mirror of
https://github.com/allankoechke/turso.git
synced 2026-11-30 11:12:58 +00:00
bindings/dotnet: pool replicas and schedule pulls
Share file-backed replicas only when Pooling=True while keeping non-pooled paths exclusive and :memory: replicas private. Normalize path identity, hash credential fingerprints, single-flight initialization, and release the shared sync database after the last lease. Run one automatic pull coordinator per replica with bounded transient retries and immutable status notifications. Keep observer callbacks outside lifecycle locks, preserve stopped status across queued events, and surface terminal failures during close. Tests: dotnet build bindings\\dotnet\\Turso.slnx --no-restore --configuration Debug; dotnet test bindings\\dotnet\\src\\Turso.Tests\\Turso.Tests.csproj --no-restore --no-build (198 passed, 1 skipped; includes live cloud convergence)
This commit is contained in:
@@ -110,14 +110,19 @@ await using var replica = new TursoConnection(
|
||||
"Data Source=turso://example-org.turso.io;"
|
||||
+ "Auth Token=eyJ...;"
|
||||
+ "Replica Path=./replica.db;"
|
||||
+ "Pooling=False");
|
||||
+ "Pooling=True;"
|
||||
+ "Sync Interval=30");
|
||||
await replica.OpenAsync();
|
||||
|
||||
// Pull remote changes into the local replica. Local writes are not pushed.
|
||||
// Pull immediately in addition to the shared 30-second automatic schedule.
|
||||
await replica.SyncAsync();
|
||||
```
|
||||
|
||||
Connection-string replicas also map `Sync Client Name`, `Sync Long Poll Timeout`, `Bootstrap If Empty`, `Partial Bootstrap Prefix`/`Query`, `Partial Sync Segment Size`/`Prefetch`, `Remote Encryption Cipher`/`Key`, `Push Operations Threshold`, `Pull Bytes Threshold`, `Force Logical MVCC Pull`, and `Sync Experimental Features` to `TursoSyncDatabaseOptions`. Local `Encryption Cipher` and `Encryption Key` do not configure remote replica encryption. Each connection owns its replica exclusively; pooling, automatic sync (`Sync Interval`), and replica batches are not supported yet.
|
||||
`Pooling=True` shares a file replica and one automatic-sync schedule among connections that use the same path and options. Pooling remains opt-in; `Pooling=False` keeps an exclusive path lease, and `:memory:` replicas are always private. Connections for one pooled path must use identical sync settings and credentials.
|
||||
|
||||
`Sync Interval` is the automatic pull period in seconds. `AutomaticSyncStatus` and `AutomaticSyncStatusChanged` expose waiting, running, retrying, faulted, and stopped states along with attempt times, the last pull result, the next attempt, and terminal failures. Automatic sync retries transient transport, I/O, and timeout failures twice; other failures are terminal and are also surfaced by `Close`.
|
||||
|
||||
Connection-string replicas also map `Sync Client Name`, `Sync Long Poll Timeout`, `Bootstrap If Empty`, `Partial Bootstrap Prefix`/`Query`, `Partial Sync Segment Size`/`Prefetch`, `Remote Encryption Cipher`/`Key`, `Push Operations Threshold`, `Pull Bytes Threshold`, `Force Logical MVCC Pull`, and `Sync Experimental Features` to `TursoSyncDatabaseOptions`. Local `Encryption Cipher` and `Encryption Key` do not configure remote replica encryption. Replica batches are not supported yet.
|
||||
|
||||
Remote mode also supports ADO.NET `DbBatch` for latency-sensitive workloads that should be sent in one Hrana batch:
|
||||
|
||||
|
||||
221
bindings/dotnet/src/Turso.Data/TursoAutomaticSyncCoordinator.cs
Normal file
221
bindings/dotnet/src/Turso.Data/TursoAutomaticSyncCoordinator.cs
Normal file
@@ -0,0 +1,221 @@
|
||||
namespace Turso;
|
||||
|
||||
internal sealed class TursoAutomaticSyncCoordinator : IDisposable
|
||||
{
|
||||
private readonly TursoSyncDatabase _database;
|
||||
private readonly TimeSpan _interval;
|
||||
private readonly TimeProvider _timeProvider;
|
||||
private readonly CancellationTokenSource? _cancellation;
|
||||
private readonly Task? _task;
|
||||
private TursoAutomaticSyncStatus _status = TursoAutomaticSyncStatus.Stopped;
|
||||
private readonly System.Collections.Concurrent.ConcurrentQueue<Notification> _notifications = new();
|
||||
private int _notificationDrainScheduled;
|
||||
private int _disposed;
|
||||
|
||||
public TursoAutomaticSyncCoordinator(
|
||||
TursoSyncDatabase database,
|
||||
TimeSpan interval,
|
||||
TimeProvider timeProvider)
|
||||
{
|
||||
_database = database;
|
||||
_interval = interval;
|
||||
_timeProvider = timeProvider;
|
||||
if (interval <= TimeSpan.Zero)
|
||||
return;
|
||||
|
||||
_cancellation = new CancellationTokenSource();
|
||||
Publish(_status with
|
||||
{
|
||||
State = TursoAutomaticSyncState.Waiting,
|
||||
NextAttempt = _timeProvider.GetUtcNow() + interval,
|
||||
});
|
||||
_task = RunAsync(_cancellation.Token);
|
||||
}
|
||||
|
||||
public TursoAutomaticSyncStatus Status => Volatile.Read(ref _status);
|
||||
|
||||
public event EventHandler<TursoAutomaticSyncStatusChangedEventArgs>? StatusChanged;
|
||||
|
||||
public Exception? Stop()
|
||||
{
|
||||
if (Interlocked.Exchange(ref _disposed, 1) != 0)
|
||||
return Status.LastException;
|
||||
if (_cancellation is null || _task is null)
|
||||
return null;
|
||||
|
||||
try
|
||||
{
|
||||
_cancellation.Cancel();
|
||||
_task.GetAwaiter().GetResult();
|
||||
PublishStopped();
|
||||
return null;
|
||||
}
|
||||
catch (OperationCanceledException) when (_cancellation.IsCancellationRequested)
|
||||
{
|
||||
PublishStopped();
|
||||
return null;
|
||||
}
|
||||
catch (Exception exception)
|
||||
{
|
||||
return exception;
|
||||
}
|
||||
finally
|
||||
{
|
||||
_cancellation.Dispose();
|
||||
}
|
||||
}
|
||||
|
||||
public void Dispose()
|
||||
{
|
||||
_ = Stop();
|
||||
}
|
||||
|
||||
private async Task RunAsync(CancellationToken cancellationToken)
|
||||
{
|
||||
while (true)
|
||||
{
|
||||
await Task.Delay(_interval, _timeProvider, cancellationToken).ConfigureAwait(false);
|
||||
for (var attempt = 0; ; attempt++)
|
||||
{
|
||||
var attemptTime = _timeProvider.GetUtcNow();
|
||||
Publish(Status with
|
||||
{
|
||||
State = attempt == 0
|
||||
? TursoAutomaticSyncState.Running
|
||||
: TursoAutomaticSyncState.Retrying,
|
||||
Attempt = attempt + 1,
|
||||
LastAttempt = attemptTime,
|
||||
LastException = null,
|
||||
NextAttempt = null,
|
||||
});
|
||||
try
|
||||
{
|
||||
var appliedChanges = await _database.PullAsync(cancellationToken).ConfigureAwait(false);
|
||||
var successTime = _timeProvider.GetUtcNow();
|
||||
Publish(Status with
|
||||
{
|
||||
State = TursoAutomaticSyncState.Waiting,
|
||||
Attempt = 0,
|
||||
LastSuccess = successTime,
|
||||
LastPullAppliedChanges = appliedChanges,
|
||||
LastException = null,
|
||||
NextAttempt = successTime + _interval,
|
||||
});
|
||||
break;
|
||||
}
|
||||
catch (Exception exception) when (
|
||||
attempt < 2 && IsTransientFailure(exception, cancellationToken))
|
||||
{
|
||||
var retryDelay = TimeSpan.FromMilliseconds(50 * (1 << attempt));
|
||||
Publish(Status with
|
||||
{
|
||||
State = TursoAutomaticSyncState.Retrying,
|
||||
Attempt = attempt + 1,
|
||||
LastException = exception,
|
||||
NextAttempt = _timeProvider.GetUtcNow() + retryDelay,
|
||||
});
|
||||
await Task.Delay(retryDelay, _timeProvider, cancellationToken).ConfigureAwait(false);
|
||||
}
|
||||
catch (Exception exception) when (!cancellationToken.IsCancellationRequested)
|
||||
{
|
||||
Publish(Status with
|
||||
{
|
||||
State = TursoAutomaticSyncState.Faulted,
|
||||
Attempt = attempt + 1,
|
||||
LastException = exception,
|
||||
NextAttempt = null,
|
||||
});
|
||||
throw;
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
private static bool IsTransientFailure(
|
||||
Exception exception,
|
||||
CancellationToken cancellationToken)
|
||||
{
|
||||
while (exception is TursoSyncException { InnerException: { } innerException })
|
||||
exception = innerException;
|
||||
|
||||
return !cancellationToken.IsCancellationRequested
|
||||
&& exception is HttpRequestException
|
||||
or IOException
|
||||
or TimeoutException
|
||||
or OperationCanceledException;
|
||||
}
|
||||
|
||||
private void PublishStopped()
|
||||
{
|
||||
Publish(Status with
|
||||
{
|
||||
State = TursoAutomaticSyncState.Stopped,
|
||||
Attempt = 0,
|
||||
NextAttempt = null,
|
||||
});
|
||||
}
|
||||
|
||||
private void Publish(TursoAutomaticSyncStatus status)
|
||||
{
|
||||
Volatile.Write(ref _status, status);
|
||||
var handlers = StatusChanged;
|
||||
if (Volatile.Read(ref _disposed) != 0 || handlers is null)
|
||||
return;
|
||||
|
||||
var args = new TursoAutomaticSyncStatusChangedEventArgs(status);
|
||||
_notifications.Enqueue(new Notification(args, handlers));
|
||||
ScheduleNotificationDrain();
|
||||
}
|
||||
|
||||
private void ScheduleNotificationDrain()
|
||||
{
|
||||
if (Interlocked.Exchange(ref _notificationDrainScheduled, 1) != 0)
|
||||
return;
|
||||
|
||||
ThreadPool.UnsafeQueueUserWorkItem(
|
||||
static coordinator => coordinator.DrainNotifications(),
|
||||
this,
|
||||
preferLocal: false);
|
||||
}
|
||||
|
||||
private void DrainNotifications()
|
||||
{
|
||||
try
|
||||
{
|
||||
while (_notifications.TryDequeue(out var notification))
|
||||
{
|
||||
if (Volatile.Read(ref _disposed) != 0)
|
||||
{
|
||||
while (_notifications.TryDequeue(out _))
|
||||
{
|
||||
}
|
||||
return;
|
||||
}
|
||||
|
||||
foreach (var callback in notification.Handlers.GetInvocationList())
|
||||
{
|
||||
try
|
||||
{
|
||||
((EventHandler<TursoAutomaticSyncStatusChangedEventArgs>)callback)(
|
||||
this,
|
||||
notification.Args);
|
||||
}
|
||||
catch
|
||||
{
|
||||
// Observers cannot stop synchronization.
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
finally
|
||||
{
|
||||
Volatile.Write(ref _notificationDrainScheduled, 0);
|
||||
if (!_notifications.IsEmpty)
|
||||
ScheduleNotificationDrain();
|
||||
}
|
||||
}
|
||||
|
||||
private sealed record Notification(
|
||||
TursoAutomaticSyncStatusChangedEventArgs Args,
|
||||
EventHandler<TursoAutomaticSyncStatusChangedEventArgs> Handlers);
|
||||
}
|
||||
34
bindings/dotnet/src/Turso.Data/TursoAutomaticSyncStatus.cs
Normal file
34
bindings/dotnet/src/Turso.Data/TursoAutomaticSyncStatus.cs
Normal file
@@ -0,0 +1,34 @@
|
||||
namespace Turso;
|
||||
|
||||
public enum TursoAutomaticSyncState
|
||||
{
|
||||
Stopped,
|
||||
Waiting,
|
||||
Running,
|
||||
Retrying,
|
||||
Faulted,
|
||||
}
|
||||
|
||||
public sealed record TursoAutomaticSyncStatus(
|
||||
TursoAutomaticSyncState State,
|
||||
int Attempt,
|
||||
DateTimeOffset? LastAttempt,
|
||||
DateTimeOffset? LastSuccess,
|
||||
bool? LastPullAppliedChanges,
|
||||
Exception? LastException,
|
||||
DateTimeOffset? NextAttempt)
|
||||
{
|
||||
public static TursoAutomaticSyncStatus Stopped { get; } = new(
|
||||
TursoAutomaticSyncState.Stopped,
|
||||
Attempt: 0,
|
||||
LastAttempt: null,
|
||||
LastSuccess: null,
|
||||
LastPullAppliedChanges: null,
|
||||
LastException: null,
|
||||
NextAttempt: null);
|
||||
}
|
||||
|
||||
public sealed class TursoAutomaticSyncStatusChangedEventArgs(TursoAutomaticSyncStatus status) : EventArgs
|
||||
{
|
||||
public TursoAutomaticSyncStatus Status { get; } = status;
|
||||
}
|
||||
@@ -13,9 +13,16 @@ public class TursoConnection : DbConnection
|
||||
private TursoDatabaseHandle? _turso;
|
||||
private TursoRemoteClient? _remoteClient;
|
||||
private TursoSyncDatabase? _syncDatabase;
|
||||
private bool _ownsSyncDatabase;
|
||||
private TursoReplicaRegistry.Lease? _replicaLease;
|
||||
private TursoAutomaticSyncCoordinator? _automaticSyncCoordinator;
|
||||
private readonly HashSet<TursoDataReader> _syncReaders = [];
|
||||
private readonly object _syncReadersLock = new();
|
||||
private readonly object _automaticSyncLock = new();
|
||||
private readonly System.Collections.Concurrent.ConcurrentQueue<AutomaticSyncNotification>
|
||||
_automaticSyncNotifications = new();
|
||||
private TursoAutomaticSyncStatus _automaticSyncStatus = TursoAutomaticSyncStatus.Stopped;
|
||||
private long _automaticSyncGeneration;
|
||||
private int _automaticSyncNotificationDrainScheduled;
|
||||
private TursoConnectionOptions _connectionOptions;
|
||||
private bool _disposed;
|
||||
private bool _closing;
|
||||
@@ -120,8 +127,10 @@ public class TursoConnection : DbConnection
|
||||
using (_syncDatabase?.EnterConnectionOperation())
|
||||
_turso?.Dispose();
|
||||
_turso = null;
|
||||
ReleaseSyncDatabase();
|
||||
var automaticSyncFailure = ReleaseSyncDatabase();
|
||||
_readUncommitted = false;
|
||||
if (automaticSyncFailure is not null)
|
||||
System.Runtime.ExceptionServices.ExceptionDispatchInfo.Capture(automaticSyncFailure).Throw();
|
||||
}
|
||||
finally
|
||||
{
|
||||
@@ -131,11 +140,16 @@ public class TursoConnection : DbConnection
|
||||
|
||||
protected override void Dispose(bool disposing)
|
||||
{
|
||||
if (disposing)
|
||||
Close();
|
||||
|
||||
_disposed = true;
|
||||
base.Dispose(disposing);
|
||||
try
|
||||
{
|
||||
if (disposing)
|
||||
Close();
|
||||
}
|
||||
finally
|
||||
{
|
||||
_disposed = true;
|
||||
base.Dispose(disposing);
|
||||
}
|
||||
}
|
||||
|
||||
protected override DbTransaction BeginDbTransaction(IsolationLevel isolationLevel)
|
||||
@@ -205,6 +219,15 @@ public class TursoConnection : DbConnection
|
||||
|
||||
internal TursoDatabaseHandle Turso => _turso ?? throw new InvalidOperationException("Turso database is closed.");
|
||||
|
||||
internal TursoSyncDatabase? SyncDatabase => _syncDatabase;
|
||||
|
||||
public TursoAutomaticSyncStatus AutomaticSyncStatus =>
|
||||
Volatile.Read(ref _automaticSyncCoordinator)?.Status ?? Volatile.Read(ref _automaticSyncStatus);
|
||||
|
||||
public event EventHandler<TursoAutomaticSyncStatusChangedEventArgs>? AutomaticSyncStatusChanged;
|
||||
|
||||
internal TimeProvider AutomaticSyncTimeProvider { get; set; } = TimeProvider.System;
|
||||
|
||||
internal static TursoConnection CreateSyncConnection(
|
||||
TursoDatabaseHandle connectionHandle,
|
||||
TursoSyncDatabase syncDatabase)
|
||||
@@ -399,19 +422,30 @@ public class TursoConnection : DbConnection
|
||||
|
||||
private void OpenReplica()
|
||||
{
|
||||
ValidateReplicaOptions();
|
||||
var syncDatabase = TursoSyncDatabase.Create(CreateReplicaOptions());
|
||||
var lease = TursoReplicaRegistry
|
||||
.AcquireAsync(
|
||||
CreateReplicaOptions(),
|
||||
_connectionOptions.Pooling,
|
||||
TimeSpan.FromSeconds(_connectionOptions.SyncInterval),
|
||||
AutomaticSyncTimeProvider,
|
||||
CancellationToken.None)
|
||||
.GetAwaiter()
|
||||
.GetResult();
|
||||
var syncDatabase = lease.Database;
|
||||
var connectionCreated = false;
|
||||
try
|
||||
{
|
||||
_turso = syncDatabase.ConnectHandleAsync(CancellationToken.None).GetAwaiter().GetResult();
|
||||
_syncDatabase = syncDatabase;
|
||||
_ownsSyncDatabase = true;
|
||||
connectionCreated = true;
|
||||
AttachReplicaLease(lease);
|
||||
}
|
||||
catch
|
||||
{
|
||||
_turso?.Dispose();
|
||||
_turso = null;
|
||||
syncDatabase.Dispose();
|
||||
if (connectionCreated)
|
||||
syncDatabase.ReleaseConnection();
|
||||
_ = lease.Release();
|
||||
throw;
|
||||
}
|
||||
}
|
||||
@@ -422,21 +456,29 @@ public class TursoConnection : DbConnection
|
||||
if (_turso is not null || _remoteClient is not null)
|
||||
throw new InvalidOperationException("The connection is already open.");
|
||||
|
||||
ValidateReplicaOptions();
|
||||
var syncDatabase = await TursoSyncDatabase
|
||||
.CreateAsync(CreateReplicaOptions(), cancellationToken)
|
||||
var lease = await TursoReplicaRegistry
|
||||
.AcquireAsync(
|
||||
CreateReplicaOptions(),
|
||||
_connectionOptions.Pooling,
|
||||
TimeSpan.FromSeconds(_connectionOptions.SyncInterval),
|
||||
AutomaticSyncTimeProvider,
|
||||
cancellationToken)
|
||||
.ConfigureAwait(false);
|
||||
var syncDatabase = lease.Database;
|
||||
var connectionCreated = false;
|
||||
try
|
||||
{
|
||||
_turso = await syncDatabase.ConnectHandleAsync(cancellationToken).ConfigureAwait(false);
|
||||
_syncDatabase = syncDatabase;
|
||||
_ownsSyncDatabase = true;
|
||||
connectionCreated = true;
|
||||
AttachReplicaLease(lease);
|
||||
}
|
||||
catch
|
||||
{
|
||||
_turso?.Dispose();
|
||||
_turso = null;
|
||||
await syncDatabase.DisposeAsync().ConfigureAwait(false);
|
||||
if (connectionCreated)
|
||||
syncDatabase.ReleaseConnection();
|
||||
_ = lease.Release();
|
||||
throw;
|
||||
}
|
||||
}
|
||||
@@ -497,12 +539,42 @@ public class TursoConnection : DbConnection
|
||||
};
|
||||
}
|
||||
|
||||
private void ValidateReplicaOptions()
|
||||
private void AttachReplicaLease(TursoReplicaRegistry.Lease lease)
|
||||
{
|
||||
if (_connectionOptions.Pooling)
|
||||
throw new NotSupportedException("Pooling is not supported for embedded replica connections yet. Set Pooling=False.");
|
||||
if (_connectionOptions.SyncInterval != 0)
|
||||
throw new NotSupportedException("Automatic sync is not supported for embedded replica connections yet. Set Sync Interval=0 and call SyncAsync explicitly.");
|
||||
EventHandler<TursoAutomaticSyncStatusChangedEventArgs>? handlers;
|
||||
TursoAutomaticSyncStatus status;
|
||||
long generation;
|
||||
lock (_automaticSyncLock)
|
||||
{
|
||||
_replicaLease = lease;
|
||||
_syncDatabase = lease.Database;
|
||||
Volatile.Write(ref _automaticSyncCoordinator, lease.Coordinator);
|
||||
lease.Coordinator.StatusChanged += OnAutomaticSyncStatusChanged;
|
||||
status = lease.Coordinator.Status;
|
||||
Volatile.Write(ref _automaticSyncStatus, status);
|
||||
generation = Interlocked.Increment(ref _automaticSyncGeneration);
|
||||
handlers = AutomaticSyncStatusChanged;
|
||||
QueueAutomaticSyncStatusChanged(handlers, status, generation);
|
||||
}
|
||||
}
|
||||
|
||||
private void OnAutomaticSyncStatusChanged(
|
||||
object? sender,
|
||||
TursoAutomaticSyncStatusChangedEventArgs args)
|
||||
{
|
||||
EventHandler<TursoAutomaticSyncStatusChangedEventArgs>? handlers;
|
||||
long generation;
|
||||
lock (_automaticSyncLock)
|
||||
{
|
||||
if (!ReferenceEquals(sender, _automaticSyncCoordinator))
|
||||
return;
|
||||
|
||||
Volatile.Write(ref _automaticSyncStatus, args.Status);
|
||||
generation = Volatile.Read(ref _automaticSyncGeneration);
|
||||
handlers = AutomaticSyncStatusChanged;
|
||||
}
|
||||
|
||||
QueueAutomaticSyncStatusChanged(handlers, args.Status, generation);
|
||||
}
|
||||
|
||||
private void ValidateLocalOnlyOptions()
|
||||
@@ -564,18 +636,104 @@ public class TursoConnection : DbConnection
|
||||
_readUncommitted = false;
|
||||
}
|
||||
|
||||
private void ReleaseSyncDatabase()
|
||||
private Exception? ReleaseSyncDatabase()
|
||||
{
|
||||
var syncDatabase = _syncDatabase;
|
||||
if (syncDatabase is null)
|
||||
return null;
|
||||
|
||||
EventHandler<TursoAutomaticSyncStatusChangedEventArgs>? handlers;
|
||||
TursoAutomaticSyncStatus stoppedStatus;
|
||||
long generation;
|
||||
lock (_automaticSyncLock)
|
||||
{
|
||||
var coordinator = _automaticSyncCoordinator;
|
||||
Volatile.Write(ref _automaticSyncCoordinator, null);
|
||||
if (coordinator is not null)
|
||||
coordinator.StatusChanged -= OnAutomaticSyncStatusChanged;
|
||||
|
||||
stoppedStatus = (coordinator?.Status ?? _automaticSyncStatus) with
|
||||
{
|
||||
State = TursoAutomaticSyncState.Stopped,
|
||||
Attempt = 0,
|
||||
NextAttempt = null,
|
||||
};
|
||||
Volatile.Write(ref _automaticSyncStatus, stoppedStatus);
|
||||
generation = Volatile.Read(ref _automaticSyncGeneration);
|
||||
handlers = AutomaticSyncStatusChanged;
|
||||
}
|
||||
|
||||
_syncDatabase = null;
|
||||
syncDatabase.ReleaseConnection();
|
||||
var lease = _replicaLease;
|
||||
_replicaLease = null;
|
||||
var failure = lease?.Release();
|
||||
QueueAutomaticSyncStatusChanged(handlers, stoppedStatus, generation);
|
||||
return failure;
|
||||
}
|
||||
|
||||
private void QueueAutomaticSyncStatusChanged(
|
||||
EventHandler<TursoAutomaticSyncStatusChangedEventArgs>? handlers,
|
||||
TursoAutomaticSyncStatus status,
|
||||
long generation)
|
||||
{
|
||||
if (handlers is null)
|
||||
return;
|
||||
|
||||
var ownsSyncDatabase = _ownsSyncDatabase;
|
||||
_syncDatabase = null;
|
||||
_ownsSyncDatabase = false;
|
||||
syncDatabase.ReleaseConnection();
|
||||
if (ownsSyncDatabase)
|
||||
syncDatabase.Dispose();
|
||||
_automaticSyncNotifications.Enqueue(new AutomaticSyncNotification(
|
||||
status,
|
||||
generation,
|
||||
handlers));
|
||||
ScheduleAutomaticSyncNotificationDrain();
|
||||
}
|
||||
|
||||
private void ScheduleAutomaticSyncNotificationDrain()
|
||||
{
|
||||
if (Interlocked.Exchange(ref _automaticSyncNotificationDrainScheduled, 1) != 0)
|
||||
return;
|
||||
|
||||
ThreadPool.UnsafeQueueUserWorkItem(
|
||||
static connection => connection.DrainAutomaticSyncNotifications(),
|
||||
this,
|
||||
preferLocal: false);
|
||||
}
|
||||
|
||||
private void DrainAutomaticSyncNotifications()
|
||||
{
|
||||
try
|
||||
{
|
||||
while (_automaticSyncNotifications.TryDequeue(out var notification))
|
||||
{
|
||||
if (notification.Generation != Volatile.Read(ref _automaticSyncGeneration))
|
||||
continue;
|
||||
|
||||
var currentStatus = Volatile.Read(ref _automaticSyncStatus);
|
||||
if (currentStatus.State == TursoAutomaticSyncState.Stopped
|
||||
&& !ReferenceEquals(currentStatus, notification.Status))
|
||||
{
|
||||
continue;
|
||||
}
|
||||
|
||||
var args = new TursoAutomaticSyncStatusChangedEventArgs(notification.Status);
|
||||
foreach (var callback in notification.Handlers.GetInvocationList())
|
||||
{
|
||||
try
|
||||
{
|
||||
((EventHandler<TursoAutomaticSyncStatusChangedEventArgs>)callback)(this, args);
|
||||
}
|
||||
catch
|
||||
{
|
||||
// Observers cannot stop synchronization.
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
finally
|
||||
{
|
||||
Volatile.Write(ref _automaticSyncNotificationDrainScheduled, 0);
|
||||
if (!_automaticSyncNotifications.IsEmpty)
|
||||
ScheduleAutomaticSyncNotificationDrain();
|
||||
}
|
||||
}
|
||||
|
||||
private void CloseSyncReaders()
|
||||
@@ -587,4 +745,9 @@ public class TursoConnection : DbConnection
|
||||
foreach (var reader in readers)
|
||||
reader.Dispose();
|
||||
}
|
||||
|
||||
private sealed record AutomaticSyncNotification(
|
||||
TursoAutomaticSyncStatus Status,
|
||||
long Generation,
|
||||
EventHandler<TursoAutomaticSyncStatusChangedEventArgs> Handlers);
|
||||
}
|
||||
|
||||
@@ -5,6 +5,8 @@ namespace Turso;
|
||||
|
||||
public class TursoConnectionOptions
|
||||
{
|
||||
private const int MaximumSyncIntervalSeconds = 4_294_967;
|
||||
|
||||
private readonly TursoConnectionStringBuilder _builder;
|
||||
|
||||
private TursoConnectionOptions(TursoConnectionStringBuilder builder)
|
||||
@@ -32,7 +34,22 @@ public class TursoConnectionOptions
|
||||
|
||||
public bool ReadYourWrites => _builder.ReadYourWrites;
|
||||
|
||||
public int SyncInterval => _builder.SyncInterval;
|
||||
public int SyncInterval
|
||||
{
|
||||
get
|
||||
{
|
||||
var value = _builder.SyncInterval;
|
||||
if (value is < 0 or > MaximumSyncIntervalSeconds)
|
||||
{
|
||||
throw new ArgumentOutOfRangeException(
|
||||
nameof(SyncInterval),
|
||||
value,
|
||||
$"Sync Interval must be between 0 and {MaximumSyncIntervalSeconds} seconds.");
|
||||
}
|
||||
|
||||
return value;
|
||||
}
|
||||
}
|
||||
|
||||
public string SyncClientName => _builder.SyncClientName;
|
||||
|
||||
|
||||
274
bindings/dotnet/src/Turso.Data/TursoReplicaRegistry.cs
Normal file
274
bindings/dotnet/src/Turso.Data/TursoReplicaRegistry.cs
Normal file
@@ -0,0 +1,274 @@
|
||||
using System.Runtime.CompilerServices;
|
||||
using System.Security.Cryptography;
|
||||
using System.Text;
|
||||
|
||||
namespace Turso;
|
||||
|
||||
internal static class TursoReplicaRegistry
|
||||
{
|
||||
private static readonly object Gate = new();
|
||||
private static readonly Dictionary<string, Entry> Entries = new(
|
||||
OperatingSystem.IsWindows() ? StringComparer.OrdinalIgnoreCase : StringComparer.Ordinal);
|
||||
|
||||
public static async Task<Lease> AcquireAsync(
|
||||
TursoSyncDatabaseOptions options,
|
||||
bool pooling,
|
||||
TimeSpan syncInterval,
|
||||
TimeProvider timeProvider,
|
||||
CancellationToken cancellationToken)
|
||||
{
|
||||
ArgumentNullException.ThrowIfNull(options);
|
||||
if (options.Path == ":memory:")
|
||||
{
|
||||
var database = await TursoSyncDatabase
|
||||
.CreateAsync(options, cancellationToken)
|
||||
.ConfigureAwait(false);
|
||||
return Lease.CreateStandalone(
|
||||
database,
|
||||
new TursoAutomaticSyncCoordinator(database, syncInterval, timeProvider));
|
||||
}
|
||||
|
||||
var path = Path.GetFullPath(options.Path);
|
||||
var fingerprint = Fingerprint.Create(options, syncInterval);
|
||||
Entry entry;
|
||||
lock (Gate)
|
||||
{
|
||||
if (Entries.TryGetValue(path, out entry!))
|
||||
{
|
||||
if (entry.Closing)
|
||||
throw new InvalidOperationException($"Embedded replica '{path}' is closing.");
|
||||
if (!pooling || !entry.Pooling)
|
||||
throw new InvalidOperationException($"Embedded replica '{path}' is already open exclusively.");
|
||||
if (entry.Fingerprint != fingerprint)
|
||||
throw new InvalidOperationException($"Embedded replica '{path}' is already open with different options.");
|
||||
|
||||
checked
|
||||
{
|
||||
entry.ReferenceCount++;
|
||||
}
|
||||
}
|
||||
else
|
||||
{
|
||||
entry = new Entry(path, pooling, fingerprint)
|
||||
{
|
||||
ReferenceCount = 1,
|
||||
};
|
||||
entry.Initialization = InitializeAsync(entry, options, syncInterval, timeProvider);
|
||||
Entries.Add(path, entry);
|
||||
}
|
||||
}
|
||||
|
||||
try
|
||||
{
|
||||
var holder = await entry.Initialization.WaitAsync(cancellationToken).ConfigureAwait(false);
|
||||
return new Lease(entry, holder);
|
||||
}
|
||||
catch
|
||||
{
|
||||
ReleaseReference(entry);
|
||||
throw;
|
||||
}
|
||||
}
|
||||
|
||||
private static async Task<Holder> InitializeAsync(
|
||||
Entry entry,
|
||||
TursoSyncDatabaseOptions options,
|
||||
TimeSpan syncInterval,
|
||||
TimeProvider timeProvider)
|
||||
{
|
||||
try
|
||||
{
|
||||
var database = await TursoSyncDatabase
|
||||
.CreateAsync(options, entry.InitializationCancellation.Token)
|
||||
.ConfigureAwait(false);
|
||||
var holder = new Holder(
|
||||
database,
|
||||
new TursoAutomaticSyncCoordinator(database, syncInterval, timeProvider));
|
||||
lock (Gate)
|
||||
entry.Holder = holder;
|
||||
return holder;
|
||||
}
|
||||
catch
|
||||
{
|
||||
lock (Gate)
|
||||
{
|
||||
if (Entries.TryGetValue(entry.Path, out var current) && ReferenceEquals(current, entry))
|
||||
Entries.Remove(entry.Path);
|
||||
}
|
||||
throw;
|
||||
}
|
||||
}
|
||||
|
||||
private static Exception? ReleaseReference(Entry entry)
|
||||
{
|
||||
Holder? holder;
|
||||
lock (Gate)
|
||||
{
|
||||
if (entry.ReferenceCount <= 0)
|
||||
throw new InvalidOperationException("Embedded replica lease ownership is unbalanced.");
|
||||
entry.ReferenceCount--;
|
||||
if (entry.ReferenceCount != 0)
|
||||
{
|
||||
var status = entry.Holder?.Coordinator.Status;
|
||||
return status?.State == TursoAutomaticSyncState.Faulted
|
||||
? status.LastException
|
||||
: null;
|
||||
}
|
||||
|
||||
entry.Closing = true;
|
||||
entry.InitializationCancellation.Cancel();
|
||||
holder = entry.Holder;
|
||||
if (holder is null)
|
||||
{
|
||||
_ = DisposeAfterInitializationAsync(entry);
|
||||
return null;
|
||||
}
|
||||
}
|
||||
|
||||
var failure = DisposeHolder(holder);
|
||||
RemoveClosingEntry(entry);
|
||||
return failure;
|
||||
}
|
||||
|
||||
private static async Task DisposeAfterInitializationAsync(Entry entry)
|
||||
{
|
||||
Holder? holder = null;
|
||||
try
|
||||
{
|
||||
holder = await entry.Initialization.ConfigureAwait(false);
|
||||
}
|
||||
catch
|
||||
{
|
||||
// Initialization failure already removed the entry.
|
||||
}
|
||||
|
||||
if (holder is not null)
|
||||
_ = DisposeHolder(holder);
|
||||
RemoveClosingEntry(entry);
|
||||
}
|
||||
|
||||
private static Exception? DisposeHolder(Holder holder)
|
||||
{
|
||||
var failure = holder.Coordinator.Stop();
|
||||
holder.Database.Dispose();
|
||||
return failure;
|
||||
}
|
||||
|
||||
private static void RemoveClosingEntry(Entry entry)
|
||||
{
|
||||
lock (Gate)
|
||||
{
|
||||
if (Entries.TryGetValue(entry.Path, out var current) && ReferenceEquals(current, entry))
|
||||
Entries.Remove(entry.Path);
|
||||
}
|
||||
entry.InitializationCancellation.Dispose();
|
||||
}
|
||||
|
||||
internal sealed class Lease : IDisposable
|
||||
{
|
||||
private readonly Entry? _entry;
|
||||
private readonly Holder _holder;
|
||||
private int _disposed;
|
||||
|
||||
internal Lease(Entry? entry, Holder holder)
|
||||
{
|
||||
_entry = entry;
|
||||
_holder = holder;
|
||||
}
|
||||
|
||||
public TursoSyncDatabase Database => _holder.Database;
|
||||
|
||||
public TursoAutomaticSyncCoordinator Coordinator => _holder.Coordinator;
|
||||
|
||||
public Exception? Release()
|
||||
{
|
||||
if (Interlocked.Exchange(ref _disposed, 1) != 0)
|
||||
return null;
|
||||
if (_entry is not null)
|
||||
return ReleaseReference(_entry);
|
||||
|
||||
return DisposeHolder(_holder);
|
||||
}
|
||||
|
||||
public void Dispose()
|
||||
{
|
||||
_ = Release();
|
||||
}
|
||||
|
||||
public static Lease CreateStandalone(
|
||||
TursoSyncDatabase database,
|
||||
TursoAutomaticSyncCoordinator coordinator)
|
||||
{
|
||||
return new Lease(null, new Holder(database, coordinator));
|
||||
}
|
||||
}
|
||||
|
||||
internal sealed class Entry(string path, bool pooling, Fingerprint fingerprint)
|
||||
{
|
||||
public string Path { get; } = path;
|
||||
public bool Pooling { get; } = pooling;
|
||||
public Fingerprint Fingerprint { get; } = fingerprint;
|
||||
public Task<Holder> Initialization { get; set; } = null!;
|
||||
public Holder? Holder { get; set; }
|
||||
public int ReferenceCount { get; set; }
|
||||
public bool Closing { get; set; }
|
||||
public CancellationTokenSource InitializationCancellation { get; } = new();
|
||||
}
|
||||
|
||||
internal sealed record Holder(
|
||||
TursoSyncDatabase Database,
|
||||
TursoAutomaticSyncCoordinator Coordinator);
|
||||
|
||||
internal sealed record Fingerprint(
|
||||
string RemoteUri,
|
||||
string ClientName,
|
||||
long? LongPollMilliseconds,
|
||||
bool BootstrapIfEmpty,
|
||||
int? PartialPrefix,
|
||||
string? PartialQuery,
|
||||
long? PartialSegmentSize,
|
||||
bool PartialPrefetch,
|
||||
TursoRemoteEncryptionCipher? EncryptionCipher,
|
||||
string? EncryptionKeyHash,
|
||||
string? AuthTokenHash,
|
||||
long? PushOperationsThreshold,
|
||||
long? PullBytesThreshold,
|
||||
bool ForceLogicalMvccPull,
|
||||
string? ExperimentalFeatures,
|
||||
long SyncIntervalMilliseconds,
|
||||
int HttpClientIdentity)
|
||||
{
|
||||
public static Fingerprint Create(
|
||||
TursoSyncDatabaseOptions options,
|
||||
TimeSpan syncInterval)
|
||||
{
|
||||
return new Fingerprint(
|
||||
options.GetNormalizedRemoteUri().ToString(),
|
||||
options.ClientName,
|
||||
options.LongPollTimeout is null
|
||||
? null
|
||||
: checked((long)options.LongPollTimeout.Value.TotalMilliseconds),
|
||||
options.BootstrapIfEmpty,
|
||||
options.PartialSync?.PrefixLength,
|
||||
options.PartialSync?.Query,
|
||||
options.PartialSync?.SegmentSize,
|
||||
options.PartialSync?.Prefetch ?? false,
|
||||
options.RemoteEncryption?.Cipher,
|
||||
HashSecret(options.RemoteEncryption?.Key),
|
||||
HashSecret(options.AuthToken),
|
||||
options.PushOperationsThreshold,
|
||||
options.PullBytesThreshold,
|
||||
options.ForceLogicalMvccPull,
|
||||
options.ExperimentalFeatures,
|
||||
checked((long)syncInterval.TotalMilliseconds),
|
||||
options.HttpClient is null ? 0 : RuntimeHelpers.GetHashCode(options.HttpClient));
|
||||
}
|
||||
|
||||
private static string? HashSecret(string? value)
|
||||
{
|
||||
return string.IsNullOrEmpty(value)
|
||||
? null
|
||||
: Convert.ToHexString(SHA256.HashData(Encoding.UTF8.GetBytes(value)));
|
||||
}
|
||||
}
|
||||
}
|
||||
186
bindings/dotnet/src/Turso.Tests/TursoAutomaticSyncTests.cs
Normal file
186
bindings/dotnet/src/Turso.Tests/TursoAutomaticSyncTests.cs
Normal file
@@ -0,0 +1,186 @@
|
||||
using System.Collections.Concurrent;
|
||||
using System.Net;
|
||||
using AwesomeAssertions;
|
||||
|
||||
namespace Turso.Tests;
|
||||
|
||||
[NonParallelizable]
|
||||
public sealed class TursoAutomaticSyncTests
|
||||
{
|
||||
[Test]
|
||||
public async Task TerminalAutomaticSyncFailureIsObservableBeforeClose()
|
||||
{
|
||||
using var httpClient = new HttpClient(new FailingSyncHandler());
|
||||
TursoConnection.SyncHttpClientFactory = () => httpClient;
|
||||
var connection = new TursoConnection(
|
||||
"Data Source=turso://example.test;Replica Path=:memory:;"
|
||||
+ "Bootstrap If Empty=False;Sync Interval=1");
|
||||
var faulted = new TaskCompletionSource<TursoAutomaticSyncStatus>(
|
||||
TaskCreationOptions.RunContinuationsAsynchronously);
|
||||
connection.AutomaticSyncStatusChanged += (_, _) => throw new InvalidOperationException("observer failure");
|
||||
connection.AutomaticSyncStatusChanged += (_, args) =>
|
||||
{
|
||||
if (args.Status.State == TursoAutomaticSyncState.Faulted)
|
||||
faulted.TrySetResult(args.Status);
|
||||
};
|
||||
|
||||
try
|
||||
{
|
||||
connection.Open();
|
||||
connection.AutomaticSyncStatus.State.Should().Be(TursoAutomaticSyncState.Waiting);
|
||||
|
||||
var status = await faulted.Task.WaitAsync(TimeSpan.FromSeconds(5));
|
||||
|
||||
status.LastAttempt.Should().NotBeNull();
|
||||
status.LastException.Should().BeOfType<TursoSyncException>()
|
||||
.Which.Operation.Should().Be(TursoSyncOperationKind.Pull);
|
||||
status.NextAttempt.Should().BeNull();
|
||||
connection.AutomaticSyncStatus.Should().Be(status);
|
||||
connection.Invoking(x => x.Dispose()).Should().Throw<TursoSyncException>();
|
||||
connection.Invoking(x => x.Open()).Should().Throw<ObjectDisposedException>();
|
||||
}
|
||||
finally
|
||||
{
|
||||
TursoConnection.SyncHttpClientFactory = null;
|
||||
connection.Dispose();
|
||||
}
|
||||
}
|
||||
|
||||
[Test]
|
||||
public async Task StatusHandlerCanCloseTheLastReplicaWithoutDeadlock()
|
||||
{
|
||||
using var httpClient = new HttpClient(new FailingSyncHandler());
|
||||
TursoConnection.SyncHttpClientFactory = () => httpClient;
|
||||
var connection = new TursoConnection(
|
||||
"Data Source=turso://example.test;Replica Path=:memory:;"
|
||||
+ "Bootstrap If Empty=False;Sync Interval=1");
|
||||
var states = new ConcurrentQueue<TursoAutomaticSyncState>();
|
||||
var closed = new TaskCompletionSource<Exception?>(
|
||||
TaskCreationOptions.RunContinuationsAsynchronously);
|
||||
var stopped = new TaskCompletionSource(
|
||||
TaskCreationOptions.RunContinuationsAsynchronously);
|
||||
connection.AutomaticSyncStatusChanged += (_, args) =>
|
||||
{
|
||||
if (args.Status.State != TursoAutomaticSyncState.Faulted)
|
||||
return;
|
||||
try
|
||||
{
|
||||
connection.Close();
|
||||
closed.TrySetResult(null);
|
||||
}
|
||||
catch (Exception exception)
|
||||
{
|
||||
closed.TrySetResult(exception);
|
||||
}
|
||||
};
|
||||
connection.AutomaticSyncStatusChanged += (_, args) =>
|
||||
{
|
||||
states.Enqueue(args.Status.State);
|
||||
if (args.Status.State == TursoAutomaticSyncState.Stopped)
|
||||
stopped.TrySetResult();
|
||||
};
|
||||
|
||||
try
|
||||
{
|
||||
connection.Open();
|
||||
|
||||
var closeError = await closed.Task.WaitAsync(TimeSpan.FromSeconds(5));
|
||||
await stopped.Task.WaitAsync(TimeSpan.FromSeconds(5));
|
||||
|
||||
closeError.Should().BeOfType<TursoSyncException>();
|
||||
connection.State.Should().Be(System.Data.ConnectionState.Closed);
|
||||
connection.AutomaticSyncStatus.State.Should().Be(TursoAutomaticSyncState.Stopped);
|
||||
states.Should().Contain(TursoAutomaticSyncState.Waiting)
|
||||
.And.Contain(TursoAutomaticSyncState.Faulted)
|
||||
.And.Contain(TursoAutomaticSyncState.Stopped);
|
||||
await Task.Delay(100);
|
||||
connection.AutomaticSyncStatus.State.Should().Be(TursoAutomaticSyncState.Stopped);
|
||||
states.SkipWhile(state => state != TursoAutomaticSyncState.Stopped)
|
||||
.Should().OnlyContain(state => state == TursoAutomaticSyncState.Stopped);
|
||||
}
|
||||
finally
|
||||
{
|
||||
TursoConnection.SyncHttpClientFactory = null;
|
||||
connection.Dispose();
|
||||
}
|
||||
}
|
||||
|
||||
[TestCase(TransientFailureKind.Transport)]
|
||||
[TestCase(TransientFailureKind.Timeout)]
|
||||
public async Task TransientFailuresRetryTwiceBeforeBecomingTerminal(
|
||||
TransientFailureKind failureKind)
|
||||
{
|
||||
var handler = new TransientFailureHandler(failureKind);
|
||||
using var httpClient = new HttpClient(handler);
|
||||
TursoConnection.SyncHttpClientFactory = () => httpClient;
|
||||
var connection = new TursoConnection(
|
||||
"Data Source=turso://example.test;Replica Path=:memory:;"
|
||||
+ "Bootstrap If Empty=False;Sync Interval=1");
|
||||
var faulted = new TaskCompletionSource<TursoAutomaticSyncStatus>(
|
||||
TaskCreationOptions.RunContinuationsAsynchronously);
|
||||
var states = new ConcurrentQueue<TursoAutomaticSyncState>();
|
||||
connection.AutomaticSyncStatusChanged += (_, args) =>
|
||||
{
|
||||
states.Enqueue(args.Status.State);
|
||||
if (args.Status.State == TursoAutomaticSyncState.Faulted)
|
||||
faulted.TrySetResult(args.Status);
|
||||
};
|
||||
|
||||
try
|
||||
{
|
||||
connection.Open();
|
||||
|
||||
var status = await faulted.Task.WaitAsync(TimeSpan.FromSeconds(5));
|
||||
|
||||
handler.RequestCount.Should().Be(3);
|
||||
status.Attempt.Should().Be(3);
|
||||
status.LastException.Should().BeOfType<TursoSyncException>();
|
||||
states.Should().Contain(TursoAutomaticSyncState.Retrying);
|
||||
connection.Invoking(x => x.Close()).Should().Throw<TursoSyncException>();
|
||||
}
|
||||
finally
|
||||
{
|
||||
TursoConnection.SyncHttpClientFactory = null;
|
||||
connection.Dispose();
|
||||
}
|
||||
}
|
||||
|
||||
private sealed class FailingSyncHandler : HttpMessageHandler
|
||||
{
|
||||
protected override Task<HttpResponseMessage> SendAsync(
|
||||
HttpRequestMessage request,
|
||||
CancellationToken cancellationToken)
|
||||
{
|
||||
return Task.FromResult(new HttpResponseMessage(HttpStatusCode.InternalServerError)
|
||||
{
|
||||
Content = new ByteArrayContent([]),
|
||||
});
|
||||
}
|
||||
}
|
||||
|
||||
private sealed class TransientFailureHandler(TransientFailureKind failureKind) : HttpMessageHandler
|
||||
{
|
||||
public int RequestCount { get; private set; }
|
||||
|
||||
protected override Task<HttpResponseMessage> SendAsync(
|
||||
HttpRequestMessage request,
|
||||
CancellationToken cancellationToken)
|
||||
{
|
||||
RequestCount++;
|
||||
throw failureKind switch
|
||||
{
|
||||
TransientFailureKind.Transport =>
|
||||
new HttpRequestException("transient transport failure"),
|
||||
TransientFailureKind.Timeout =>
|
||||
new TaskCanceledException("request timeout", new TimeoutException()),
|
||||
_ => throw new ArgumentOutOfRangeException(nameof(failureKind)),
|
||||
};
|
||||
}
|
||||
}
|
||||
|
||||
public enum TransientFailureKind
|
||||
{
|
||||
Transport,
|
||||
Timeout,
|
||||
}
|
||||
}
|
||||
75
bindings/dotnet/src/Turso.Tests/TursoCloudAcceptanceTests.cs
Normal file
75
bindings/dotnet/src/Turso.Tests/TursoCloudAcceptanceTests.cs
Normal file
@@ -0,0 +1,75 @@
|
||||
using AwesomeAssertions;
|
||||
|
||||
namespace Turso.Tests;
|
||||
|
||||
[NonParallelizable]
|
||||
public sealed class TursoCloudAcceptanceTests
|
||||
{
|
||||
[Test]
|
||||
public async Task AutomaticSyncPullsRemoteChanges()
|
||||
{
|
||||
var (remoteUrl, authToken) = GetCloudCredentials();
|
||||
var tableName = "dotnet_interval_" + Guid.NewGuid().ToString("N");
|
||||
var replicaDirectory = NewReplicaDirectory();
|
||||
var replicaPath = Path.Combine(replicaDirectory, "replica.db");
|
||||
var remoteConnectionString = $"Data Source={remoteUrl};Auth Token={authToken}";
|
||||
|
||||
await using var remote = new TursoConnection(remoteConnectionString);
|
||||
await remote.OpenAsync();
|
||||
try
|
||||
{
|
||||
await ExecuteNonQueryAsync(remote, $"CREATE TABLE {tableName}(id INTEGER PRIMARY KEY, value INTEGER)");
|
||||
await ExecuteNonQueryAsync(remote, $"INSERT INTO {tableName} VALUES (1, 1)");
|
||||
await using var replica = new TursoConnection(
|
||||
remoteConnectionString
|
||||
+ $";Replica Path={replicaPath};Pooling=False;Sync Interval=1");
|
||||
var synchronized = new TaskCompletionSource<TursoAutomaticSyncStatus>(
|
||||
TaskCreationOptions.RunContinuationsAsynchronously);
|
||||
replica.AutomaticSyncStatusChanged += (_, args) =>
|
||||
{
|
||||
if (args.Status.LastPullAppliedChanges == true)
|
||||
synchronized.TrySetResult(args.Status);
|
||||
};
|
||||
await replica.OpenAsync();
|
||||
|
||||
await ExecuteNonQueryAsync(remote, $"UPDATE {tableName} SET value = 2 WHERE id = 1");
|
||||
var status = await synchronized.Task.WaitAsync(TimeSpan.FromSeconds(10));
|
||||
|
||||
status.LastSuccess.Should().NotBeNull();
|
||||
await using var verify = replica.CreateCommand();
|
||||
verify.CommandText = $"SELECT value FROM {tableName} WHERE id = 1";
|
||||
(await verify.ExecuteScalarAsync()).Should().Be(2L);
|
||||
}
|
||||
finally
|
||||
{
|
||||
await ExecuteNonQueryAsync(remote, $"DROP TABLE IF EXISTS {tableName}");
|
||||
Directory.Delete(replicaDirectory, recursive: true);
|
||||
}
|
||||
}
|
||||
|
||||
private static async Task ExecuteNonQueryAsync(TursoConnection connection, string sql)
|
||||
{
|
||||
await using var command = connection.CreateCommand();
|
||||
command.CommandText = sql;
|
||||
await command.ExecuteNonQueryAsync();
|
||||
}
|
||||
|
||||
private static (string RemoteUrl, string AuthToken) GetCloudCredentials()
|
||||
{
|
||||
var remoteUrl = Environment.GetEnvironmentVariable("TURSO_REMOTE_URL");
|
||||
var authToken = Environment.GetEnvironmentVariable("TURSO_AUTH_TOKEN");
|
||||
if (string.IsNullOrWhiteSpace(remoteUrl) || string.IsNullOrWhiteSpace(authToken))
|
||||
Assert.Ignore("Set TURSO_REMOTE_URL and TURSO_AUTH_TOKEN to run the Turso Cloud acceptance tests.");
|
||||
|
||||
return (remoteUrl, authToken);
|
||||
}
|
||||
|
||||
private static string NewReplicaDirectory()
|
||||
{
|
||||
var path = Path.Combine(
|
||||
TestContext.CurrentContext.WorkDirectory,
|
||||
"turso-cloud-interval-" + Guid.NewGuid().ToString("N"));
|
||||
Directory.CreateDirectory(path);
|
||||
return path;
|
||||
}
|
||||
}
|
||||
@@ -82,16 +82,17 @@ public sealed class TursoReplicaConnectionStringTests
|
||||
.WithMessage("*exactly one*");
|
||||
}
|
||||
|
||||
[TestCase("Pooling=True", "Pooling is not supported")]
|
||||
[TestCase("Sync Interval=1", "Automatic sync is not supported")]
|
||||
public void DeferredReplicaFeaturesAreRejected(string option, string message)
|
||||
[TestCase(-1)]
|
||||
[TestCase(4_294_968)]
|
||||
public void InvalidAutomaticSyncIntervalsAreRejected(int interval)
|
||||
{
|
||||
using var connection = new TursoConnection(
|
||||
$"Data Source=turso://example.test;Replica Path=:memory:;Bootstrap If Empty=False;{option}");
|
||||
"Data Source=turso://example.test;Replica Path=:memory:;"
|
||||
+ $"Bootstrap If Empty=False;Sync Interval={interval}");
|
||||
|
||||
connection.Invoking(x => x.Open())
|
||||
.Should().Throw<NotSupportedException>()
|
||||
.WithMessage($"{message}*");
|
||||
.Should().Throw<ArgumentOutOfRangeException>()
|
||||
.WithParameterName("SyncInterval");
|
||||
}
|
||||
|
||||
[TestCase(false)]
|
||||
|
||||
290
bindings/dotnet/src/Turso.Tests/TursoReplicaPoolingTests.cs
Normal file
290
bindings/dotnet/src/Turso.Tests/TursoReplicaPoolingTests.cs
Normal file
@@ -0,0 +1,290 @@
|
||||
using AwesomeAssertions;
|
||||
using System.Net;
|
||||
|
||||
namespace Turso.Tests;
|
||||
|
||||
[NonParallelizable]
|
||||
public sealed class TursoReplicaPoolingTests
|
||||
{
|
||||
[Test]
|
||||
public async Task PooledConnectionsShareOneSyncDatabaseUntilLastClose()
|
||||
{
|
||||
var directory = NewDirectory();
|
||||
var path = Path.Combine(directory, "replica.db");
|
||||
try
|
||||
{
|
||||
using var first = new TursoConnection(ConnectionString(path, pooling: true));
|
||||
using var second = new TursoConnection(ConnectionString(path, pooling: true));
|
||||
await Task.WhenAll(first.OpenAsync(), second.OpenAsync());
|
||||
|
||||
first.SyncDatabase.Should().BeSameAs(second.SyncDatabase);
|
||||
first.ExecuteNonQuery("CREATE TABLE items(value TEXT)");
|
||||
first.ExecuteNonQuery("INSERT INTO items VALUES ('shared')");
|
||||
using (var query = new TursoCommand(second, "SELECT value FROM items"))
|
||||
query.ExecuteScalar().Should().Be("shared");
|
||||
|
||||
first.Close();
|
||||
first.Close();
|
||||
using var afterFirstClose = new TursoCommand(second, "SELECT COUNT(*) FROM items");
|
||||
afterFirstClose.ExecuteScalar().Should().Be(1L);
|
||||
second.Close();
|
||||
|
||||
using var reopened = new TursoConnection(ConnectionString(path, pooling: false));
|
||||
reopened.Open();
|
||||
using var persisted = new TursoCommand(reopened, "SELECT value FROM items");
|
||||
persisted.ExecuteScalar().Should().Be("shared");
|
||||
}
|
||||
finally
|
||||
{
|
||||
Directory.Delete(directory, recursive: true);
|
||||
}
|
||||
}
|
||||
|
||||
[Test]
|
||||
public async Task EquivalentAbsoluteAndRelativePathsShareOneReplica()
|
||||
{
|
||||
var directory = NewDirectory();
|
||||
var absolutePath = Path.Combine(directory, "replica.db");
|
||||
var relativePath = Path.GetRelativePath(Environment.CurrentDirectory, absolutePath);
|
||||
try
|
||||
{
|
||||
using var first = new TursoConnection(ConnectionString(absolutePath, pooling: true));
|
||||
using var second = new TursoConnection(ConnectionString(relativePath, pooling: true));
|
||||
|
||||
await Task.WhenAll(first.OpenAsync(), second.OpenAsync());
|
||||
|
||||
first.SyncDatabase.Should().BeSameAs(second.SyncDatabase);
|
||||
}
|
||||
finally
|
||||
{
|
||||
Directory.Delete(directory, recursive: true);
|
||||
}
|
||||
}
|
||||
|
||||
[Test]
|
||||
public async Task InitializationIsSingleFlightAndFailureCanBeRetried()
|
||||
{
|
||||
var directory = NewDirectory();
|
||||
var path = Path.Combine(directory, "replica.db");
|
||||
var handler = new BlockingFailureHandler();
|
||||
using var failingClient = new HttpClient(handler);
|
||||
using var retryClient = new HttpClient(new UnexpectedHttpHandler());
|
||||
HttpClient activeClient = failingClient;
|
||||
TursoConnection.SyncHttpClientFactory = () => activeClient;
|
||||
try
|
||||
{
|
||||
using var first = new TursoConnection(
|
||||
$"Data Source=turso://example.test;Replica Path={path};Pooling=True");
|
||||
using var second = new TursoConnection(
|
||||
$"Data Source=turso://example.test;Replica Path={path};Pooling=True");
|
||||
|
||||
var firstOpen = first.OpenAsync();
|
||||
await handler.RequestStarted.Task.WaitAsync(TimeSpan.FromSeconds(5));
|
||||
var secondOpen = second.OpenAsync();
|
||||
handler.ReleaseResponse();
|
||||
|
||||
var opening = async () => await Task.WhenAll(firstOpen, secondOpen);
|
||||
await opening.Should().ThrowAsync<TursoSyncException>();
|
||||
handler.RequestCount.Should().Be(1);
|
||||
|
||||
activeClient = retryClient;
|
||||
using var retry = new TursoConnection(ConnectionString(path, pooling: true));
|
||||
await retry.OpenAsync();
|
||||
retry.State.Should().Be(System.Data.ConnectionState.Open);
|
||||
}
|
||||
finally
|
||||
{
|
||||
handler.ReleaseResponse();
|
||||
TursoConnection.SyncHttpClientFactory = null;
|
||||
Directory.Delete(directory, recursive: true);
|
||||
}
|
||||
}
|
||||
|
||||
[Test]
|
||||
public void MemoryReplicasAreNeverShared()
|
||||
{
|
||||
using var first = new TursoConnection(ConnectionString(":memory:", pooling: true));
|
||||
using var second = new TursoConnection(ConnectionString(":memory:", pooling: true));
|
||||
|
||||
first.Open();
|
||||
second.Open();
|
||||
|
||||
first.SyncDatabase.Should().NotBeSameAs(second.SyncDatabase);
|
||||
first.ExecuteNonQuery("CREATE TABLE only_in_first(value INTEGER)");
|
||||
using var query = new TursoCommand(
|
||||
second,
|
||||
"SELECT COUNT(*) FROM sqlite_schema WHERE name = 'only_in_first'");
|
||||
query.ExecuteScalar().Should().Be(0L);
|
||||
}
|
||||
|
||||
[Test]
|
||||
public void PooledConnectionsRejectConflictingOptionsWithoutLeakingSecrets()
|
||||
{
|
||||
var directory = NewDirectory();
|
||||
var path = Path.Combine(directory, "replica.db");
|
||||
const string firstSecret = "first-secret-value";
|
||||
const string secondSecret = "second-secret-value";
|
||||
try
|
||||
{
|
||||
using var first = new TursoConnection(
|
||||
ConnectionString(path, pooling: true) + $";Auth Token={firstSecret}");
|
||||
using var conflicting = new TursoConnection(
|
||||
ConnectionString(path, pooling: true) + $";Auth Token={secondSecret}");
|
||||
first.Open();
|
||||
|
||||
var exception = conflicting.Invoking(x => x.Open())
|
||||
.Should().Throw<InvalidOperationException>()
|
||||
.WithMessage("*different options*")
|
||||
.Which;
|
||||
exception.ToString().Should().NotContain(firstSecret).And.NotContain(secondSecret);
|
||||
}
|
||||
finally
|
||||
{
|
||||
Directory.Delete(directory, recursive: true);
|
||||
}
|
||||
}
|
||||
|
||||
[Test]
|
||||
public void NonPooledReplicaHasAnExclusivePathLease()
|
||||
{
|
||||
var directory = NewDirectory();
|
||||
var path = Path.Combine(directory, "replica.db");
|
||||
try
|
||||
{
|
||||
using var first = new TursoConnection(ConnectionString(path, pooling: false));
|
||||
using var second = new TursoConnection(ConnectionString(path, pooling: false));
|
||||
first.Open();
|
||||
|
||||
second.Invoking(x => x.Open())
|
||||
.Should().Throw<InvalidOperationException>()
|
||||
.WithMessage("*already open exclusively*");
|
||||
}
|
||||
finally
|
||||
{
|
||||
Directory.Delete(directory, recursive: true);
|
||||
}
|
||||
}
|
||||
|
||||
[Test]
|
||||
public async Task PooledConnectionsUseOneAutomaticSyncScheduler()
|
||||
{
|
||||
var directory = NewDirectory();
|
||||
var path = Path.Combine(directory, "replica.db");
|
||||
var handler = new CountingFailureHandler();
|
||||
using var httpClient = new HttpClient(handler);
|
||||
TursoConnection.SyncHttpClientFactory = () => httpClient;
|
||||
var first = new TursoConnection(
|
||||
ConnectionString(path, pooling: true) + ";Sync Interval=1");
|
||||
var second = new TursoConnection(
|
||||
ConnectionString(path, pooling: true) + ";Sync Interval=1");
|
||||
try
|
||||
{
|
||||
await Task.WhenAll(first.OpenAsync(), second.OpenAsync());
|
||||
await WaitForFaultAsync(first);
|
||||
|
||||
first.AutomaticSyncStatus.State.Should().Be(TursoAutomaticSyncState.Faulted);
|
||||
second.AutomaticSyncStatus.State.Should().Be(TursoAutomaticSyncState.Faulted);
|
||||
handler.RequestCount.Should().Be(1);
|
||||
}
|
||||
finally
|
||||
{
|
||||
TursoConnection.SyncHttpClientFactory = null;
|
||||
CloseFaulted(first);
|
||||
CloseFaulted(second);
|
||||
first.Dispose();
|
||||
second.Dispose();
|
||||
Directory.Delete(directory, recursive: true);
|
||||
}
|
||||
}
|
||||
|
||||
private static async Task WaitForFaultAsync(TursoConnection connection)
|
||||
{
|
||||
var deadline = DateTime.UtcNow + TimeSpan.FromSeconds(5);
|
||||
while (connection.AutomaticSyncStatus.State != TursoAutomaticSyncState.Faulted
|
||||
&& DateTime.UtcNow < deadline)
|
||||
{
|
||||
await Task.Delay(25);
|
||||
}
|
||||
}
|
||||
|
||||
private static void CloseFaulted(TursoConnection connection)
|
||||
{
|
||||
try
|
||||
{
|
||||
connection.Close();
|
||||
}
|
||||
catch (TursoSyncException)
|
||||
{
|
||||
}
|
||||
}
|
||||
|
||||
private static string ConnectionString(string path, bool pooling)
|
||||
{
|
||||
return $"Data Source=turso://example.test;Replica Path={path};"
|
||||
+ $"Bootstrap If Empty=False;Pooling={pooling}";
|
||||
}
|
||||
|
||||
private static string NewDirectory()
|
||||
{
|
||||
var path = Path.Combine(
|
||||
TestContext.CurrentContext.WorkDirectory,
|
||||
"turso-replica-pool-" + Guid.NewGuid().ToString("N"));
|
||||
Directory.CreateDirectory(path);
|
||||
return path;
|
||||
}
|
||||
|
||||
private sealed class CountingFailureHandler : HttpMessageHandler
|
||||
{
|
||||
public int RequestCount { get; private set; }
|
||||
|
||||
protected override Task<HttpResponseMessage> SendAsync(
|
||||
HttpRequestMessage request,
|
||||
CancellationToken cancellationToken)
|
||||
{
|
||||
RequestCount++;
|
||||
return Task.FromResult(new HttpResponseMessage(HttpStatusCode.InternalServerError)
|
||||
{
|
||||
Content = new ByteArrayContent([]),
|
||||
});
|
||||
}
|
||||
}
|
||||
|
||||
private sealed class BlockingFailureHandler : HttpMessageHandler
|
||||
{
|
||||
private readonly TaskCompletionSource _release = new(
|
||||
TaskCreationOptions.RunContinuationsAsynchronously);
|
||||
|
||||
public TaskCompletionSource RequestStarted { get; } = new(
|
||||
TaskCreationOptions.RunContinuationsAsynchronously);
|
||||
|
||||
public int RequestCount { get; private set; }
|
||||
|
||||
public void ReleaseResponse()
|
||||
{
|
||||
_release.TrySetResult();
|
||||
}
|
||||
|
||||
protected override async Task<HttpResponseMessage> SendAsync(
|
||||
HttpRequestMessage request,
|
||||
CancellationToken cancellationToken)
|
||||
{
|
||||
RequestCount++;
|
||||
RequestStarted.TrySetResult();
|
||||
await _release.Task.WaitAsync(cancellationToken);
|
||||
return new HttpResponseMessage(HttpStatusCode.InternalServerError)
|
||||
{
|
||||
Content = new ByteArrayContent([]),
|
||||
};
|
||||
}
|
||||
}
|
||||
|
||||
private sealed class UnexpectedHttpHandler : HttpMessageHandler
|
||||
{
|
||||
protected override Task<HttpResponseMessage> SendAsync(
|
||||
HttpRequestMessage request,
|
||||
CancellationToken cancellationToken)
|
||||
{
|
||||
throw new AssertionException($"Unexpected HTTP request: {request.RequestUri}");
|
||||
}
|
||||
}
|
||||
}
|
||||
Reference in New Issue
Block a user