mirror of
https://github.com/allankoechke/turso.git
synced 2026-11-30 11:12:58 +00:00
bindings/dotnet: add managed pull replica API
Expose the minimum managed embedded-replica lifecycle on top of the native sync ABI: create or open a replica, connect locally, and pull remote changes safely. Drive HTTP and file I/O with cancellation while coordinating local statement, reader, connection, and database lifetimes. Advanced sync configuration, push, checkpoint, and statistics remain deferred to focused follow-up changes.
This commit is contained in:
@@ -123,7 +123,24 @@ batch.BatchCommands.Add(select);
|
||||
await using var reader = await batch.ExecuteReaderAsync();
|
||||
```
|
||||
|
||||
Embedded replicas are not enabled yet in the .NET provider. `Replica Path` and `Sync Interval` are parsed so applications fail early with clear errors, and `TursoConnection.Sync()` / `SyncAsync(CancellationToken)` are reserved for that mode once `turso_sync_sdk_kit` is packaged and wired through .NET.
|
||||
Use `TursoSyncDatabase` when an application needs an embedded replica with explicit pull control:
|
||||
|
||||
```C#
|
||||
var options = new TursoSyncDatabaseOptions(
|
||||
"./replica.db",
|
||||
new Uri("turso://example-org.turso.io"))
|
||||
{
|
||||
AuthToken = authToken,
|
||||
};
|
||||
|
||||
await using var database = await TursoSyncDatabase.CreateAsync(options);
|
||||
await using var local = await database.ConnectAsync();
|
||||
var changed = await database.PullAsync();
|
||||
```
|
||||
|
||||
`PullAsync` never pushes local writes. Sync failures are `TursoSyncException` values carrying the operation, native status, sanitized endpoint, HTTP method/status, and original exception.
|
||||
|
||||
Push, checkpoint, statistics, partial sync, remote encryption, connection-string replica integration, pooling, and automatic synchronization are not enabled yet. Use the explicit `TursoSyncDatabase` API for managed pull replicas.
|
||||
|
||||
Provider factories are available through `TursoFactory.Instance`:
|
||||
|
||||
|
||||
@@ -0,0 +1,3 @@
|
||||
using System.Runtime.CompilerServices;
|
||||
|
||||
[assembly: InternalsVisibleTo("Turso.Tests")]
|
||||
@@ -150,6 +150,12 @@ public class TursoCommand : DbCommand
|
||||
}
|
||||
|
||||
public override void Prepare()
|
||||
{
|
||||
using var syncOperation = _connection?.EnterSyncOperation();
|
||||
PrepareCore();
|
||||
}
|
||||
|
||||
private void PrepareCore()
|
||||
{
|
||||
if (_connection is null)
|
||||
throw new InvalidOperationException("Connection must be set before preparing a command.");
|
||||
@@ -273,12 +279,29 @@ public class TursoCommand : DbCommand
|
||||
if (_connection.IsRemote)
|
||||
return ExecuteRemoteAsync(behavior, CancellationToken.None).GetAwaiter().GetResult();
|
||||
|
||||
Prepare();
|
||||
IDisposable? syncOperation = _connection.EnterSyncOperation();
|
||||
try
|
||||
{
|
||||
PrepareCore();
|
||||
|
||||
var statement = _statement ?? throw new InvalidOperationException("Command was not prepared.");
|
||||
_statement = null;
|
||||
var reader = new TursoDataReader(this, statement, behavior);
|
||||
return reader;
|
||||
var statement = _statement ?? throw new InvalidOperationException("Command was not prepared.");
|
||||
_statement = null;
|
||||
try
|
||||
{
|
||||
var reader = new TursoDataReader(this, statement, behavior, syncOperation);
|
||||
syncOperation = null;
|
||||
return reader;
|
||||
}
|
||||
catch
|
||||
{
|
||||
statement.Dispose();
|
||||
throw;
|
||||
}
|
||||
}
|
||||
finally
|
||||
{
|
||||
syncOperation?.Dispose();
|
||||
}
|
||||
}
|
||||
|
||||
private async Task<DbDataReader> ExecuteRemoteAsync(CommandBehavior behavior, CancellationToken cancellationToken)
|
||||
|
||||
@@ -10,8 +10,12 @@ public class TursoConnection : DbConnection
|
||||
{
|
||||
private TursoDatabaseHandle? _turso;
|
||||
private TursoRemoteClient? _remoteClient;
|
||||
private TursoSyncDatabase? _syncDatabase;
|
||||
private readonly HashSet<TursoDataReader> _syncReaders = [];
|
||||
private readonly object _syncReadersLock = new();
|
||||
private TursoConnectionOptions _connectionOptions;
|
||||
private bool _disposed;
|
||||
private bool _closing;
|
||||
private bool _readUncommitted;
|
||||
private bool _remoteTransactionActive;
|
||||
|
||||
@@ -93,15 +97,30 @@ public class TursoConnection : DbConnection
|
||||
|
||||
public override void Close()
|
||||
{
|
||||
if (_remoteClient is not null)
|
||||
{
|
||||
CloseRemote();
|
||||
if (_closing)
|
||||
return;
|
||||
}
|
||||
|
||||
_turso?.Dispose();
|
||||
_turso = null;
|
||||
_readUncommitted = false;
|
||||
_syncDatabase?.ThrowIfIoReentrant();
|
||||
_closing = true;
|
||||
try
|
||||
{
|
||||
if (_remoteClient is not null)
|
||||
{
|
||||
CloseRemote();
|
||||
return;
|
||||
}
|
||||
|
||||
CloseSyncReaders();
|
||||
using (_syncDatabase?.EnterConnectionOperation())
|
||||
_turso?.Dispose();
|
||||
_turso = null;
|
||||
ReleaseSyncDatabase();
|
||||
_readUncommitted = false;
|
||||
}
|
||||
finally
|
||||
{
|
||||
_closing = false;
|
||||
}
|
||||
}
|
||||
|
||||
protected override void Dispose(bool disposing)
|
||||
@@ -179,6 +198,41 @@ public class TursoConnection : DbConnection
|
||||
|
||||
internal TursoDatabaseHandle Turso => _turso ?? throw new InvalidOperationException("Turso database is closed.");
|
||||
|
||||
internal static TursoConnection CreateSyncConnection(
|
||||
TursoDatabaseHandle connectionHandle,
|
||||
TursoSyncDatabase syncDatabase)
|
||||
{
|
||||
ArgumentNullException.ThrowIfNull(connectionHandle);
|
||||
ArgumentNullException.ThrowIfNull(syncDatabase);
|
||||
return new TursoConnection
|
||||
{
|
||||
_turso = connectionHandle,
|
||||
_syncDatabase = syncDatabase,
|
||||
};
|
||||
}
|
||||
|
||||
internal void RunExternalIo()
|
||||
{
|
||||
_syncDatabase?.ProcessOneIo();
|
||||
}
|
||||
|
||||
internal IDisposable? EnterSyncOperation()
|
||||
{
|
||||
return _syncDatabase?.EnterConnectionOperation();
|
||||
}
|
||||
|
||||
internal void RegisterSyncReader(TursoDataReader reader)
|
||||
{
|
||||
lock (_syncReadersLock)
|
||||
_syncReaders.Add(reader);
|
||||
}
|
||||
|
||||
internal void UnregisterSyncReader(TursoDataReader reader)
|
||||
{
|
||||
lock (_syncReadersLock)
|
||||
_syncReaders.Remove(reader);
|
||||
}
|
||||
|
||||
internal async Task<RemoteStatementResult> ExecuteRemoteAsync(
|
||||
string sql,
|
||||
TursoParameterCollection parameters,
|
||||
@@ -387,4 +441,24 @@ public class TursoConnection : DbConnection
|
||||
_remoteTransactionActive = false;
|
||||
_readUncommitted = false;
|
||||
}
|
||||
|
||||
private void ReleaseSyncDatabase()
|
||||
{
|
||||
var syncDatabase = _syncDatabase;
|
||||
if (syncDatabase is null)
|
||||
return;
|
||||
|
||||
_syncDatabase = null;
|
||||
syncDatabase.ReleaseConnection();
|
||||
}
|
||||
|
||||
private void CloseSyncReaders()
|
||||
{
|
||||
TursoDataReader[] readers;
|
||||
lock (_syncReadersLock)
|
||||
readers = [.. _syncReaders];
|
||||
|
||||
foreach (var reader in readers)
|
||||
reader.Dispose();
|
||||
}
|
||||
}
|
||||
|
||||
@@ -15,13 +15,30 @@ public class TursoDataReader : DbDataReader
|
||||
private readonly TursoCommand _command;
|
||||
private readonly TursoStatementHandle _statement;
|
||||
private readonly CommandBehavior _behavior;
|
||||
private IDisposable? _syncOperation;
|
||||
private TursoConnection? _syncConnection;
|
||||
private bool _isClosed;
|
||||
|
||||
public TursoDataReader(TursoCommand command, TursoStatementHandle statement, CommandBehavior behavior)
|
||||
: this(command, statement, behavior, syncOperation: null)
|
||||
{
|
||||
}
|
||||
|
||||
public TursoDataReader(
|
||||
TursoCommand command,
|
||||
TursoStatementHandle statement,
|
||||
CommandBehavior behavior,
|
||||
IDisposable? syncOperation)
|
||||
{
|
||||
_command = command;
|
||||
_statement = statement;
|
||||
_behavior = behavior;
|
||||
_syncOperation = syncOperation;
|
||||
if (syncOperation is not null && command.Connection is TursoConnection connection)
|
||||
{
|
||||
_syncConnection = connection;
|
||||
connection.RegisterSyncReader(this);
|
||||
}
|
||||
}
|
||||
|
||||
public override bool GetBoolean(int ordinal)
|
||||
@@ -195,7 +212,7 @@ public class TursoDataReader : DbDataReader
|
||||
public override bool NextResult()
|
||||
{
|
||||
EnsureOpen();
|
||||
while (TursoBindings.Read(_statement))
|
||||
while (TursoBindings.Read(_statement, RunExternalIo))
|
||||
{
|
||||
}
|
||||
|
||||
@@ -207,6 +224,10 @@ public class TursoDataReader : DbDataReader
|
||||
if (disposing && !_isClosed)
|
||||
{
|
||||
_statement.Dispose();
|
||||
_syncOperation?.Dispose();
|
||||
_syncOperation = null;
|
||||
_syncConnection?.UnregisterSyncReader(this);
|
||||
_syncConnection = null;
|
||||
if ((_behavior & CommandBehavior.CloseConnection) == CommandBehavior.CloseConnection)
|
||||
_command.Connection?.Close();
|
||||
}
|
||||
@@ -218,7 +239,7 @@ public class TursoDataReader : DbDataReader
|
||||
public override bool Read()
|
||||
{
|
||||
EnsureOpen();
|
||||
return TursoBindings.Read(_statement);
|
||||
return TursoBindings.Read(_statement, RunExternalIo);
|
||||
}
|
||||
|
||||
public override int Depth => 0;
|
||||
@@ -268,4 +289,9 @@ public class TursoDataReader : DbDataReader
|
||||
if (IsClosed)
|
||||
throw new InvalidOperationException("The data reader is closed.");
|
||||
}
|
||||
|
||||
private void RunExternalIo()
|
||||
{
|
||||
_syncConnection?.RunExternalIo();
|
||||
}
|
||||
}
|
||||
|
||||
818
bindings/dotnet/src/Turso.Data/TursoSyncDatabase.cs
Normal file
818
bindings/dotnet/src/Turso.Data/TursoSyncDatabase.cs
Normal file
@@ -0,0 +1,818 @@
|
||||
using System.Buffers;
|
||||
using System.Net.Http.Headers;
|
||||
using System.Runtime.ExceptionServices;
|
||||
using Turso.Raw.Public;
|
||||
using Turso.Raw.Public.Handles;
|
||||
|
||||
namespace Turso;
|
||||
|
||||
public sealed class TursoSyncDatabase : IDisposable, IAsyncDisposable
|
||||
{
|
||||
private const int IoBufferSize = 64 * 1024;
|
||||
|
||||
private readonly TursoSyncDatabaseOptions _options;
|
||||
private readonly Uri _remoteUri;
|
||||
private readonly HttpClient _httpClient;
|
||||
private readonly bool _disposeHttpClient;
|
||||
private readonly TursoSyncDatabaseHandle _handle;
|
||||
private readonly SemaphoreSlim _operationLock = new(1, 1);
|
||||
private readonly AsyncLocal<int> _ioCallbackDepth = new();
|
||||
private SyncTransportContext? _lastTransportContext;
|
||||
private int _activeConnections;
|
||||
private int _disposeRequested;
|
||||
private int _resourcesDisposed;
|
||||
|
||||
private TursoSyncDatabase(TursoSyncDatabaseOptions options)
|
||||
{
|
||||
options.Validate();
|
||||
_options = options;
|
||||
_remoteUri = options.GetNormalizedRemoteUri();
|
||||
_disposeHttpClient = options.HttpClient is null;
|
||||
_httpClient = options.HttpClient ?? new HttpClient
|
||||
{
|
||||
Timeout = Timeout.InfiniteTimeSpan,
|
||||
};
|
||||
try
|
||||
{
|
||||
_handle = TursoSyncBindings.NewDatabase(CreateNativeConfiguration(options, _remoteUri));
|
||||
}
|
||||
catch
|
||||
{
|
||||
if (_disposeHttpClient)
|
||||
_httpClient.Dispose();
|
||||
throw;
|
||||
}
|
||||
}
|
||||
|
||||
public static TursoSyncDatabase Create(TursoSyncDatabaseOptions options)
|
||||
{
|
||||
var database = new TursoSyncDatabase(options);
|
||||
try
|
||||
{
|
||||
RunSynchronously(
|
||||
() => database.RunVoidOperationAsync(
|
||||
TursoSyncBindings.StartCreate,
|
||||
TursoSyncOperationKind.Create,
|
||||
CancellationToken.None));
|
||||
return database;
|
||||
}
|
||||
catch
|
||||
{
|
||||
database.Dispose();
|
||||
throw;
|
||||
}
|
||||
}
|
||||
|
||||
public static async Task<TursoSyncDatabase> CreateAsync(
|
||||
TursoSyncDatabaseOptions options,
|
||||
CancellationToken cancellationToken = default)
|
||||
{
|
||||
var database = new TursoSyncDatabase(options);
|
||||
try
|
||||
{
|
||||
await database.RunVoidOperationAsync(
|
||||
TursoSyncBindings.StartCreate,
|
||||
TursoSyncOperationKind.Create,
|
||||
cancellationToken)
|
||||
.ConfigureAwait(false);
|
||||
return database;
|
||||
}
|
||||
catch
|
||||
{
|
||||
await database.DisposeAsync().ConfigureAwait(false);
|
||||
throw;
|
||||
}
|
||||
}
|
||||
|
||||
public static TursoSyncDatabase Open(TursoSyncDatabaseOptions options)
|
||||
{
|
||||
var database = new TursoSyncDatabase(options);
|
||||
try
|
||||
{
|
||||
RunSynchronously(
|
||||
() => database.RunVoidOperationAsync(
|
||||
TursoSyncBindings.StartOpen,
|
||||
TursoSyncOperationKind.Open,
|
||||
CancellationToken.None));
|
||||
return database;
|
||||
}
|
||||
catch
|
||||
{
|
||||
database.Dispose();
|
||||
throw;
|
||||
}
|
||||
}
|
||||
|
||||
public static async Task<TursoSyncDatabase> OpenAsync(
|
||||
TursoSyncDatabaseOptions options,
|
||||
CancellationToken cancellationToken = default)
|
||||
{
|
||||
var database = new TursoSyncDatabase(options);
|
||||
try
|
||||
{
|
||||
await database.RunVoidOperationAsync(
|
||||
TursoSyncBindings.StartOpen,
|
||||
TursoSyncOperationKind.Open,
|
||||
cancellationToken)
|
||||
.ConfigureAwait(false);
|
||||
return database;
|
||||
}
|
||||
catch
|
||||
{
|
||||
await database.DisposeAsync().ConfigureAwait(false);
|
||||
throw;
|
||||
}
|
||||
}
|
||||
|
||||
public TursoConnection Connect()
|
||||
=> RunSynchronously(() => ConnectAsync(CancellationToken.None));
|
||||
|
||||
public async Task<TursoConnection> ConnectAsync(CancellationToken cancellationToken = default)
|
||||
{
|
||||
var connectionHandle = await ConnectHandleAsync(cancellationToken).ConfigureAwait(false);
|
||||
try
|
||||
{
|
||||
return TursoConnection.CreateSyncConnection(connectionHandle, this);
|
||||
}
|
||||
catch
|
||||
{
|
||||
connectionHandle.Dispose();
|
||||
ReleaseConnection();
|
||||
throw;
|
||||
}
|
||||
}
|
||||
|
||||
public bool Pull()
|
||||
=> RunSynchronously(() => PullAsync(CancellationToken.None));
|
||||
|
||||
public async Task<bool> PullAsync(CancellationToken cancellationToken = default)
|
||||
{
|
||||
ThrowIfDisposed();
|
||||
await _operationLock.WaitAsync(cancellationToken).ConfigureAwait(false);
|
||||
try
|
||||
{
|
||||
ThrowIfDisposed();
|
||||
using var waitOperation = StartOperation(
|
||||
TursoSyncBindings.StartWaitChanges,
|
||||
TursoSyncOperationKind.Pull);
|
||||
await DriveOperationAsync(
|
||||
waitOperation,
|
||||
TursoSyncOperationKind.Pull,
|
||||
cancellationToken)
|
||||
.ConfigureAwait(false);
|
||||
EnsureResultKind(waitOperation, TursoSyncOperationResultKind.Changes);
|
||||
using var changes = TursoSyncBindings.ExtractChanges(waitOperation);
|
||||
if (changes is null)
|
||||
return false;
|
||||
|
||||
using var applyOperation = StartOperation(
|
||||
database => TursoSyncBindings.StartApplyChanges(database, changes),
|
||||
TursoSyncOperationKind.Apply);
|
||||
await DriveOperationAsync(
|
||||
applyOperation,
|
||||
TursoSyncOperationKind.Apply,
|
||||
cancellationToken)
|
||||
.ConfigureAwait(false);
|
||||
EnsureResultKind(applyOperation, TursoSyncOperationResultKind.None);
|
||||
return true;
|
||||
}
|
||||
finally
|
||||
{
|
||||
_operationLock.Release();
|
||||
}
|
||||
}
|
||||
|
||||
public void Dispose()
|
||||
{
|
||||
ThrowIfIoReentrant();
|
||||
if (Interlocked.Exchange(ref _disposeRequested, 1) != 0)
|
||||
return;
|
||||
|
||||
if (Volatile.Read(ref _activeConnections) == 0)
|
||||
DisposeResources();
|
||||
}
|
||||
|
||||
public ValueTask DisposeAsync()
|
||||
{
|
||||
Dispose();
|
||||
return ValueTask.CompletedTask;
|
||||
}
|
||||
|
||||
internal void ProcessOneIo()
|
||||
{
|
||||
using var item = TursoSyncBindings.TakeIoItem(_handle);
|
||||
if (item is not null)
|
||||
RunSynchronously(() => HandleIoItemAsync(item, CancellationToken.None));
|
||||
TursoSyncBindings.StepIoCallbacks(_handle);
|
||||
}
|
||||
|
||||
internal IDisposable EnterConnectionOperation()
|
||||
{
|
||||
ThrowIfIoReentrant();
|
||||
ObjectDisposedException.ThrowIf(Volatile.Read(ref _resourcesDisposed) != 0, this);
|
||||
_operationLock.Wait();
|
||||
return new ConnectionOperationLease(_operationLock);
|
||||
}
|
||||
|
||||
internal void ThrowIfIoReentrant()
|
||||
{
|
||||
if (_ioCallbackDepth.Value != 0)
|
||||
throw new InvalidOperationException("Turso sync operations cannot be reentered from the sync HTTP handler.");
|
||||
}
|
||||
|
||||
internal async Task<TursoDatabaseHandle> ConnectHandleAsync(CancellationToken cancellationToken)
|
||||
{
|
||||
ThrowIfDisposed();
|
||||
await _operationLock.WaitAsync(cancellationToken).ConfigureAwait(false);
|
||||
try
|
||||
{
|
||||
ThrowIfDisposed();
|
||||
using var operation = StartOperation(
|
||||
TursoSyncBindings.StartConnect,
|
||||
TursoSyncOperationKind.Connect);
|
||||
await DriveOperationAsync(
|
||||
operation,
|
||||
TursoSyncOperationKind.Connect,
|
||||
cancellationToken)
|
||||
.ConfigureAwait(false);
|
||||
EnsureResultKind(operation, TursoSyncOperationResultKind.Connection);
|
||||
var connectionHandle = TursoSyncBindings.ExtractConnection(_handle, operation);
|
||||
Interlocked.Increment(ref _activeConnections);
|
||||
return connectionHandle;
|
||||
}
|
||||
finally
|
||||
{
|
||||
_operationLock.Release();
|
||||
}
|
||||
}
|
||||
|
||||
internal void ReleaseConnection()
|
||||
{
|
||||
var remaining = Interlocked.Decrement(ref _activeConnections);
|
||||
if (remaining < 0)
|
||||
throw new InvalidOperationException("Turso sync connection ownership is unbalanced.");
|
||||
if (remaining == 0 && Volatile.Read(ref _disposeRequested) != 0)
|
||||
DisposeResources();
|
||||
}
|
||||
|
||||
private async Task RunVoidOperationAsync(
|
||||
Func<TursoSyncDatabaseHandle, TursoSyncOperationHandle> start,
|
||||
TursoSyncOperationKind operationKind,
|
||||
CancellationToken cancellationToken)
|
||||
{
|
||||
ThrowIfDisposed();
|
||||
await _operationLock.WaitAsync(cancellationToken).ConfigureAwait(false);
|
||||
try
|
||||
{
|
||||
ThrowIfDisposed();
|
||||
using var operation = StartOperation(start, operationKind);
|
||||
await DriveOperationAsync(operation, operationKind, cancellationToken).ConfigureAwait(false);
|
||||
EnsureResultKind(operation, TursoSyncOperationResultKind.None);
|
||||
}
|
||||
finally
|
||||
{
|
||||
_operationLock.Release();
|
||||
}
|
||||
}
|
||||
|
||||
private async Task DriveOperationAsync(
|
||||
TursoSyncOperationHandle operation,
|
||||
TursoSyncOperationKind operationKind,
|
||||
CancellationToken cancellationToken)
|
||||
{
|
||||
try
|
||||
{
|
||||
while (true)
|
||||
{
|
||||
cancellationToken.ThrowIfCancellationRequested();
|
||||
switch (TursoSyncBindings.Resume(operation))
|
||||
{
|
||||
case TursoSyncOperationState.Done:
|
||||
return;
|
||||
case TursoSyncOperationState.Continue:
|
||||
continue;
|
||||
case TursoSyncOperationState.Io:
|
||||
await ProcessIoQueueAsync(cancellationToken).ConfigureAwait(false);
|
||||
break;
|
||||
default:
|
||||
throw new InvalidOperationException("Unknown Turso sync operation state.");
|
||||
}
|
||||
}
|
||||
}
|
||||
catch (OperationCanceledException) when (cancellationToken.IsCancellationRequested)
|
||||
{
|
||||
try
|
||||
{
|
||||
CancelQueuedIo();
|
||||
}
|
||||
catch
|
||||
{
|
||||
// Preserve cancellation after making the best effort to release native callbacks.
|
||||
}
|
||||
throw;
|
||||
}
|
||||
catch (TursoSyncException)
|
||||
{
|
||||
throw;
|
||||
}
|
||||
catch (Exception exception)
|
||||
{
|
||||
throw CreateSyncException(operationKind, exception);
|
||||
}
|
||||
}
|
||||
|
||||
private TursoSyncOperationHandle StartOperation(
|
||||
Func<TursoSyncDatabaseHandle, TursoSyncOperationHandle> start,
|
||||
TursoSyncOperationKind operationKind)
|
||||
{
|
||||
_lastTransportContext = null;
|
||||
try
|
||||
{
|
||||
return start(_handle);
|
||||
}
|
||||
catch (TursoSyncException)
|
||||
{
|
||||
throw;
|
||||
}
|
||||
catch (Exception exception)
|
||||
{
|
||||
throw CreateSyncException(operationKind, exception);
|
||||
}
|
||||
}
|
||||
|
||||
private async Task ProcessIoQueueAsync(CancellationToken cancellationToken)
|
||||
{
|
||||
ExceptionDispatchInfo? failure = null;
|
||||
while (true)
|
||||
{
|
||||
cancellationToken.ThrowIfCancellationRequested();
|
||||
using var item = TursoSyncBindings.TakeIoItem(_handle);
|
||||
if (item is null)
|
||||
break;
|
||||
|
||||
if (failure is null)
|
||||
{
|
||||
try
|
||||
{
|
||||
await HandleIoItemAsync(item, cancellationToken).ConfigureAwait(false);
|
||||
}
|
||||
catch (Exception exception)
|
||||
{
|
||||
failure = ExceptionDispatchInfo.Capture(exception);
|
||||
}
|
||||
}
|
||||
else
|
||||
{
|
||||
try
|
||||
{
|
||||
PoisonAndCompleteIo(item, RedactSecrets(failure.SourceException.Message));
|
||||
}
|
||||
catch
|
||||
{
|
||||
// Keep draining queued work and preserve the first I/O failure.
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
try
|
||||
{
|
||||
TursoSyncBindings.StepIoCallbacks(_handle);
|
||||
}
|
||||
catch (Exception exception) when (failure is null)
|
||||
{
|
||||
failure = ExceptionDispatchInfo.Capture(exception);
|
||||
}
|
||||
catch
|
||||
{
|
||||
// Preserve the first I/O failure.
|
||||
}
|
||||
|
||||
failure?.Throw();
|
||||
}
|
||||
|
||||
private void CancelQueuedIo()
|
||||
{
|
||||
ExceptionDispatchInfo? failure = null;
|
||||
while (true)
|
||||
{
|
||||
using var item = TursoSyncBindings.TakeIoItem(_handle);
|
||||
if (item is null)
|
||||
break;
|
||||
try
|
||||
{
|
||||
PoisonAndCompleteIo(item, "Turso sync operation was canceled.");
|
||||
}
|
||||
catch (Exception exception) when (failure is null)
|
||||
{
|
||||
failure = ExceptionDispatchInfo.Capture(exception);
|
||||
}
|
||||
catch
|
||||
{
|
||||
// Keep draining queued work and preserve the first cleanup failure.
|
||||
}
|
||||
}
|
||||
|
||||
try
|
||||
{
|
||||
TursoSyncBindings.StepIoCallbacks(_handle);
|
||||
}
|
||||
catch (Exception exception) when (failure is null)
|
||||
{
|
||||
failure = ExceptionDispatchInfo.Capture(exception);
|
||||
}
|
||||
catch
|
||||
{
|
||||
// Preserve the first cleanup failure.
|
||||
}
|
||||
|
||||
failure?.Throw();
|
||||
}
|
||||
|
||||
private static void PoisonAndCompleteIo(TursoSyncIoItemHandle item, string error)
|
||||
{
|
||||
ExceptionDispatchInfo? failure = null;
|
||||
try
|
||||
{
|
||||
TursoSyncBindings.PoisonIo(item, error);
|
||||
}
|
||||
catch (Exception exception)
|
||||
{
|
||||
failure = ExceptionDispatchInfo.Capture(exception);
|
||||
}
|
||||
|
||||
try
|
||||
{
|
||||
TursoSyncBindings.CompleteIo(item);
|
||||
}
|
||||
catch when (failure is not null)
|
||||
{
|
||||
// Preserve the first cleanup failure.
|
||||
}
|
||||
|
||||
failure?.Throw();
|
||||
}
|
||||
|
||||
private async Task HandleIoItemAsync(
|
||||
TursoSyncIoItemHandle item,
|
||||
CancellationToken cancellationToken)
|
||||
{
|
||||
ExceptionDispatchInfo? failure = null;
|
||||
try
|
||||
{
|
||||
switch (TursoSyncBindings.GetIoKind(item))
|
||||
{
|
||||
case TursoSyncIoKind.None:
|
||||
break;
|
||||
case TursoSyncIoKind.Http:
|
||||
await HandleHttpAsync(item, cancellationToken).ConfigureAwait(false);
|
||||
break;
|
||||
case TursoSyncIoKind.FullRead:
|
||||
await HandleFullReadAsync(item, cancellationToken).ConfigureAwait(false);
|
||||
break;
|
||||
case TursoSyncIoKind.FullWrite:
|
||||
await HandleFullWriteAsync(item, cancellationToken).ConfigureAwait(false);
|
||||
break;
|
||||
default:
|
||||
throw new InvalidOperationException("Unknown Turso sync I/O request.");
|
||||
}
|
||||
}
|
||||
catch (Exception exception)
|
||||
{
|
||||
failure = ExceptionDispatchInfo.Capture(exception);
|
||||
try
|
||||
{
|
||||
TursoSyncBindings.PoisonIo(item, RedactSecrets(exception.Message));
|
||||
}
|
||||
catch
|
||||
{
|
||||
// Preserve the I/O failure that caused poisoning.
|
||||
}
|
||||
}
|
||||
|
||||
try
|
||||
{
|
||||
TursoSyncBindings.CompleteIo(item);
|
||||
}
|
||||
catch when (failure is not null)
|
||||
{
|
||||
// Preserve the original I/O failure.
|
||||
}
|
||||
|
||||
failure?.Throw();
|
||||
}
|
||||
|
||||
private async Task HandleHttpAsync(
|
||||
TursoSyncIoItemHandle item,
|
||||
CancellationToken cancellationToken)
|
||||
{
|
||||
var previousDepth = _ioCallbackDepth.Value;
|
||||
_ioCallbackDepth.Value = previousDepth + 1;
|
||||
try
|
||||
{
|
||||
await HandleHttpCoreAsync(item, cancellationToken).ConfigureAwait(false);
|
||||
}
|
||||
finally
|
||||
{
|
||||
_ioCallbackDepth.Value = previousDepth;
|
||||
}
|
||||
}
|
||||
|
||||
private async Task HandleHttpCoreAsync(
|
||||
TursoSyncIoItemHandle item,
|
||||
CancellationToken cancellationToken)
|
||||
{
|
||||
var request = TursoSyncBindings.GetHttpRequest(item);
|
||||
var baseUri = request.Url is null ? _remoteUri : NormalizeRemoteUri(new Uri(request.Url, UriKind.Absolute));
|
||||
var requestUri = CombineUri(baseUri, request.Path);
|
||||
ValidateAuthTransport(requestUri, _remoteUri, _options.AuthToken);
|
||||
_lastTransportContext = new SyncTransportContext(
|
||||
request.Method,
|
||||
requestUri,
|
||||
StatusCode: null);
|
||||
|
||||
using var message = new HttpRequestMessage(new HttpMethod(request.Method), requestUri);
|
||||
if (request.Body.Length > 0)
|
||||
message.Content = new ByteArrayContent(request.Body);
|
||||
foreach (var header in request.Headers)
|
||||
{
|
||||
if (message.Headers.TryAddWithoutValidation(header.Name, header.Value))
|
||||
continue;
|
||||
|
||||
message.Content ??= new ByteArrayContent([]);
|
||||
if (!message.Content.Headers.TryAddWithoutValidation(header.Name, header.Value))
|
||||
throw new InvalidOperationException($"Invalid sync HTTP header: {header.Name}");
|
||||
}
|
||||
if (!string.IsNullOrWhiteSpace(_options.AuthToken))
|
||||
message.Headers.Authorization = new AuthenticationHeaderValue("Bearer", _options.AuthToken);
|
||||
|
||||
using var response = await _httpClient
|
||||
.SendAsync(message, HttpCompletionOption.ResponseHeadersRead, cancellationToken)
|
||||
.ConfigureAwait(false);
|
||||
_lastTransportContext = _lastTransportContext with
|
||||
{
|
||||
StatusCode = response.StatusCode,
|
||||
};
|
||||
TursoSyncBindings.SetIoStatus(item, (int)response.StatusCode);
|
||||
|
||||
await using var responseStream = await response.Content
|
||||
.ReadAsStreamAsync(cancellationToken)
|
||||
.ConfigureAwait(false);
|
||||
var buffer = ArrayPool<byte>.Shared.Rent(IoBufferSize);
|
||||
try
|
||||
{
|
||||
while (true)
|
||||
{
|
||||
var count = await responseStream
|
||||
.ReadAsync(buffer.AsMemory(0, IoBufferSize), cancellationToken)
|
||||
.ConfigureAwait(false);
|
||||
if (count == 0)
|
||||
break;
|
||||
TursoSyncBindings.PushIoBuffer(item, buffer.AsSpan(0, count));
|
||||
}
|
||||
}
|
||||
finally
|
||||
{
|
||||
ArrayPool<byte>.Shared.Return(buffer);
|
||||
}
|
||||
}
|
||||
|
||||
private static Task HandleFullReadAsync(
|
||||
TursoSyncIoItemHandle item,
|
||||
CancellationToken cancellationToken)
|
||||
{
|
||||
var path = TursoSyncBindings.GetFullReadPath(item);
|
||||
FileStream stream;
|
||||
try
|
||||
{
|
||||
stream = new FileStream(
|
||||
path,
|
||||
FileMode.Open,
|
||||
FileAccess.Read,
|
||||
FileShare.Read,
|
||||
IoBufferSize,
|
||||
FileOptions.SequentialScan);
|
||||
}
|
||||
catch (FileNotFoundException)
|
||||
{
|
||||
return Task.CompletedTask;
|
||||
}
|
||||
catch (DirectoryNotFoundException)
|
||||
{
|
||||
return Task.CompletedTask;
|
||||
}
|
||||
|
||||
using (stream)
|
||||
{
|
||||
var buffer = ArrayPool<byte>.Shared.Rent(IoBufferSize);
|
||||
try
|
||||
{
|
||||
while (true)
|
||||
{
|
||||
cancellationToken.ThrowIfCancellationRequested();
|
||||
var count = stream.Read(buffer, 0, IoBufferSize);
|
||||
if (count == 0)
|
||||
break;
|
||||
TursoSyncBindings.PushIoBuffer(item, buffer.AsSpan(0, count));
|
||||
}
|
||||
}
|
||||
finally
|
||||
{
|
||||
ArrayPool<byte>.Shared.Return(buffer);
|
||||
}
|
||||
}
|
||||
|
||||
return Task.CompletedTask;
|
||||
}
|
||||
|
||||
private static Task HandleFullWriteAsync(
|
||||
TursoSyncIoItemHandle item,
|
||||
CancellationToken cancellationToken)
|
||||
{
|
||||
var request = TursoSyncBindings.GetFullWriteRequest(item);
|
||||
var directory = Path.GetDirectoryName(Path.GetFullPath(request.Path));
|
||||
if (!string.IsNullOrEmpty(directory))
|
||||
Directory.CreateDirectory(directory);
|
||||
|
||||
var temporaryPath = request.Path + "." + Guid.NewGuid().ToString("N") + ".tmp";
|
||||
try
|
||||
{
|
||||
cancellationToken.ThrowIfCancellationRequested();
|
||||
using (var stream = new FileStream(
|
||||
temporaryPath,
|
||||
FileMode.CreateNew,
|
||||
FileAccess.Write,
|
||||
FileShare.None,
|
||||
IoBufferSize,
|
||||
FileOptions.WriteThrough))
|
||||
{
|
||||
stream.Write(request.Content);
|
||||
stream.Flush(flushToDisk: true);
|
||||
}
|
||||
|
||||
File.Move(temporaryPath, request.Path, overwrite: true);
|
||||
}
|
||||
finally
|
||||
{
|
||||
if (File.Exists(temporaryPath))
|
||||
File.Delete(temporaryPath);
|
||||
}
|
||||
|
||||
return Task.CompletedTask;
|
||||
}
|
||||
|
||||
private void ThrowIfDisposed()
|
||||
{
|
||||
ThrowIfIoReentrant();
|
||||
ObjectDisposedException.ThrowIf(Volatile.Read(ref _disposeRequested) != 0, this);
|
||||
}
|
||||
|
||||
private void DisposeResources()
|
||||
{
|
||||
_operationLock.Wait();
|
||||
try
|
||||
{
|
||||
if (Volatile.Read(ref _activeConnections) != 0
|
||||
|| Interlocked.Exchange(ref _resourcesDisposed, 1) != 0)
|
||||
{
|
||||
return;
|
||||
}
|
||||
|
||||
_handle.Dispose();
|
||||
if (_disposeHttpClient)
|
||||
_httpClient.Dispose();
|
||||
}
|
||||
finally
|
||||
{
|
||||
_operationLock.Release();
|
||||
}
|
||||
}
|
||||
|
||||
internal static void ValidateAuthTransport(
|
||||
Uri requestUri,
|
||||
Uri configuredRemoteUri,
|
||||
string? authToken)
|
||||
{
|
||||
if (string.IsNullOrWhiteSpace(authToken))
|
||||
return;
|
||||
if (!HasSameOrigin(requestUri, configuredRemoteUri))
|
||||
{
|
||||
throw new InvalidOperationException(
|
||||
"Refusing to send the sync auth token to an origin other than the configured remote.");
|
||||
}
|
||||
if (requestUri.Scheme != Uri.UriSchemeHttps && !requestUri.IsLoopback)
|
||||
{
|
||||
throw new InvalidOperationException(
|
||||
"Auth Token requires HTTPS sync requests unless the host is localhost or loopback.");
|
||||
}
|
||||
}
|
||||
|
||||
private static bool HasSameOrigin(Uri left, Uri right)
|
||||
{
|
||||
return left.Scheme.Equals(right.Scheme, StringComparison.OrdinalIgnoreCase)
|
||||
&& left.IdnHost.Equals(right.IdnHost, StringComparison.OrdinalIgnoreCase)
|
||||
&& left.Port == right.Port;
|
||||
}
|
||||
|
||||
private static Uri NormalizeRemoteUri(Uri uri)
|
||||
{
|
||||
var scheme = uri.Scheme.ToLowerInvariant() switch
|
||||
{
|
||||
"turso" or "libsql" => Uri.UriSchemeHttps,
|
||||
"http" => Uri.UriSchemeHttp,
|
||||
"https" => Uri.UriSchemeHttps,
|
||||
_ => throw new InvalidOperationException($"Unsupported sync URL scheme: {uri.Scheme}"),
|
||||
};
|
||||
return new UriBuilder(uri)
|
||||
{
|
||||
Scheme = scheme,
|
||||
Port = uri.IsDefaultPort ? -1 : uri.Port,
|
||||
UserName = string.Empty,
|
||||
Password = string.Empty,
|
||||
}.Uri;
|
||||
}
|
||||
|
||||
private static Uri CombineUri(Uri baseUri, string path)
|
||||
{
|
||||
var baseText = baseUri.GetLeftPart(UriPartial.Path).TrimEnd('/');
|
||||
return new Uri(baseText + "/" + path.TrimStart('/'), UriKind.Absolute);
|
||||
}
|
||||
|
||||
private static TursoSyncDatabaseConfiguration CreateNativeConfiguration(
|
||||
TursoSyncDatabaseOptions options,
|
||||
Uri remoteUri)
|
||||
{
|
||||
return new TursoSyncDatabaseConfiguration
|
||||
{
|
||||
Path = options.Path,
|
||||
RemoteUrl = remoteUri.ToString(),
|
||||
ClientName = options.ClientName,
|
||||
LongPollTimeoutMilliseconds = options.LongPollTimeout is null
|
||||
? 0
|
||||
: checked((int)options.LongPollTimeout.Value.TotalMilliseconds),
|
||||
BootstrapIfEmpty = options.BootstrapIfEmpty,
|
||||
};
|
||||
}
|
||||
|
||||
private static void EnsureResultKind(
|
||||
TursoSyncOperationHandle operation,
|
||||
TursoSyncOperationResultKind expected)
|
||||
{
|
||||
var actual = TursoSyncBindings.GetResultKind(operation);
|
||||
if (actual != expected)
|
||||
throw new InvalidOperationException($"Expected Turso sync result {expected}, got {actual}.");
|
||||
}
|
||||
|
||||
private TursoSyncException CreateSyncException(
|
||||
TursoSyncOperationKind operation,
|
||||
Exception exception)
|
||||
{
|
||||
var transport = _lastTransportContext;
|
||||
var message = RedactSecrets(exception.Message);
|
||||
var innerException = ContainsSecret(exception.ToString())
|
||||
? new Exception(message)
|
||||
: exception;
|
||||
return new TursoSyncException(
|
||||
operation,
|
||||
$"Turso sync {operation} failed: {message}",
|
||||
(exception as TursoSyncNativeException)?.StatusCode,
|
||||
transport?.Method,
|
||||
transport?.Endpoint,
|
||||
transport?.StatusCode,
|
||||
innerException);
|
||||
}
|
||||
|
||||
private string RedactSecrets(string message)
|
||||
{
|
||||
return string.IsNullOrWhiteSpace(_options.AuthToken)
|
||||
? message
|
||||
: message.Replace(_options.AuthToken, "[REDACTED]", StringComparison.Ordinal);
|
||||
}
|
||||
|
||||
private bool ContainsSecret(string message)
|
||||
{
|
||||
return !string.IsNullOrWhiteSpace(_options.AuthToken)
|
||||
&& message.Contains(_options.AuthToken, StringComparison.Ordinal);
|
||||
}
|
||||
|
||||
private static void RunSynchronously(Func<Task> operation)
|
||||
=> Task.Run(operation).GetAwaiter().GetResult();
|
||||
|
||||
private static T RunSynchronously<T>(Func<Task<T>> operation)
|
||||
=> Task.Run(operation).GetAwaiter().GetResult();
|
||||
|
||||
private sealed record SyncTransportContext(
|
||||
string Method,
|
||||
Uri Endpoint,
|
||||
System.Net.HttpStatusCode? StatusCode);
|
||||
|
||||
private sealed class ConnectionOperationLease(SemaphoreSlim operationLock) : IDisposable
|
||||
{
|
||||
private int _disposed;
|
||||
|
||||
public void Dispose()
|
||||
{
|
||||
if (Interlocked.Exchange(ref _disposed, 1) == 0)
|
||||
operationLock.Release();
|
||||
}
|
||||
}
|
||||
}
|
||||
75
bindings/dotnet/src/Turso.Data/TursoSyncDatabaseOptions.cs
Normal file
75
bindings/dotnet/src/Turso.Data/TursoSyncDatabaseOptions.cs
Normal file
@@ -0,0 +1,75 @@
|
||||
namespace Turso;
|
||||
|
||||
public sealed class TursoSyncDatabaseOptions
|
||||
{
|
||||
public TursoSyncDatabaseOptions(string path, Uri remoteUri)
|
||||
{
|
||||
ArgumentException.ThrowIfNullOrWhiteSpace(path);
|
||||
ArgumentNullException.ThrowIfNull(remoteUri);
|
||||
Path = path;
|
||||
RemoteUri = remoteUri;
|
||||
}
|
||||
|
||||
public string Path { get; }
|
||||
public Uri RemoteUri { get; }
|
||||
public string? AuthToken { get; init; }
|
||||
public string ClientName { get; init; } = "turso-sync-dotnet";
|
||||
public TimeSpan? LongPollTimeout { get; init; }
|
||||
public bool BootstrapIfEmpty { get; init; } = true;
|
||||
public HttpClient? HttpClient { get; init; }
|
||||
|
||||
internal Uri GetNormalizedRemoteUri()
|
||||
{
|
||||
if (!RemoteUri.IsAbsoluteUri)
|
||||
throw new ArgumentException("The sync remote URL must be absolute.", nameof(RemoteUri));
|
||||
if (!string.IsNullOrEmpty(RemoteUri.Query) || !string.IsNullOrEmpty(RemoteUri.Fragment))
|
||||
throw new ArgumentException("The sync remote URL must not include a query string or fragment.", nameof(RemoteUri));
|
||||
if (!string.IsNullOrEmpty(RemoteUri.UserInfo))
|
||||
throw new ArgumentException("Use AuthToken instead of embedding credentials in the sync URL.", nameof(RemoteUri));
|
||||
if (string.IsNullOrEmpty(RemoteUri.Host))
|
||||
throw new ArgumentException("The sync remote URL must include a host.", nameof(RemoteUri));
|
||||
|
||||
var scheme = RemoteUri.Scheme.ToLowerInvariant() switch
|
||||
{
|
||||
"turso" or "libsql" => Uri.UriSchemeHttps,
|
||||
"http" => Uri.UriSchemeHttp,
|
||||
"https" => Uri.UriSchemeHttps,
|
||||
_ => throw new ArgumentException(
|
||||
"The sync remote URL must use turso, libsql, HTTP, or HTTPS.",
|
||||
nameof(RemoteUri)),
|
||||
};
|
||||
var builder = new UriBuilder(RemoteUri)
|
||||
{
|
||||
Scheme = scheme,
|
||||
Port = RemoteUri.IsDefaultPort ? -1 : RemoteUri.Port,
|
||||
UserName = string.Empty,
|
||||
Password = string.Empty,
|
||||
};
|
||||
return builder.Uri;
|
||||
}
|
||||
|
||||
internal void Validate()
|
||||
{
|
||||
ArgumentException.ThrowIfNullOrWhiteSpace(Path);
|
||||
ArgumentException.ThrowIfNullOrWhiteSpace(ClientName);
|
||||
|
||||
var normalizedUri = GetNormalizedRemoteUri();
|
||||
if (!string.IsNullOrWhiteSpace(AuthToken)
|
||||
&& normalizedUri.Scheme != Uri.UriSchemeHttps
|
||||
&& !normalizedUri.IsLoopback)
|
||||
{
|
||||
throw new InvalidOperationException(
|
||||
"Auth Token requires an HTTPS sync URL unless the host is localhost or loopback.");
|
||||
}
|
||||
|
||||
if (LongPollTimeout is { } timeout
|
||||
&& (timeout < TimeSpan.FromMilliseconds(1) || timeout.TotalMilliseconds > int.MaxValue))
|
||||
{
|
||||
throw new ArgumentOutOfRangeException(
|
||||
nameof(LongPollTimeout),
|
||||
timeout,
|
||||
$"Long-poll timeout must be between 1 and {int.MaxValue} milliseconds.");
|
||||
}
|
||||
|
||||
}
|
||||
}
|
||||
43
bindings/dotnet/src/Turso.Data/TursoSyncException.cs
Normal file
43
bindings/dotnet/src/Turso.Data/TursoSyncException.cs
Normal file
@@ -0,0 +1,43 @@
|
||||
using System.Net;
|
||||
using Turso.Raw.Public;
|
||||
|
||||
namespace Turso;
|
||||
|
||||
public enum TursoSyncOperationKind
|
||||
{
|
||||
Create,
|
||||
Open,
|
||||
Connect,
|
||||
Pull,
|
||||
Apply,
|
||||
}
|
||||
|
||||
public sealed class TursoSyncException : TursoException
|
||||
{
|
||||
internal TursoSyncException(
|
||||
TursoSyncOperationKind operation,
|
||||
string message,
|
||||
uint? nativeStatusCode,
|
||||
string? httpMethod,
|
||||
Uri? endpoint,
|
||||
HttpStatusCode? httpStatusCode,
|
||||
Exception innerException)
|
||||
: base(message, innerException)
|
||||
{
|
||||
Operation = operation;
|
||||
NativeStatusCode = nativeStatusCode;
|
||||
HttpMethod = httpMethod;
|
||||
Endpoint = endpoint;
|
||||
HttpStatusCode = httpStatusCode;
|
||||
}
|
||||
|
||||
public TursoSyncOperationKind Operation { get; }
|
||||
|
||||
public uint? NativeStatusCode { get; }
|
||||
|
||||
public string? HttpMethod { get; }
|
||||
|
||||
public Uri? Endpoint { get; }
|
||||
|
||||
public HttpStatusCode? HttpStatusCode { get; }
|
||||
}
|
||||
@@ -180,6 +180,9 @@ public static class TursoBindings
|
||||
}
|
||||
|
||||
public static bool Read(TursoStatementHandle statement)
|
||||
=> Read(statement, runExternalIo: null);
|
||||
|
||||
public static bool Read(TursoStatementHandle statement, Action? runExternalIo)
|
||||
{
|
||||
statement.ThrowIfInvalid();
|
||||
|
||||
@@ -192,6 +195,7 @@ public static class TursoBindings
|
||||
return false;
|
||||
if (status == TursoStatusCode.Io)
|
||||
{
|
||||
runExternalIo?.Invoke();
|
||||
var ioStatus = TursoInterop.StatementRunIo(statement, out errorPtr);
|
||||
ThrowIfError(ioStatus, errorPtr);
|
||||
continue;
|
||||
|
||||
@@ -1,8 +1,25 @@
|
||||
namespace Turso.Raw.Public;
|
||||
|
||||
public class TursoException(string message) : Exception(message);
|
||||
|
||||
public sealed class TursoSyncNativeException(uint statusCode, string message) : TursoException(message)
|
||||
public class TursoException : Exception
|
||||
{
|
||||
public uint StatusCode { get; } = statusCode;
|
||||
public TursoException(string message)
|
||||
: base(message)
|
||||
{
|
||||
}
|
||||
|
||||
public TursoException(string message, Exception? innerException)
|
||||
: base(message, innerException)
|
||||
{
|
||||
}
|
||||
}
|
||||
|
||||
public sealed class TursoSyncNativeException : TursoException
|
||||
{
|
||||
public TursoSyncNativeException(uint statusCode, string message)
|
||||
: base(message)
|
||||
{
|
||||
StatusCode = statusCode;
|
||||
}
|
||||
|
||||
public uint StatusCode { get; }
|
||||
}
|
||||
382
bindings/dotnet/src/Turso.Tests/TursoManagedSyncTests.cs
Normal file
382
bindings/dotnet/src/Turso.Tests/TursoManagedSyncTests.cs
Normal file
@@ -0,0 +1,382 @@
|
||||
using System.Data;
|
||||
using System.Net;
|
||||
using AwesomeAssertions;
|
||||
using Turso.Raw.Public;
|
||||
|
||||
namespace Turso.Tests;
|
||||
|
||||
public sealed class TursoManagedSyncTests
|
||||
{
|
||||
[Test]
|
||||
public void SyncAuthTokenIsPinnedToConfiguredOrigin()
|
||||
{
|
||||
Action crossOrigin = () => TursoSyncDatabase.ValidateAuthTransport(
|
||||
new Uri("https://attacker.example/pull-updates"),
|
||||
new Uri("https://database.example"),
|
||||
"secret");
|
||||
|
||||
crossOrigin.Should().Throw<InvalidOperationException>()
|
||||
.WithMessage("*configured remote*");
|
||||
|
||||
TursoSyncDatabase.ValidateAuthTransport(
|
||||
new Uri("https://database.example/pull-updates"),
|
||||
new Uri("https://database.example"),
|
||||
"secret");
|
||||
}
|
||||
|
||||
[Test]
|
||||
public void SyncOptionsRejectUnsafeAuthTransport()
|
||||
{
|
||||
new TursoSyncDatabaseOptions("replica.db", new Uri("http://example.test"))
|
||||
{
|
||||
AuthToken = "secret",
|
||||
}.Invoking(x => x.Validate())
|
||||
.Should().Throw<InvalidOperationException>()
|
||||
.WithMessage("*HTTPS*");
|
||||
}
|
||||
|
||||
[Test]
|
||||
public async Task HighLevelCreateDrivesHttpAndSurfacesTheNativeFailure()
|
||||
{
|
||||
using var httpClient = new HttpClient(new FailingSyncHandler());
|
||||
var options = new TursoSyncDatabaseOptions(":memory:", new Uri("https://example.test"))
|
||||
{
|
||||
HttpClient = httpClient,
|
||||
AuthToken = "secret",
|
||||
};
|
||||
|
||||
var action = async () => await TursoSyncDatabase.CreateAsync(options);
|
||||
|
||||
var exception = await action.Should().ThrowAsync<TursoSyncException>();
|
||||
exception.And.Message.Should().NotContain("secret");
|
||||
exception.And.Operation.Should().Be(TursoSyncOperationKind.Create);
|
||||
exception.And.NativeStatusCode.Should().NotBeNull();
|
||||
exception.And.HttpMethod.Should().Be("POST");
|
||||
exception.And.Endpoint.Should().Be(new Uri("https://example.test/pull-updates"));
|
||||
exception.And.HttpStatusCode.Should().Be(HttpStatusCode.InternalServerError);
|
||||
}
|
||||
|
||||
[Test]
|
||||
public async Task HttpHandlerSecretsAreRedactedFromTheSyncFailureMessage()
|
||||
{
|
||||
using var httpClient = new HttpClient(new SecretLeakingHandler());
|
||||
var options = new TursoSyncDatabaseOptions(":memory:", new Uri("https://example.test"))
|
||||
{
|
||||
HttpClient = httpClient,
|
||||
AuthToken = "secret",
|
||||
};
|
||||
|
||||
var action = async () => await TursoSyncDatabase.CreateAsync(options);
|
||||
|
||||
var exception = await action.Should().ThrowAsync<TursoSyncException>();
|
||||
exception.And.Message.Should().NotContain("secret");
|
||||
exception.And.Message.Should().Contain("[REDACTED]");
|
||||
exception.And.ToString().Should().NotContain("secret");
|
||||
}
|
||||
|
||||
[Test]
|
||||
public void SynchronousCreateDoesNotDependOnTheCallersSynchronizationContext()
|
||||
{
|
||||
Exception? failure = null;
|
||||
var thread = new Thread(() =>
|
||||
{
|
||||
SynchronizationContext.SetSynchronizationContext(new NonPumpingSynchronizationContext());
|
||||
try
|
||||
{
|
||||
using var httpClient = new HttpClient(new YieldingFailureHandler());
|
||||
TursoSyncDatabase.Create(
|
||||
new TursoSyncDatabaseOptions(":memory:", new Uri("https://example.test"))
|
||||
{
|
||||
HttpClient = httpClient,
|
||||
});
|
||||
}
|
||||
catch (TursoSyncException)
|
||||
{
|
||||
}
|
||||
catch (Exception exception)
|
||||
{
|
||||
failure = exception;
|
||||
}
|
||||
})
|
||||
{
|
||||
IsBackground = true,
|
||||
};
|
||||
|
||||
thread.Start();
|
||||
|
||||
thread.Join(TimeSpan.FromSeconds(5)).Should().BeTrue();
|
||||
failure.Should().BeNull();
|
||||
}
|
||||
|
||||
[Test]
|
||||
public async Task DeferredBootstrapCreatesAUsableLocalConnection()
|
||||
{
|
||||
using var httpClient = new HttpClient(new UnexpectedHttpHandler());
|
||||
var database = await TursoSyncDatabase.CreateAsync(
|
||||
new TursoSyncDatabaseOptions(":memory:", new Uri("https://example.test"))
|
||||
{
|
||||
BootstrapIfEmpty = false,
|
||||
HttpClient = httpClient,
|
||||
});
|
||||
await using var connection = await database.ConnectAsync();
|
||||
|
||||
connection.ExecuteNonQuery("CREATE TABLE items(id INTEGER PRIMARY KEY, name TEXT)");
|
||||
connection.ExecuteNonQuery("INSERT INTO items(name) VALUES ('local')");
|
||||
using (var command = new TursoCommand(connection, "SELECT name FROM items"))
|
||||
command.ExecuteScalar().Should().Be("local");
|
||||
|
||||
await database.DisposeAsync();
|
||||
using var afterDispose = new TursoCommand(connection, "SELECT COUNT(*) FROM items");
|
||||
afterDispose.ExecuteScalar().Should().Be(1L);
|
||||
}
|
||||
|
||||
[Test]
|
||||
public async Task CancellationStopsAnInFlightSyncHttpRequest()
|
||||
{
|
||||
var handler = new BlockingSyncHandler();
|
||||
using var httpClient = new HttpClient(handler);
|
||||
await using var database = await TursoSyncDatabase.CreateAsync(
|
||||
new TursoSyncDatabaseOptions(":memory:", new Uri("https://example.test"))
|
||||
{
|
||||
BootstrapIfEmpty = false,
|
||||
HttpClient = httpClient,
|
||||
});
|
||||
using var cancellation = new CancellationTokenSource(TimeSpan.FromMilliseconds(100));
|
||||
|
||||
var canceledPull = async () => await database.PullAsync(cancellation.Token);
|
||||
|
||||
await canceledPull.Should().ThrowAsync<OperationCanceledException>();
|
||||
|
||||
var nextPull = async () => await database.PullAsync();
|
||||
await nextPull.Should().ThrowAsync<TursoException>();
|
||||
handler.RequestCount.Should().Be(2);
|
||||
}
|
||||
|
||||
[Test]
|
||||
public async Task FileReplicaCanBeCreatedClosedAndOpenedAgain()
|
||||
{
|
||||
var directory = Path.Combine(
|
||||
TestContext.CurrentContext.WorkDirectory,
|
||||
"turso-sync-open-" + Guid.NewGuid().ToString("N"));
|
||||
Directory.CreateDirectory(directory);
|
||||
var path = Path.Combine(directory, "replica.db");
|
||||
using var httpClient = new HttpClient(new UnexpectedHttpHandler());
|
||||
var options = new TursoSyncDatabaseOptions(path, new Uri("https://example.test"))
|
||||
{
|
||||
BootstrapIfEmpty = false,
|
||||
HttpClient = httpClient,
|
||||
};
|
||||
|
||||
try
|
||||
{
|
||||
await using (var created = await TursoSyncDatabase.CreateAsync(options))
|
||||
await using (var connection = await created.ConnectAsync())
|
||||
{
|
||||
connection.ExecuteNonQuery("CREATE TABLE persisted(value TEXT)");
|
||||
connection.ExecuteNonQuery("INSERT INTO persisted VALUES ('yes')");
|
||||
}
|
||||
|
||||
await using var opened = await TursoSyncDatabase.OpenAsync(options);
|
||||
await using var reopenedConnection = await opened.ConnectAsync();
|
||||
using var query = new TursoCommand(reopenedConnection, "SELECT value FROM persisted");
|
||||
query.ExecuteScalar().Should().Be("yes");
|
||||
}
|
||||
finally
|
||||
{
|
||||
Directory.Delete(directory, recursive: true);
|
||||
}
|
||||
}
|
||||
|
||||
[Test]
|
||||
public async Task PullWaitsForActiveReaders()
|
||||
{
|
||||
using var httpClient = new HttpClient(new FailingSyncHandler());
|
||||
await using var database = await TursoSyncDatabase.CreateAsync(
|
||||
new TursoSyncDatabaseOptions(":memory:", new Uri("https://example.test"))
|
||||
{
|
||||
BootstrapIfEmpty = false,
|
||||
HttpClient = httpClient,
|
||||
});
|
||||
await using var connection = await database.ConnectAsync();
|
||||
connection.ExecuteNonQuery("CREATE TABLE items(value INTEGER)");
|
||||
connection.ExecuteNonQuery("INSERT INTO items VALUES (1)");
|
||||
|
||||
using var command = new TursoCommand(connection, "SELECT value FROM items");
|
||||
using var reader = command.ExecuteReader();
|
||||
reader.Read().Should().BeTrue();
|
||||
|
||||
var pull = database.PullAsync();
|
||||
await Task.Delay(50);
|
||||
pull.IsCompleted.Should().BeFalse();
|
||||
|
||||
reader.Dispose();
|
||||
var action = async () => await pull;
|
||||
await action.Should().ThrowAsync<TursoException>();
|
||||
}
|
||||
|
||||
[Test]
|
||||
public async Task SyncHttpHandlerCannotReenterTheDatabase()
|
||||
{
|
||||
var handler = new ReentrantSyncHandler();
|
||||
using var httpClient = new HttpClient(handler);
|
||||
await using var database = await TursoSyncDatabase.CreateAsync(
|
||||
new TursoSyncDatabaseOptions(":memory:", new Uri("https://example.test"))
|
||||
{
|
||||
BootstrapIfEmpty = false,
|
||||
HttpClient = httpClient,
|
||||
});
|
||||
handler.OnSend = database.Dispose;
|
||||
|
||||
var action = async () => await database.PullAsync();
|
||||
|
||||
await action.Should().ThrowAsync<TursoException>();
|
||||
handler.ReentryFailure.Should().BeOfType<InvalidOperationException>()
|
||||
.Which.Message.Should().Contain("cannot be reentered");
|
||||
}
|
||||
|
||||
[Test]
|
||||
public async Task ClosingAConnectionClosesItsActiveReaderBeforeReleasingSyncOwnership()
|
||||
{
|
||||
using var httpClient = new HttpClient(new UnexpectedHttpHandler());
|
||||
await using var database = await TursoSyncDatabase.CreateAsync(
|
||||
new TursoSyncDatabaseOptions(":memory:", new Uri("https://example.test"))
|
||||
{
|
||||
BootstrapIfEmpty = false,
|
||||
HttpClient = httpClient,
|
||||
});
|
||||
await using var connection = await database.ConnectAsync();
|
||||
connection.ExecuteNonQuery("CREATE TABLE items(value INTEGER)");
|
||||
connection.ExecuteNonQuery("INSERT INTO items VALUES (1)");
|
||||
using var command = new TursoCommand(connection, "SELECT value FROM items");
|
||||
using var reader = command.ExecuteReader();
|
||||
reader.Read().Should().BeTrue();
|
||||
|
||||
connection.Close();
|
||||
|
||||
connection.State.Should().Be(ConnectionState.Closed);
|
||||
reader.IsClosed.Should().BeTrue();
|
||||
}
|
||||
|
||||
[Test]
|
||||
public async Task ConnectionQueuedBeforeDisposeIsRejectedAfterItGetsTheGate()
|
||||
{
|
||||
using var httpClient = new HttpClient(new UnexpectedHttpHandler());
|
||||
var database = await TursoSyncDatabase.CreateAsync(
|
||||
new TursoSyncDatabaseOptions(":memory:", new Uri("https://example.test"))
|
||||
{
|
||||
BootstrapIfEmpty = false,
|
||||
HttpClient = httpClient,
|
||||
});
|
||||
var gate = database.EnterConnectionOperation();
|
||||
var connecting = database.ConnectAsync();
|
||||
await Task.Delay(20);
|
||||
var disposing = Task.Run(database.Dispose);
|
||||
|
||||
gate.Dispose();
|
||||
var connectAction = async () => await connecting;
|
||||
await connectAction.Should().ThrowAsync<ObjectDisposedException>();
|
||||
await disposing;
|
||||
}
|
||||
|
||||
private sealed class FailingSyncHandler : HttpMessageHandler
|
||||
{
|
||||
protected override Task<HttpResponseMessage> SendAsync(
|
||||
HttpRequestMessage request,
|
||||
CancellationToken cancellationToken)
|
||||
{
|
||||
request.RequestUri.Should().Be(new Uri("https://example.test/pull-updates"));
|
||||
request.Headers.Authorization?.Scheme.Should().Be("Bearer");
|
||||
request.Headers.Authorization?.Parameter.Should().Be("secret");
|
||||
request.Content?.Headers.ContentType?.MediaType.Should().Be("application/protobuf");
|
||||
return Task.FromResult(new HttpResponseMessage(HttpStatusCode.InternalServerError)
|
||||
{
|
||||
Content = new ByteArrayContent([]),
|
||||
});
|
||||
}
|
||||
}
|
||||
|
||||
private sealed class SecretLeakingHandler : HttpMessageHandler
|
||||
{
|
||||
protected override Task<HttpResponseMessage> SendAsync(
|
||||
HttpRequestMessage request,
|
||||
CancellationToken cancellationToken)
|
||||
{
|
||||
throw new HttpRequestException("transport exposed secret");
|
||||
}
|
||||
}
|
||||
|
||||
private sealed class YieldingFailureHandler : HttpMessageHandler
|
||||
{
|
||||
protected override async Task<HttpResponseMessage> SendAsync(
|
||||
HttpRequestMessage request,
|
||||
CancellationToken cancellationToken)
|
||||
{
|
||||
await Task.Yield();
|
||||
return new HttpResponseMessage(HttpStatusCode.InternalServerError)
|
||||
{
|
||||
Content = new ByteArrayContent([]),
|
||||
};
|
||||
}
|
||||
}
|
||||
|
||||
private sealed class NonPumpingSynchronizationContext : SynchronizationContext
|
||||
{
|
||||
public override void Post(SendOrPostCallback callback, object? state)
|
||||
{
|
||||
}
|
||||
}
|
||||
|
||||
private sealed class UnexpectedHttpHandler : HttpMessageHandler
|
||||
{
|
||||
protected override Task<HttpResponseMessage> SendAsync(
|
||||
HttpRequestMessage request,
|
||||
CancellationToken cancellationToken)
|
||||
{
|
||||
throw new AssertionException($"Unexpected HTTP request: {request.RequestUri}");
|
||||
}
|
||||
}
|
||||
|
||||
private sealed class BlockingSyncHandler : HttpMessageHandler
|
||||
{
|
||||
public int RequestCount { get; private set; }
|
||||
|
||||
protected override async Task<HttpResponseMessage> SendAsync(
|
||||
HttpRequestMessage request,
|
||||
CancellationToken cancellationToken)
|
||||
{
|
||||
RequestCount++;
|
||||
if (RequestCount == 1)
|
||||
await Task.Delay(Timeout.InfiniteTimeSpan, cancellationToken);
|
||||
|
||||
return new HttpResponseMessage(HttpStatusCode.InternalServerError)
|
||||
{
|
||||
Content = new ByteArrayContent([]),
|
||||
};
|
||||
}
|
||||
}
|
||||
|
||||
private sealed class ReentrantSyncHandler : HttpMessageHandler
|
||||
{
|
||||
public Action? OnSend { get; set; }
|
||||
public Exception? ReentryFailure { get; private set; }
|
||||
|
||||
protected override Task<HttpResponseMessage> SendAsync(
|
||||
HttpRequestMessage request,
|
||||
CancellationToken cancellationToken)
|
||||
{
|
||||
try
|
||||
{
|
||||
OnSend?.Invoke();
|
||||
}
|
||||
catch (Exception exception)
|
||||
{
|
||||
ReentryFailure = exception;
|
||||
}
|
||||
|
||||
return Task.FromResult(new HttpResponseMessage(HttpStatusCode.InternalServerError)
|
||||
{
|
||||
Content = new ByteArrayContent([]),
|
||||
});
|
||||
}
|
||||
}
|
||||
}
|
||||
Reference in New Issue
Block a user