Skip to content
Draft
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
101 changes: 86 additions & 15 deletions packages/nitro-sqlite-core/cpp/SQLiteDatabaseConnections.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -2,14 +2,16 @@
#include "SQLiteDatabaseMigration.hpp"
#include "SQLiteException.hpp"
#include "SQLiteLogs.hpp"
#include "SQLiteOperationCancellation.hpp"
#include <algorithm>
#include <array>
#include <condition_variable>
#include <cstring>
#include <deque>
#include <exception>
#include <filesystem>
#include <fstream>
#include <memory>
#include <queue>
#include <stdexcept>
#include <unordered_map>
#include <vector>
Expand Down Expand Up @@ -39,8 +41,21 @@ namespace {
return state;
}

int readOnlyAuthorizer(void*, int action, const char*, const char*, const char*, const char*) {
return action == SQLITE_ATTACH ? SQLITE_DENY : SQLITE_OK;
int authorizeStatement(void* context, int action, const char*, const char* detail, const char*, const char*) {
const auto& connection = *static_cast<SQLiteConnection*>(context);
if (!connection.isCancellableRead) {
return connection.readOnly && action == SQLITE_ATTACH ? SQLITE_DENY : SQLITE_OK;
}
switch (action) {
case SQLITE_SELECT:
case SQLITE_READ:
case SQLITE_RECURSIVE:
return SQLITE_OK;
case SQLITE_FUNCTION:
return detail != nullptr && sqlite3_stricmp(detail, "load_extension") == 0 ? SQLITE_DENY : SQLITE_OK;
default:
return SQLITE_DENY;
}
}

struct IndependentId {
Expand Down Expand Up @@ -164,7 +179,12 @@ struct SerialWorker::State {
const std::string name;
std::mutex mutex;
std::condition_variable condition;
std::queue<std::function<void()>> operations;
struct Job {
std::function<void()> operation;
std::shared_ptr<SQLiteOperationCancellation> cancellation;
std::function<void()> onCancelled;
};
std::deque<Job> operations;
bool stopping = false;
};

Expand All @@ -176,25 +196,27 @@ SerialWorker::SerialWorker(std::string name) : _state(std::make_shared<State>(st
facebook::jni::ThreadScope jniScope;
#endif
while (true) {
std::function<void()> operation;
State::Job job;
{
std::unique_lock lock(state->mutex);
state->condition.wait(lock, [&] { return state->stopping || !state->operations.empty(); });
if (state->operations.empty()) {
return;
}
operation = std::move(state->operations.front());
state->operations.pop();
job = std::move(state->operations.front());
state->operations.pop_front();
}
try {
operation();
if (job.cancellation && job.cancellation->isCancelled()) {
job.onCancelled();
} else {
job.operation();
}
} catch (const std::exception& error) {
LOGE("Async operation on database %s failed while settling its promise: %s", state->name.c_str(), error.what());
} catch (...) {
LOGE("Async operation on database %s failed while settling its promise", state->name.c_str());
}
// Releasing the operation may drop the last reference to the connection that owns this worker.
operation = nullptr;
}
});
}
Expand All @@ -215,11 +237,52 @@ SerialWorker::~SerialWorker() {
void SerialWorker::enqueue(std::function<void()> operation) {
{
std::lock_guard lock(_state->mutex);
_state->operations.push(std::move(operation));
_state->operations.push_back({std::move(operation), nullptr, nullptr});
}
_state->condition.notify_one();
}

void SerialWorker::enqueue(std::function<void()> operation, const std::shared_ptr<SQLiteOperationCancellation>& cancellation,
std::function<void()> onCancelled) {
onCancelled = [name = _state->name, settle = std::move(onCancelled)] {
try {
settle();
} catch (const std::exception& error) {
LOGE("Cancelled operation on database %s failed while settling its promise: %s", name.c_str(), error.what());
} catch (...) {
LOGE("Cancelled operation on database %s failed while settling its promise", name.c_str());
}
};
const auto remove = [weakState = std::weak_ptr(_state), token = cancellation.get()] {
const auto state = weakState.lock();
if (!state) {
return;
}
State::Job cancelled;
{
std::lock_guard lock(state->mutex);
const auto job = std::find_if(state->operations.begin(), state->operations.end(),
[token](const auto& candidate) { return candidate.cancellation.get() == token; });
if (job == state->operations.end()) {
return;
}
cancelled = std::move(*job);
state->operations.erase(job);
}
cancelled.onCancelled();
};

{
std::lock_guard lock(_state->mutex);
if (cancellation->submit(remove)) {
_state->operations.push_back({std::move(operation), cancellation, std::move(onCancelled)});
_state->condition.notify_one();
return;
}
}
onCancelled();
}

namespace {

// SQLite calls this for each changed row while the stepping thread holds the connection's mutex.
Expand Down Expand Up @@ -250,6 +313,8 @@ namespace {

SQLiteConnection::SQLiteConnection(std::string connectionName, fs::path path, bool isReadOnly, sqlite3* handle)
: name(std::move(connectionName)), physicalPath(canonicalDatabasePath(path)), readOnly(isReadOnly), database(handle) {
// Replacing an authorizer expires every statement, so install it only once.
sqlite3_set_authorizer(database, authorizeStatement, this);
// Installed once, before any other thread can use the handle. They only record while a handler is set.
sqlite3_update_hook(database, recordChange, this);
sqlite3_rollback_hook(database, discardChanges, this);
Expand All @@ -269,11 +334,20 @@ void SQLiteConnection::requireActiveTransaction() const {
}

void SQLiteConnection::enqueueAsync(std::function<void()>&& operation) {
worker().enqueue(std::move(operation));
}

void SQLiteConnection::enqueueAsync(std::function<void()>&& operation, const std::shared_ptr<SQLiteOperationCancellation>& cancellation,
std::function<void()> onCancelled) {
worker().enqueue(std::move(operation), cancellation, std::move(onCancelled));
}

SerialWorker& SQLiteConnection::worker() {
std::lock_guard lock(asyncWorkerMutex);
if (!asyncWorker) {
asyncWorker = std::make_unique<SerialWorker>(name);
}
asyncWorker->enqueue(std::move(operation));
return *asyncWorker;
}

void SQLiteConnection::setChangeHandler(std::optional<SQLiteChangeHandler> handler) {
Expand Down Expand Up @@ -387,9 +461,6 @@ void DatabaseConnections::openKey(const std::string& key, const fs::path& path,
throw SQLiteException(SQLiteExceptionType::DatabaseCannotBeOpened, message);
}
applyEncryptionKey(database.get(), encryptionKey);
if (readOnly) {
sqlite3_set_authorizer(database.get(), readOnlyAuthorizer, nullptr);
}
auto connection = std::make_shared<SQLiteConnection>(connectionLabel(key), physicalPath, readOnly, database.get());
database.release();
auto& liveConnections = processConnections().connections;
Expand Down
14 changes: 14 additions & 0 deletions packages/nitro-sqlite-core/cpp/SQLiteDatabaseConnections.hpp
Original file line number Diff line number Diff line change
Expand Up @@ -19,6 +19,8 @@

namespace margelo::nitro::nitrosqlite {

class SQLiteOperationCancellation;

/** Runs operations in FIFO order on one dedicated thread. */
class SerialWorker final {
public:
Expand All @@ -32,6 +34,12 @@ class SerialWorker final {

/** Queue an operation. Exceptions it throws are logged and dropped. */
void enqueue(std::function<void()> operation);
/** Queue a single-use cancellable operation. @p onCancelled runs once if the job is cancelled before execution.
* It may run on the submitting, cancelling, or worker thread. Its exceptions are logged and dropped,
* like exceptions from @p operation. A callback that throws is not retried.
*/
void enqueue(std::function<void()> operation, const std::shared_ptr<SQLiteOperationCancellation>& cancellation,
std::function<void()> onCancelled);

private:
struct State;
Expand Down Expand Up @@ -64,6 +72,11 @@ struct SQLiteConnection final {
void close() noexcept;
/** Submit an operation to this connection's native FIFO worker. */
void enqueueAsync(std::function<void()>&& operation);
/** Submit an operation that can be removed before it starts. */
void enqueueAsync(std::function<void()>&& operation, const std::shared_ptr<SQLiteOperationCancellation>& cancellation,
std::function<void()> onCancelled);
/** Whether the installed authorizer must reject non-read actions. Guarded by mutex. */
bool isCancellableRead = false;
/** Send committed row changes to @p handler, or stop recording them with std::nullopt.
* A replacement handler receives only changes recorded after its registration. Does not wait
* for the connection's running operation.
Expand Down Expand Up @@ -95,6 +108,7 @@ struct SQLiteConnection final {
std::atomic<uint64_t> changeHandlerGeneration = 0;

private:
SerialWorker& worker();
// Separate from mutex so that registering a handler never waits for a running query.
std::mutex changeHandlerMutex;
std::optional<SQLiteChangeHandler> changeHandler;
Expand Down
12 changes: 10 additions & 2 deletions packages/nitro-sqlite-core/cpp/SQLiteException.hpp
Original file line number Diff line number Diff line change
Expand Up @@ -4,6 +4,7 @@
#include <iostream>
#include <optional>
#include <string>
#include <unordered_map>

const std::string NITRO_SQLITE_EXCEPTION_PREFIX = "[NativeNitroSQLiteException]";

Expand All @@ -16,7 +17,8 @@ enum SQLiteExceptionType {
UnableToAttachToDatabase,
SqlExecutionError,
CouldNotLoadFile,
NoBatchCommandsProvided
NoBatchCommandsProvided,
OperationCancelled
};

inline std::unordered_map<SQLiteExceptionType, std::string> exceptionTypeStrings = {
Expand All @@ -28,7 +30,8 @@ inline std::unordered_map<SQLiteExceptionType, std::string> exceptionTypeStrings
{UnableToAttachToDatabase, "UnableToAttachToDatabase"},
{SqlExecutionError, "SqlExecutionError"},
{CouldNotLoadFile, "CouldNotLoadFile"},
{NoBatchCommandsProvided, "NoBatchCommandsProvided"}};
{NoBatchCommandsProvided, "NoBatchCommandsProvided"},
{OperationCancelled, "OperationCancelled"}};

inline std::string typeToString(SQLiteExceptionType type) {
return exceptionTypeStrings[type];
Expand Down Expand Up @@ -63,6 +66,11 @@ class SQLiteException : public std::exception {
return SQLiteException(SQLiteExceptionType::SqlExecutionError, errorMessage);
}

/** The caller cancelled a queued or running SQLite read. */
static SQLiteException Cancelled() {
return SQLiteException(SQLiteExceptionType::OperationCancelled, "SQLite read was cancelled");
}

static SQLiteException DatabaseFileNotFound(const std::string& dbFilePath) {
return SQLiteException(SQLiteExceptionType::SqlExecutionError, "Database file not found: " + dbFilePath);
}
Expand Down
95 changes: 95 additions & 0 deletions packages/nitro-sqlite-core/cpp/SQLiteOperationCancellation.hpp
Original file line number Diff line number Diff line change
@@ -0,0 +1,95 @@
#pragma once

#include "SQLiteException.hpp"
#include "sqlite/sqlite3.h"
#include <atomic>
#include <functional>
#include <mutex>
#include <utility>

namespace margelo::nitro::nitrosqlite {

/** Single-use cancellation shared by the submitter and the connection's worker. */
class SQLiteOperationCancellation final {
public:
/** Register the removal callback. Returns false if cancellation already won. */
bool submit(std::function<void()> removeFromQueue) {
std::lock_guard lock(_mutex);
if (_isSubmitted) {
throw SQLiteException::SqlExecution("A cancellation token can only be used once");
}
_isSubmitted = true;
if (isCancelled()) {
return false;
}
_removeFromQueue = std::move(removeFromQueue);
return true;
}

/** Remove a queued job, or interrupt this operation's live SQLite handle. */
void cancel() {
std::function<void()> removeFromQueue;
{
std::lock_guard lock(_mutex);
if (_state != State::Pending) {
return;
}
_state = State::Cancelled;
if (_activeDatabase != nullptr) {
sqlite3_interrupt(_activeDatabase);
}
removeFromQueue = std::move(_removeFromQueue);
}
if (removeFromQueue) {
removeFromQueue();
}
}

/** Commit the operation's result or error once. Returns false if already finished or cancelled. */
bool finish() {
std::lock_guard lock(_mutex);
if (_state != State::Pending) {
return false;
}
_state = State::Finished;
_removeFromQueue = nullptr;
return true;
}

/** Whether cancellation won against completion. */
bool isCancelled() const noexcept {
return _state.load() == State::Cancelled;
}

/** Throw the operation-specific error if cancelled. */
void throwIfCancelled() const {
if (isCancelled()) {
throw SQLiteException::Cancelled();
}
}

/** Enable interrupts once the worker has started a statement on @p database. The
* caller holds the connection lock until deactivate() has returned.
*/
void activate(sqlite3* database) {
std::lock_guard lock(_mutex);
throwIfCancelled();
_activeDatabase = database;
}

/** Wait for any concurrent interrupt and clear the handle before it can close. */
void deactivate() {
std::lock_guard lock(_mutex);
_activeDatabase = nullptr;
}

private:
enum class State { Pending, Cancelled, Finished };
std::atomic<State> _state = State::Pending;
std::mutex _mutex;
bool _isSubmitted = false;
sqlite3* _activeDatabase = nullptr;
std::function<void()> _removeFromQueue;
};

} // namespace margelo::nitro::nitrosqlite
Loading