Files
Library/examples/platforms/networked-kv/src/sqlite_store.cpp
T

532 lines
15 KiB
C++

#include "networked_kv/sqlite_store.hpp"
#include <Void/Sqlite/Types.hpp>
#include <algorithm>
#include <cstdint>
#include <mutex>
#include <string>
#include <utility>
#include <vector>
namespace NetworkedKv
{
using Void::Sqlite::BeginMode;
using Void::Sqlite::ValueView;
namespace
{
[[nodiscard]] Void::Result::Error invalid(std::string message)
{
return Void::Result::Error{Void::Result::ErrorKind::invalid_argument,
std::move(message)};
}
[[nodiscard]] int outcome_to_int(WriteOutcome outcome) noexcept
{
return static_cast<int>(outcome);
}
[[nodiscard]] WriteOutcome outcome_from_int(int value) noexcept
{
switch (value) {
case 0: return WriteOutcome::Applied;
case 1: return WriteOutcome::Conflict;
case 2: return WriteOutcome::NotFound;
default: return WriteOutcome::Unknown;
}
}
[[nodiscard]] bool matches(const std::optional<Entry>& current,
const Precondition& precondition) noexcept
{
if (precondition.kind == PreconditionKind::Absent) {
return !current.has_value();
}
return current.has_value() &&
current->version == precondition.version;
}
[[nodiscard]] ValueView blob_view(std::string_view value) noexcept
{
return ValueView{std::span<const std::byte>{
reinterpret_cast<const std::byte*>(value.data()), value.size()}};
}
} // namespace
SqliteKvStore::SqliteKvStore(Void::Sqlite::Database database, Limits limits)
: m_db(std::move(database))
, m_limits(limits)
{
}
Void::Result::Result<void> SqliteKvStore::ensure_schema()
{
if (auto wal = m_db.exec("PRAGMA journal_mode=WAL"); !wal) {
return std::unexpected{std::move(wal).error()};
}
if (auto kv = m_db.exec(
"CREATE TABLE IF NOT EXISTS kv("
"key TEXT PRIMARY KEY, value BLOB NOT NULL, version INTEGER NOT NULL)");
!kv) {
return std::unexpected{std::move(kv).error()};
}
if (auto ops = m_db.exec(
"CREATE TABLE IF NOT EXISTS operations("
"request_id TEXT PRIMARY KEY, outcome INTEGER NOT NULL, "
"version INTEGER NOT NULL)");
!ops) {
return std::unexpected{std::move(ops).error()};
}
return {};
}
Void::Result::Result<std::unique_ptr<SqliteKvStore>>
SqliteKvStore::open(const std::filesystem::path& path, Limits limits)
{
auto database = Void::Sqlite::Database::open(path);
if (!database) {
return std::unexpected{std::move(database).error()};
}
std::unique_ptr<SqliteKvStore> store{
new SqliteKvStore{std::move(*database), limits}};
if (auto schema = store->ensure_schema(); !schema) {
return std::unexpected{std::move(schema).error()};
}
return store;
}
Void::Result::Result<std::optional<Entry>>
SqliteKvStore::get(std::string_view key) const
{
if (key.empty() || key.size() > m_limits.max_key_bytes) {
return std::unexpected{invalid("KvStore: invalid key")};
}
std::lock_guard lock{m_mutex};
auto statement = m_db.prepare("SELECT value, version FROM kv WHERE key = ?");
if (!statement) {
return std::unexpected{std::move(statement).error()};
}
if (auto bound = statement->bind_checked(1, ValueView{key}); !bound) {
return std::unexpected{std::move(bound).error()};
}
auto row = statement->step();
if (!row) {
return std::unexpected{std::move(row).error()};
}
if (!*row) {
return std::optional<Entry>{};
}
auto value = statement->try_column_blob(0);
auto version = statement->try_column_int(1);
if (!value || !version) {
return std::unexpected{invalid("KvStore: malformed row")};
}
Entry entry;
entry.value.assign(reinterpret_cast<const char*>(value->data()),
value->size());
entry.version = static_cast<Version>(*version);
return std::optional<Entry>{std::move(entry)};
}
Void::Result::Result<WriteResult>
SqliteKvStore::put(std::string_view key, std::string value,
Precondition precondition, RequestId request)
{
if (key.empty() || key.size() > m_limits.max_key_bytes) {
return std::unexpected{invalid("KvStore: invalid key")};
}
if (request.value.empty() ||
request.value.size() > m_limits.max_request_id_bytes) {
return std::unexpected{invalid("KvStore: invalid request id")};
}
if (value.size() > m_limits.max_value_bytes) {
return std::unexpected{invalid("KvStore: value too large")};
}
std::lock_guard lock{m_mutex};
auto transaction = m_db.begin(Void::Sqlite::BeginMode::Immediate);
if (!transaction) {
return std::unexpected{std::move(transaction).error()};
}
const auto rollback = [&] { (void)transaction->rollback_checked(); };
// Idempotent replay.
{
auto replay = m_db.prepare(
"SELECT outcome, version FROM operations WHERE request_id = ?");
if (!replay) {
rollback();
return std::unexpected{std::move(replay).error()};
}
if (auto bound =
replay->bind_checked(1, ValueView{request.value});
!bound) {
rollback();
return std::unexpected{std::move(bound).error()};
}
auto row = replay->step();
if (!row) {
rollback();
return std::unexpected{std::move(row).error()};
}
if (*row) {
auto outcome = replay->try_column_int(0);
auto version = replay->try_column_int(1);
if (!outcome || !version) {
rollback();
return std::unexpected{invalid("KvStore: malformed operation")};
}
if (auto committed = transaction->commit(); !committed) {
return std::unexpected{std::move(committed).error()};
}
return WriteResult{outcome_from_int(
static_cast<int>(*outcome)),
static_cast<Version>(*version)};
}
}
std::optional<Entry> current;
{
auto existing =
m_db.prepare("SELECT value, version FROM kv WHERE key = ?");
if (!existing) {
rollback();
return std::unexpected{std::move(existing).error()};
}
if (auto bound = existing->bind_checked(1, ValueView{key}); !bound) {
rollback();
return std::unexpected{std::move(bound).error()};
}
auto row = existing->step();
if (!row) {
rollback();
return std::unexpected{std::move(row).error()};
}
if (*row) {
auto version = existing->try_column_int(1);
if (!version) {
rollback();
return std::unexpected{invalid("KvStore: malformed row")};
}
current = Entry{{}, static_cast<Version>(*version)};
}
}
WriteResult result;
if (!matches(current, precondition)) {
result = WriteResult{WriteOutcome::Conflict,
current ? current->version : 0};
} else {
const Version version = current ? current->version + 1 : 1;
auto upsert = m_db.prepare(
"INSERT INTO kv(key, value, version) VALUES(?, ?, ?) "
"ON CONFLICT(key) DO UPDATE SET "
"value = excluded.value, version = excluded.version");
if (!upsert) {
rollback();
return std::unexpected{std::move(upsert).error()};
}
if (auto bound = upsert->bind_checked(1, ValueView{key}); !bound) {
rollback();
return std::unexpected{std::move(bound).error()};
}
if (auto bound = upsert->bind_checked(2, blob_view(value)); !bound) {
rollback();
return std::unexpected{std::move(bound).error()};
}
if (auto bound = upsert->bind_checked(
3, ValueView{static_cast<std::int64_t>(version)});
!bound) {
rollback();
return std::unexpected{std::move(bound).error()};
}
auto stepped = upsert->step();
if (!stepped) {
rollback();
return std::unexpected{std::move(stepped).error()};
}
result = WriteResult{WriteOutcome::Applied, version};
}
{
auto record = m_db.prepare(
"INSERT INTO operations(request_id, outcome, version) "
"VALUES(?, ?, ?)");
if (!record) {
rollback();
return std::unexpected{std::move(record).error()};
}
if (auto bound =
record->bind_checked(1, ValueView{request.value});
!bound) {
rollback();
return std::unexpected{std::move(bound).error()};
}
if (auto bound = record->bind_checked(
2, ValueView{outcome_to_int(result.outcome)});
!bound) {
rollback();
return std::unexpected{std::move(bound).error()};
}
if (auto bound = record->bind_checked(
3, ValueView{static_cast<std::int64_t>(result.version)});
!bound) {
rollback();
return std::unexpected{std::move(bound).error()};
}
auto stepped = record->step();
if (!stepped) {
rollback();
return std::unexpected{std::move(stepped).error()};
}
}
if (auto committed = transaction->commit(); !committed) {
return std::unexpected{std::move(committed).error()};
}
return result;
}
Void::Result::Result<WriteResult>
SqliteKvStore::erase(std::string_view key, Precondition precondition,
RequestId request)
{
if (key.empty() || key.size() > m_limits.max_key_bytes) {
return std::unexpected{invalid("KvStore: invalid key")};
}
if (request.value.empty() ||
request.value.size() > m_limits.max_request_id_bytes) {
return std::unexpected{invalid("KvStore: invalid request id")};
}
std::lock_guard lock{m_mutex};
auto transaction = m_db.begin(Void::Sqlite::BeginMode::Immediate);
if (!transaction) {
return std::unexpected{std::move(transaction).error()};
}
const auto rollback = [&] { (void)transaction->rollback_checked(); };
{
auto replay = m_db.prepare(
"SELECT outcome, version FROM operations WHERE request_id = ?");
if (!replay) {
rollback();
return std::unexpected{std::move(replay).error()};
}
if (auto bound =
replay->bind_checked(1, ValueView{request.value});
!bound) {
rollback();
return std::unexpected{std::move(bound).error()};
}
auto row = replay->step();
if (!row) {
rollback();
return std::unexpected{std::move(row).error()};
}
if (*row) {
auto outcome = replay->try_column_int(0);
auto version = replay->try_column_int(1);
if (!outcome || !version) {
rollback();
return std::unexpected{invalid("KvStore: malformed operation")};
}
if (auto committed = transaction->commit(); !committed) {
return std::unexpected{std::move(committed).error()};
}
return WriteResult{outcome_from_int(
static_cast<int>(*outcome)),
static_cast<Version>(*version)};
}
}
std::optional<Version> current;
{
auto existing = m_db.prepare("SELECT version FROM kv WHERE key = ?");
if (!existing) {
rollback();
return std::unexpected{std::move(existing).error()};
}
if (auto bound = existing->bind_checked(1, ValueView{key}); !bound) {
rollback();
return std::unexpected{std::move(bound).error()};
}
auto row = existing->step();
if (!row) {
rollback();
return std::unexpected{std::move(row).error()};
}
if (*row) {
auto version = existing->try_column_int(0);
if (!version) {
rollback();
return std::unexpected{invalid("KvStore: malformed row")};
}
current = static_cast<Version>(*version);
}
}
WriteResult result;
if (!current) {
result = WriteResult{WriteOutcome::NotFound, 0};
} else if (precondition.kind == PreconditionKind::Version &&
*current != precondition.version) {
result = WriteResult{WriteOutcome::Conflict, *current};
} else if (precondition.kind == PreconditionKind::Absent) {
result = WriteResult{WriteOutcome::Conflict, *current};
} else {
auto remove = m_db.prepare("DELETE FROM kv WHERE key = ?");
if (!remove) {
rollback();
return std::unexpected{std::move(remove).error()};
}
if (auto bound = remove->bind_checked(1, ValueView{key}); !bound) {
rollback();
return std::unexpected{std::move(bound).error()};
}
auto stepped = remove->step();
if (!stepped) {
rollback();
return std::unexpected{std::move(stepped).error()};
}
result = WriteResult{WriteOutcome::Applied, 0};
}
{
auto record = m_db.prepare(
"INSERT INTO operations(request_id, outcome, version) "
"VALUES(?, ?, ?)");
if (!record) {
rollback();
return std::unexpected{std::move(record).error()};
}
(void)record->bind_checked(1, ValueView{request.value});
(void)record->bind_checked(
2, ValueView{outcome_to_int(result.outcome)});
(void)record->bind_checked(
3, ValueView{static_cast<std::int64_t>(result.version)});
if (auto stepped = record->step(); !stepped) {
rollback();
return std::unexpected{std::move(stepped).error()};
}
}
if (auto committed = transaction->commit(); !committed) {
return std::unexpected{std::move(committed).error()};
}
return result;
}
Void::Result::Result<ScanPage>
SqliteKvStore::scan(std::optional<std::string_view> cursor,
std::size_t limit) const
{
const std::size_t page =
std::min(limit == 0 ? m_limits.max_scan_page : limit,
m_limits.max_scan_page);
if (page == 0) {
return ScanPage{};
}
std::lock_guard lock{m_mutex};
auto statement = m_db.prepare(
"SELECT key, value, version FROM kv WHERE key > ? "
"ORDER BY key LIMIT ?");
if (!statement) {
return std::unexpected{std::move(statement).error()};
}
if (auto bound = statement->bind_checked(
1, ValueView{cursor.value_or(std::string_view{})});
!bound) {
return std::unexpected{std::move(bound).error()};
}
if (auto bound = statement->bind_checked(
2, ValueView{static_cast<std::int64_t>(page + 1)});
!bound) {
return std::unexpected{std::move(bound).error()};
}
ScanPage out;
while (true) {
auto row = statement->step();
if (!row) {
return std::unexpected{std::move(row).error()};
}
if (!*row) {
break;
}
auto key = statement->try_column_text(0);
auto value = statement->try_column_blob(1);
auto version = statement->try_column_int(2);
if (!key || !value || !version) {
return std::unexpected{invalid("KvStore: malformed scan row")};
}
if (out.items.size() == page) {
out.next_cursor = out.items.back().key;
break;
}
Entry entry;
entry.value.assign(reinterpret_cast<const char*>(value->data()),
value->size());
entry.version = static_cast<Version>(*version);
out.items.push_back(
ScanItem{std::string{*key}, std::move(entry)});
}
return out;
}
} // namespace NetworkedKv
namespace NetworkedKv
{
Void::Result::Result<Void::Sqlite::BackupReport>
SqliteKvStore::backup_to(const std::filesystem::path& destination)
{
std::lock_guard lock{m_mutex};
return m_db.backup_to(destination);
}
Void::Result::Result<Void::Sqlite::BackupReport>
SqliteKvStore::restore_from(const std::filesystem::path& source)
{
std::lock_guard lock{m_mutex};
return m_db.restore_from(source);
}
} // namespace NetworkedKv
namespace NetworkedKv
{
Void::Result::Result<std::optional<WriteResult>>
SqliteKvStore::lookup_operation(const RequestId& request) const
{
if (request.value.empty() ||
request.value.size() > m_limits.max_request_id_bytes) {
return std::unexpected{invalid("KvStore: invalid request id")};
}
std::lock_guard lock{m_mutex};
auto statement = m_db.prepare(
"SELECT outcome, version FROM operations WHERE request_id = ?");
if (!statement) {
return std::unexpected{std::move(statement).error()};
}
if (auto bound = statement->bind_checked(1, ValueView{request.value});
!bound) {
return std::unexpected{std::move(bound).error()};
}
auto row = statement->step();
if (!row) {
return std::unexpected{std::move(row).error()};
}
if (!*row) {
return std::optional<WriteResult>{};
}
auto outcome = statement->try_column_int(0);
auto version = statement->try_column_int(1);
if (!outcome || !version) {
return std::unexpected{invalid("KvStore: malformed operation")};
}
return std::optional<WriteResult>{WriteResult{
outcome_from_int(static_cast<int>(*outcome)),
static_cast<Version>(*version)}};
}
} // namespace NetworkedKv