diff --git a/bindings/dotnet/Readme.md b/bindings/dotnet/Readme.md index 936d0d957..4056cb379 100644 --- a/bindings/dotnet/Readme.md +++ b/bindings/dotnet/Readme.md @@ -123,7 +123,7 @@ batch.BatchCommands.Add(select); await using var reader = await batch.ExecuteReaderAsync(); ``` -Use `TursoSyncDatabase` when an application needs an embedded replica with explicit pull control: +Use `TursoSyncDatabase` when an application needs an embedded replica with explicit sync control: ```C# var options = new TursoSyncDatabaseOptions( @@ -136,11 +136,16 @@ var options = new TursoSyncDatabaseOptions( await using var database = await TursoSyncDatabase.CreateAsync(options); await using var local = await database.ConnectAsync(); var changed = await database.PullAsync(); +var stats = await database.GetStatsAsync(); + +// Push is explicit. Do not call it for pull-only replicas. +await database.PushAsync(); +await database.CheckpointAsync(); ``` -`PullAsync` never pushes local writes. Sync failures are `TursoSyncException` values carrying the operation, native status, sanitized endpoint, HTTP method/status, and original exception. +`PullAsync` never pushes local writes. `PushAsync` currently follows the sync engine's last-write-wins conflict behavior, so use it only when that policy is acceptable. `CheckpointAsync` runs the sync engine's local checkpoint operation, while `GetStatsAsync` reports WAL sizes, CDC operations, transfer totals, revision, and the most recent pull and push times. 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. +Partial sync, remote encryption, connection-string replica integration, pooling, and automatic synchronization are not enabled yet. Use the explicit `TursoSyncDatabase` API for managed replicas. Provider factories are available through `TursoFactory.Instance`: diff --git a/bindings/dotnet/src/Turso.Data/TursoSyncDatabase.cs b/bindings/dotnet/src/Turso.Data/TursoSyncDatabase.cs index efbe118e8..1208a566e 100644 --- a/bindings/dotnet/src/Turso.Data/TursoSyncDatabase.cs +++ b/bindings/dotnet/src/Turso.Data/TursoSyncDatabase.cs @@ -182,6 +182,60 @@ public sealed class TursoSyncDatabase : IDisposable, IAsyncDisposable } } + public void Push() + => RunSynchronously(() => PushAsync(CancellationToken.None)); + + public Task PushAsync(CancellationToken cancellationToken = default) + => RunVoidOperationAsync( + TursoSyncBindings.StartPush, + TursoSyncOperationKind.Push, + cancellationToken); + + public void Checkpoint() + => RunSynchronously(() => CheckpointAsync(CancellationToken.None)); + + public Task CheckpointAsync(CancellationToken cancellationToken = default) + => RunVoidOperationAsync( + TursoSyncBindings.StartCheckpoint, + TursoSyncOperationKind.Checkpoint, + cancellationToken); + + public TursoSyncStats GetStats() + => RunSynchronously(() => GetStatsAsync(CancellationToken.None)); + + public async Task GetStatsAsync(CancellationToken cancellationToken = default) + { + ThrowIfDisposed(); + await _operationLock.WaitAsync(cancellationToken).ConfigureAwait(false); + try + { + ThrowIfDisposed(); + using var operation = StartOperation( + TursoSyncBindings.StartStats, + TursoSyncOperationKind.Stats); + await DriveOperationAsync( + operation, + TursoSyncOperationKind.Stats, + cancellationToken) + .ConfigureAwait(false); + EnsureResultKind(operation, TursoSyncOperationResultKind.Stats); + var stats = TursoSyncBindings.ExtractStats(operation); + return new TursoSyncStats( + stats.CdcOperations, + stats.MainWalSize, + stats.RevertWalSize, + ToTimestamp(stats.LastPullUnixTime), + ToTimestamp(stats.LastPushUnixTime), + stats.NetworkSentBytes, + stats.NetworkReceivedBytes, + stats.Revision); + } + finally + { + _operationLock.Release(); + } + } + public void Dispose() { ThrowIfIoReentrant(); @@ -762,6 +816,9 @@ public sealed class TursoSyncDatabase : IDisposable, IAsyncDisposable throw new InvalidOperationException($"Expected Turso sync result {expected}, got {actual}."); } + private static DateTimeOffset? ToTimestamp(long value) + => value <= 0 ? null : DateTimeOffset.FromUnixTimeSeconds(value); + private TursoSyncException CreateSyncException( TursoSyncOperationKind operation, Exception exception) diff --git a/bindings/dotnet/src/Turso.Data/TursoSyncDatabaseOptions.cs b/bindings/dotnet/src/Turso.Data/TursoSyncDatabaseOptions.cs index aad8a4322..961a2d87d 100644 --- a/bindings/dotnet/src/Turso.Data/TursoSyncDatabaseOptions.cs +++ b/bindings/dotnet/src/Turso.Data/TursoSyncDatabaseOptions.cs @@ -73,3 +73,13 @@ public sealed class TursoSyncDatabaseOptions } } + +public sealed record TursoSyncStats( + long CdcOperations, + long MainWalSize, + long RevertWalSize, + DateTimeOffset? LastPullTime, + DateTimeOffset? LastPushTime, + long NetworkSentBytes, + long NetworkReceivedBytes, + string Revision); diff --git a/bindings/dotnet/src/Turso.Data/TursoSyncException.cs b/bindings/dotnet/src/Turso.Data/TursoSyncException.cs index 087c18d09..023448981 100644 --- a/bindings/dotnet/src/Turso.Data/TursoSyncException.cs +++ b/bindings/dotnet/src/Turso.Data/TursoSyncException.cs @@ -10,6 +10,9 @@ public enum TursoSyncOperationKind Connect, Pull, Apply, + Push, + Checkpoint, + Stats, } public sealed class TursoSyncException : TursoException diff --git a/bindings/dotnet/src/Turso.Tests/TursoManagedSyncTests.cs b/bindings/dotnet/src/Turso.Tests/TursoManagedSyncTests.cs index 4ff1738e8..96eaad4a9 100644 --- a/bindings/dotnet/src/Turso.Tests/TursoManagedSyncTests.cs +++ b/bindings/dotnet/src/Turso.Tests/TursoManagedSyncTests.cs @@ -130,6 +130,82 @@ public sealed class TursoManagedSyncTests afterDispose.ExecuteScalar().Should().Be(1L); } + [Test] + public async Task StatsAndCheckpointCompleteWithoutRemoteIo() + { + 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, + }); + + var asyncStats = await database.GetStatsAsync(); + await database.CheckpointAsync(); + var syncStats = database.GetStats(); + database.Checkpoint(); + + asyncStats.LastPullTime.Should().BeNull(); + asyncStats.LastPushTime.Should().BeNull(); + asyncStats.Revision.Should().NotBeNull(); + syncStats.LastPullTime.Should().BeNull(); + syncStats.LastPushTime.Should().BeNull(); + syncStats.Revision.Should().NotBeNull(); + } + + [Test] + public async Task PushFailureReportsPushOperation() + { + using var httpClient = new HttpClient(new RejectingSyncHandler()); + 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)"); + + var action = async () => await database.PushAsync(); + + var exception = await action.Should().ThrowAsync(); + exception.And.Operation.Should().Be(TursoSyncOperationKind.Push); + exception.And.HttpMethod.Should().Be("POST"); + exception.And.HttpStatusCode.Should().Be(HttpStatusCode.InternalServerError); + + Action synchronousAction = database.Push; + synchronousAction.Should().Throw() + .Which.Operation.Should().Be(TursoSyncOperationKind.Push); + } + + [Test] + public async Task StatsWaitForActiveReaders() + { + 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(); + + var stats = database.GetStatsAsync(); + await Task.Delay(50); + stats.IsCompleted.Should().BeFalse(); + + reader.Dispose(); + (await stats).Revision.Should().NotBeNull(); + } + [Test] public async Task CancellationStopsAnInFlightSyncHttpRequest() { @@ -336,6 +412,19 @@ public sealed class TursoManagedSyncTests } } + private sealed class RejectingSyncHandler : HttpMessageHandler + { + protected override Task SendAsync( + HttpRequestMessage request, + CancellationToken cancellationToken) + { + return Task.FromResult(new HttpResponseMessage(HttpStatusCode.InternalServerError) + { + Content = new ByteArrayContent([]), + }); + } + } + private sealed class BlockingSyncHandler : HttpMessageHandler { public int RequestCount { get; private set; }