feat(sqlite): harden Sqlite lifecycle/transactions/migrations/ops and add SqliteAsync pool

This commit is contained in:
faumaray committed 2026-11-26 15:17:59 +03:00
1 parent 9925ea1764
commit 427cc9a843
15 files changed
+4438 -134

No files matched your search

+461
View File
@@ -0,0 +1,461 @@
#include <Void/Sqlite/AsyncPool.hpp>
#include <atomic>
#include <condition_variable>
#include <deque>
#include <memory>
#include <mutex>
#include <stop_token>
#include <thread>
#include <utility>
#include <vector>
namespace Void::Sqlite
{
struct AsyncPool::Impl : public std::enable_shared_from_this<Impl> {
struct Job {
std::shared_ptr<Void::Async::OperationState<void>> op_state{};
std::function<Result<void>(Database&)> fn{};
std::size_t input_bytes{0};
std::uint64_t generation{0};
};
explicit Impl(AsyncPoolOptions opts, Void::Async::Executor* exec)
: options(std::move(opts)),
clock(options.clock ? options.clock
: &Void::Time::SystemMonotonicClock::instance()),
completion_executor(exec)
{
}
~Impl()
{
(void)close_and_join();
}
Result<void> start()
{
if (options.path.empty()) {
return Void::Result::fail(make_sqlite_error(
SqliteErrorCode::invalid_argument,
"AsyncPool: database path must not be empty"));
}
if (options.reader_connections > 0 &&
(options.path == ":memory:" ||
options.path.string().starts_with("file::memory:"))) {
return Void::Result::fail(make_sqlite_error(
SqliteErrorCode::invalid_argument,
"AsyncPool: multi-connection pool does not support private :memory: paths"));
}
if (options.max_queued_jobs == 0 || options.max_pending_input_bytes == 0) {
return Void::Result::fail(make_sqlite_error(
SqliteErrorCode::invalid_argument,
"AsyncPool: max_queued_jobs and max_pending_input_bytes must be positive"));
}
if (auto v = validate_limits(options.open_options.limits); !v) {
return v;
}
// Open writer first so the file and WAL mode are initialized before
// read-only connections open.
OpenOptions writer_opts = options.open_options;
if (writer_opts.mode == OpenMode::ReadOnly) {
writer_opts.mode = OpenMode::ReadWriteCreate;
}
auto wdb = Database::open_with_options(options.path, std::move(writer_opts));
if (!wdb) {
return Void::Result::fail(std::move(wdb).error());
}
writer_db = std::move(*wdb);
readers.reserve(options.reader_connections);
for (std::size_t i = 0; i < options.reader_connections; ++i) {
OpenOptions ropts = options.open_options;
ropts.mode = OpenMode::ReadOnly;
auto rdb = Database::open_with_options(options.path, std::move(ropts));
if (!rdb) {
(void)writer_db.close();
for (auto& existing : readers) {
(void)existing.close();
}
readers.clear();
return Void::Result::fail(std::move(rdb).error());
}
readers.push_back(std::move(*rdb));
}
writer_thread = std::thread([this]() { run_writer_loop(); });
reader_threads.reserve(readers.size());
for (std::size_t i = 0; i < readers.size(); ++i) {
reader_threads.emplace_back([this, i]() { run_reader_loop(i); });
}
return {};
}
Void::Coro::Task<Result<void>> submit_erased(
bool is_write,
std::function<Result<void>(Database&)> fn,
Void::Async::OperationOptions op,
std::size_t input_bytes)
{
if (!fn) {
rejected_jobs.fetch_add(1, std::memory_order_relaxed);
co_return Void::Result::fail(make_sqlite_error(
SqliteErrorCode::invalid_argument,
"AsyncPool: null work callback"));
}
if (is_write == false && readers.empty()) {
// Route read to writer lane when configured with 0 readers.
is_write = true;
}
if (op.stop.stop_requested()) {
cancelled_jobs.fetch_add(1, std::memory_order_relaxed);
co_return Void::Result::fail(make_sqlite_error(
SqliteErrorCode::cancelled,
"AsyncPool: operation cancelled before admission"));
}
if (op.deadline.has_value() && clock->now() >= *op.deadline) {
cancelled_jobs.fetch_add(1, std::memory_order_relaxed);
co_return Void::Result::fail(make_sqlite_error(
SqliteErrorCode::timeout,
"AsyncPool: operation deadline expired before admission"));
}
auto state = Void::Async::OperationState<void>::create(
op, completion_executor, Void::Async::StopBehavior::notify_only);
Job job;
job.op_state = state;
job.fn = std::move(fn);
job.input_bytes = input_bytes;
{
std::lock_guard lk{mu};
if (closing || closed) {
rejected_jobs.fetch_add(1, std::memory_order_relaxed);
co_return Void::Result::fail(make_sqlite_error(
SqliteErrorCode::closed,
"AsyncPool: pool is closing"));
}
const std::size_t total_queued = write_queue.size() + read_queue.size();
if (total_queued >= options.max_queued_jobs ||
input_bytes > options.max_pending_input_bytes ||
pending_input_bytes > options.max_pending_input_bytes - input_bytes) {
rejected_jobs.fetch_add(1, std::memory_order_relaxed);
co_return Void::Result::fail(make_sqlite_error(
SqliteErrorCode::overloaded,
"AsyncPool: queue depth or pending input byte budget exceeded"));
}
job.generation = ++next_generation;
pending_input_bytes += input_bytes;
state->acquire_backend_ref();
if (is_write) {
write_queue.push_back(std::move(job));
} else {
read_queue.push_back(std::move(job));
}
}
if (is_write) {
write_cv.notify_one();
} else {
read_cv.notify_one();
}
auto res = co_await state->awaitable(completion_executor);
co_return res;
}
void execute_job(Database& db, Job& job)
{
auto& state = job.op_state;
if (state->stop_requested()) {
cancelled_jobs.fetch_add(1, std::memory_order_relaxed);
if (auto t = state->try_commit_error(make_sqlite_error(
SqliteErrorCode::cancelled,
"AsyncPool: operation cancelled before execution"));
t) {
t->dispatch();
}
state->release_backend_ref_and_dispatch();
return;
}
if (state->is_deadline_expired(*clock)) {
cancelled_jobs.fetch_add(1, std::memory_order_relaxed);
if (auto t = state->try_commit_error(make_sqlite_error(
SqliteErrorCode::timeout,
"AsyncPool: operation deadline expired before execution"));
t) {
t->dispatch();
}
state->release_backend_ref_and_dispatch();
return;
}
const auto gen = job.generation;
const int steps = std::max(1, options.progress_handler_steps);
db.begin_leased_operation(
gen,
steps,
[state, clk = this->clock]() {
return state->stop_requested() || state->is_deadline_expired(*clk);
});
struct StopInterrupter {
Database* target_db{nullptr};
std::uint64_t target_gen{0};
void operator()() const noexcept
{
if (target_db != nullptr) {
target_db->interrupt_leased_operation(target_gen);
}
}
};
// Registered before job.fn runs and destroyed BEFORE end_leased_operation,
// so stop callbacks never race with subsequent borrowers.
Result<void> exec_result;
{
std::optional<std::stop_callback<StopInterrupter>> stop_cb;
const auto st = state->stop_token();
if (st.stop_possible()) {
stop_cb.emplace(st, StopInterrupter{&db, gen});
}
exec_result = job.fn(db);
}
db.end_leased_operation(gen);
std::optional<Void::Async::ResumeTicket> ticket;
if (exec_result) {
completed_jobs.fetch_add(1, std::memory_order_relaxed);
ticket = state->try_commit_value();
} else {
const auto kind = exec_result.error().kind();
if (kind == Void::Result::ErrorKind::cancelled ||
kind == Void::Result::ErrorKind::timeout) {
cancelled_jobs.fetch_add(1, std::memory_order_relaxed);
}
// Reclassify SQLITE_INTERRUPT when caused by deadline expiry.
if (kind == Void::Result::ErrorKind::cancelled &&
!state->stop_requested() &&
state->is_deadline_expired(*clock)) {
ticket = state->try_commit_error(make_sqlite_error(
SqliteErrorCode::timeout,
"AsyncPool: operation interrupted due to deadline expiry"));
} else {
ticket = state->try_commit_error(std::move(exec_result).error());
}
}
if (ticket) {
ticket->dispatch();
}
state->release_backend_ref_and_dispatch();
}
void run_writer_loop()
{
for (;;) {
Job job;
{
std::unique_lock lk{mu};
write_cv.wait(lk, [this]() {
return !write_queue.empty() || closing;
});
if (write_queue.empty() && closing) {
return;
}
job = std::move(write_queue.front());
write_queue.pop_front();
pending_input_bytes -= job.input_bytes;
++active_write_jobs;
}
execute_job(writer_db, job);
{
std::lock_guard lk{mu};
--active_write_jobs;
}
}
}
void run_reader_loop(std::size_t idx)
{
for (;;) {
Job job;
{
std::unique_lock lk{mu};
read_cv.wait(lk, [this]() {
return !read_queue.empty() || closing;
});
if (read_queue.empty() && closing) {
return;
}
job = std::move(read_queue.front());
read_queue.pop_front();
pending_input_bytes -= job.input_bytes;
++active_read_jobs;
}
execute_job(readers[idx], job);
{
std::lock_guard lk{mu};
--active_read_jobs;
}
}
}
Result<void> close_and_join()
{
{
std::lock_guard lk{mu};
if (closed) {
return {};
}
closing = true;
}
write_cv.notify_all();
read_cv.notify_all();
if (writer_thread.joinable()) {
writer_thread.join();
}
for (auto& t : reader_threads) {
if (t.joinable()) {
t.join();
}
}
reader_threads.clear();
std::optional<Error> first_err;
if (writer_db.is_open()) {
if (auto r = writer_db.close(); !r && !first_err) {
first_err = std::move(r).error();
}
}
for (auto& rdb : readers) {
if (rdb.is_open()) {
if (auto r = rdb.close(); !r && !first_err) {
first_err = std::move(r).error();
}
}
}
readers.clear();
{
std::lock_guard lk{mu};
closed = true;
}
if (first_err) {
return Void::Result::fail(std::move(*first_err));
}
return {};
}
AsyncPoolOptions options;
const Void::Time::MonotonicClock* clock;
Void::Async::Executor* completion_executor{nullptr};
Database writer_db{};
std::vector<Database> readers{};
mutable std::mutex mu{};
std::condition_variable write_cv{};
std::condition_variable read_cv{};
std::deque<Job> write_queue{};
std::deque<Job> read_queue{};
std::size_t pending_input_bytes{0};
std::size_t active_read_jobs{0};
std::size_t active_write_jobs{0};
std::uint64_t next_generation{0};
bool closing{false};
bool closed{false};
std::atomic<std::uint64_t> completed_jobs{0};
std::atomic<std::uint64_t> rejected_jobs{0};
std::atomic<std::uint64_t> cancelled_jobs{0};
std::thread writer_thread{};
std::vector<std::thread> reader_threads{};
};
AsyncPool::AsyncPool(std::shared_ptr<Impl> impl) noexcept
: m_impl(std::move(impl))
{
}
AsyncPool::~AsyncPool()
{
if (m_impl) {
(void)m_impl->close_and_join();
}
}
AsyncPool::AsyncPool(AsyncPool&&) noexcept = default;
AsyncPool& AsyncPool::operator=(AsyncPool&&) noexcept = default;
Result<AsyncPool> AsyncPool::open(
AsyncPoolOptions options,
Void::Async::Executor* completion_executor)
{
auto impl = std::make_shared<Impl>(std::move(options), completion_executor);
if (auto r = impl->start(); !r) {
return Void::Result::fail(std::move(r).error());
}
return AsyncPool{std::move(impl)};
}
Void::Coro::Task<Result<void>> AsyncPool::submit_erased(
bool is_write,
std::function<Result<void>(Database&)> fn,
Void::Async::OperationOptions op,
std::size_t input_bytes)
{
if (!m_impl) {
co_return Void::Result::fail(make_sqlite_error(
SqliteErrorCode::closed, "AsyncPool: moved-from pool"));
}
co_return co_await m_impl->submit_erased(
is_write, std::move(fn), std::move(op), input_bytes);
}
Void::Coro::Task<Result<void>> AsyncPool::run_read_void(
std::function<Result<void>(Database&)> fn,
Void::Async::OperationOptions op,
std::size_t input_bytes)
{
co_return co_await submit_erased(false, std::move(fn), std::move(op), input_bytes);
}
Void::Coro::Task<Result<void>> AsyncPool::run_write_void(
std::function<Result<void>(Database&)> fn,
Void::Async::OperationOptions op,
std::size_t input_bytes)
{
co_return co_await submit_erased(true, std::move(fn), std::move(op), input_bytes);
}
AsyncPoolStats AsyncPool::stats() const noexcept
{
AsyncPoolStats out;
if (!m_impl) return out;
std::lock_guard lk{m_impl->mu};
out.reader_connections = m_impl->readers.size();
out.queued_read_jobs = m_impl->read_queue.size();
out.queued_write_jobs = m_impl->write_queue.size();
out.active_read_jobs = m_impl->active_read_jobs;
out.active_write_jobs = m_impl->active_write_jobs;
out.pending_input_bytes = m_impl->pending_input_bytes;
out.completed_jobs = m_impl->completed_jobs.load(std::memory_order_relaxed);
out.rejected_jobs = m_impl->rejected_jobs.load(std::memory_order_relaxed);
out.cancelled_jobs = m_impl->cancelled_jobs.load(std::memory_order_relaxed);
return out;
}
Result<void> AsyncPool::close_and_join()
{
if (!m_impl) return {};
return m_impl->close_and_join();
}
} // namespace Void::Sqlite
+4
View File
@@ -0,0 +1,4 @@
void_add_module(SqliteAsync
INTERNAL_DEPS Sqlite Async Time Functional
EXTRA_HEADERS Void/Sqlite/AsyncPool.hpp
)