mirror of
https://github.com/allankoechke/turso.git
synced 2026-11-30 11:12:58 +00:00
Merge 'bindings/dotnet: add connection-string embedded replicas' from Marc-André Moreau
## Summary - route a remote `Data Source` with `Replica Path` through the managed `TursoSyncDatabase` API, with synchronous and asynchronous open and direct per-connection ownership - make `TursoConnection.SyncAsync` explicitly pull remote changes while keeping direct remote and local connection behavior unchanged - map advanced explicit sync settings into connection-string keywords, including partial sync, remote encryption, thresholds, logical MVCC pull, and experimental features - close active readers and local handles before releasing owned sync resources, and clean up failed or canceled opens without changing caller ownership of explicit `TursoSyncDatabase` connections - reject deferred replica pooling and automatic sync instead of silently ignoring them, while keeping `:memory:` replicas usable ## Extraction context This is the next ordinary PR extracted from the closed source draft #8504. It builds on #8514, #8519, #8523, and #8530: the native sync ABI, managed pull replica API, explicit sync controls, and advanced sync options are already present on `main`; this PR wires only the basic `TursoConnection` connection-string layer onto those APIs. ## Deferred work This PR intentionally does not add `TursoReplicaRegistry`, pooling or shared replica ownership, automatic sync coordination/status/events or interval scheduling, replica `DbBatch`, Hrana stream-expiry recovery, broader ADO.NET schema/GUID/enum/isolation work, the `Turso.Data.Sqlite` managed remote/replica backend, EF Core integration, NativeAOT/mobile/package-consumer samples or CI jobs, or Rust changes. `Pooling=True` and nonzero `Sync Interval` are rejected for replica connections. Use `Pooling=False` and call `SyncAsync` for an explicit pull. ## Validation - `dotnet format Turso.slnx --verify-no-changes --no-restore` for changed files - `dotnet build src/Turso.Data/Turso.Data.csproj --no-restore` (0 warnings, 0 errors) - focused `TursoReplicaConnectionStringTests`, `TursoRemoteTests`, and `TursoManagedSyncTests` (57 passed) - live Cloud `TursoReplicaCloudTests.ExplicitPullConvergesWithRemoteChanges` using `TURSO_REMOTE_URL` and `TURSO_AUTH_TOKEN` (1 passed) Closes #8555
This commit is contained in:
@@ -103,6 +103,22 @@ var name = await command.ExecuteScalarAsync();
|
||||
|
||||
Remote mode uses the Hrana HTTP `/v2/pipeline` protocol. `libsql://` URLs default to HTTPS; `Tls=False` maps them to HTTP for local development. `ws://` and `wss://` URLs are accepted and mapped to the equivalent HTTP pipeline endpoint. `Auth Token` requires HTTPS unless the host is `localhost` or loopback.
|
||||
|
||||
Add `Replica Path` to use the same provider surface with a local embedded replica:
|
||||
|
||||
```C#
|
||||
await using var replica = new TursoConnection(
|
||||
"Data Source=turso://example-org.turso.io;"
|
||||
+ "Auth Token=eyJ...;"
|
||||
+ "Replica Path=./replica.db;"
|
||||
+ "Pooling=False");
|
||||
await replica.OpenAsync();
|
||||
|
||||
// Pull remote changes into the local replica. Local writes are not pushed.
|
||||
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.
|
||||
|
||||
Remote mode also supports ADO.NET `DbBatch` for latency-sensitive workloads that should be sent in one Hrana batch:
|
||||
|
||||
```C#
|
||||
@@ -155,7 +171,7 @@ await database.CheckpointAsync();
|
||||
|
||||
`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.
|
||||
|
||||
Remote encryption is configured with `RemoteEncryption = new TursoRemoteEncryptionOptions { Key = key, Cipher = TursoRemoteEncryptionCipher.Aes256Gcm }`. It cannot be combined with partial sync. Query-based partial sync cannot set `PullBytesThreshold`, all partial-sync strategies require `BootstrapIfEmpty`, and partial sync is unavailable on Windows until native sparse-file hole detection is implemented. Connection-string replica integration, pooling, and automatic synchronization are not enabled yet; use the explicit `TursoSyncDatabaseOptions` API for these advanced settings.
|
||||
Remote encryption is configured with `RemoteEncryption = new TursoRemoteEncryptionOptions { Key = key, Cipher = TursoRemoteEncryptionCipher.Aes256Gcm }`. It cannot be combined with partial sync. Query-based partial sync cannot set `PullBytesThreshold`, all partial-sync strategies require `BootstrapIfEmpty`, and partial sync is unavailable on Windows until native sparse-file hole detection is implemented.
|
||||
|
||||
Provider factories are available through `TursoFactory.Instance`:
|
||||
|
||||
|
||||
@@ -8,9 +8,12 @@ namespace Turso;
|
||||
|
||||
public class TursoConnection : DbConnection
|
||||
{
|
||||
internal static Func<HttpClient?>? SyncHttpClientFactory { get; set; }
|
||||
|
||||
private TursoDatabaseHandle? _turso;
|
||||
private TursoRemoteClient? _remoteClient;
|
||||
private TursoSyncDatabase? _syncDatabase;
|
||||
private bool _ownsSyncDatabase;
|
||||
private readonly HashSet<TursoDataReader> _syncReaders = [];
|
||||
private readonly object _syncReadersLock = new();
|
||||
private TursoConnectionOptions _connectionOptions;
|
||||
@@ -91,6 +94,9 @@ public class TursoConnection : DbConnection
|
||||
if (cancellationToken.IsCancellationRequested)
|
||||
return Task.FromCanceled(cancellationToken);
|
||||
|
||||
if (_connectionOptions.IsReplica)
|
||||
return OpenReplicaAsync(cancellationToken);
|
||||
|
||||
Open();
|
||||
return Task.CompletedTask;
|
||||
}
|
||||
@@ -178,7 +184,8 @@ public class TursoConnection : DbConnection
|
||||
if (!_connectionOptions.IsReplica)
|
||||
throw new NotSupportedException("Sync requires an embedded replica connection.");
|
||||
|
||||
throw new NotSupportedException("Embedded replica sync is not supported yet by the .NET provider.");
|
||||
return (_syncDatabase ?? throw new InvalidOperationException("The embedded replica is not initialized."))
|
||||
.PullAsync(cancellationToken);
|
||||
}
|
||||
|
||||
public override void ChangeDatabase(string databaseName)
|
||||
@@ -374,10 +381,15 @@ public class TursoConnection : DbConnection
|
||||
private void OpenRemote()
|
||||
{
|
||||
if (_connectionOptions.IsReplica)
|
||||
throw new NotSupportedException("Embedded replica connections are not supported yet by the .NET provider. Use a remote URL without Replica Path for direct remote execution.");
|
||||
{
|
||||
OpenReplica();
|
||||
return;
|
||||
}
|
||||
|
||||
if (_connectionOptions.SyncInterval > 0)
|
||||
throw new NotSupportedException("Sync Interval requires embedded replica support, which is not supported yet by the .NET provider.");
|
||||
throw new NotSupportedException("Sync Interval requires an embedded replica connection.");
|
||||
if (_connectionOptions.HasAdvancedReplicaOptions)
|
||||
throw new NotSupportedException("Advanced sync options require an embedded replica connection.");
|
||||
|
||||
if (_connectionOptions.GetEncryptionCipher().HasValue || !string.IsNullOrWhiteSpace(_connectionOptions["Encryption Key"]))
|
||||
throw new InvalidOperationException("Encryption Cipher and Encryption Key are local database options and cannot be used with remote Turso URLs.");
|
||||
@@ -385,6 +397,114 @@ public class TursoConnection : DbConnection
|
||||
_remoteClient = new TursoRemoteClient(_connectionOptions.GetRemoteUri(), _connectionOptions.AuthToken);
|
||||
}
|
||||
|
||||
private void OpenReplica()
|
||||
{
|
||||
ValidateReplicaOptions();
|
||||
var syncDatabase = TursoSyncDatabase.Create(CreateReplicaOptions());
|
||||
try
|
||||
{
|
||||
_turso = syncDatabase.ConnectHandleAsync(CancellationToken.None).GetAwaiter().GetResult();
|
||||
_syncDatabase = syncDatabase;
|
||||
_ownsSyncDatabase = true;
|
||||
}
|
||||
catch
|
||||
{
|
||||
_turso?.Dispose();
|
||||
_turso = null;
|
||||
syncDatabase.Dispose();
|
||||
throw;
|
||||
}
|
||||
}
|
||||
|
||||
private async Task OpenReplicaAsync(CancellationToken cancellationToken)
|
||||
{
|
||||
ObjectDisposedException.ThrowIf(_disposed, this);
|
||||
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)
|
||||
.ConfigureAwait(false);
|
||||
try
|
||||
{
|
||||
_turso = await syncDatabase.ConnectHandleAsync(cancellationToken).ConfigureAwait(false);
|
||||
_syncDatabase = syncDatabase;
|
||||
_ownsSyncDatabase = true;
|
||||
}
|
||||
catch
|
||||
{
|
||||
_turso?.Dispose();
|
||||
_turso = null;
|
||||
await syncDatabase.DisposeAsync().ConfigureAwait(false);
|
||||
throw;
|
||||
}
|
||||
}
|
||||
|
||||
internal TursoSyncDatabaseOptions CreateReplicaOptions()
|
||||
{
|
||||
if (_connectionOptions.GetEncryptionCipher().HasValue
|
||||
|| !string.IsNullOrWhiteSpace(_connectionOptions["Encryption Key"]))
|
||||
{
|
||||
throw new InvalidOperationException(
|
||||
"Encryption Cipher and Encryption Key are local database options. "
|
||||
+ "Use Remote Encryption Cipher and Remote Encryption Key for embedded replicas.");
|
||||
}
|
||||
|
||||
TursoPartialSyncOptions? partialSync = null;
|
||||
if (_connectionOptions.HasPartialSyncOptions)
|
||||
{
|
||||
partialSync = new TursoPartialSyncOptions
|
||||
{
|
||||
PrefixLength = _connectionOptions.PartialBootstrapPrefix == 0
|
||||
? null
|
||||
: _connectionOptions.PartialBootstrapPrefix,
|
||||
Query = string.IsNullOrWhiteSpace(_connectionOptions.PartialBootstrapQuery)
|
||||
? null
|
||||
: _connectionOptions.PartialBootstrapQuery,
|
||||
SegmentSize = _connectionOptions.PartialSyncSegmentSize == 0
|
||||
? null
|
||||
: _connectionOptions.PartialSyncSegmentSize,
|
||||
Prefetch = _connectionOptions.PartialSyncPrefetch,
|
||||
};
|
||||
}
|
||||
|
||||
return new TursoSyncDatabaseOptions(
|
||||
_connectionOptions.ReplicaPath,
|
||||
_connectionOptions.GetRemoteUri())
|
||||
{
|
||||
AuthToken = _connectionOptions.AuthToken,
|
||||
ClientName = string.IsNullOrWhiteSpace(_connectionOptions.SyncClientName)
|
||||
? "turso-sync-dotnet"
|
||||
: _connectionOptions.SyncClientName,
|
||||
LongPollTimeout = _connectionOptions.SyncLongPollTimeout == 0
|
||||
? null
|
||||
: TimeSpan.FromMilliseconds(_connectionOptions.SyncLongPollTimeout),
|
||||
BootstrapIfEmpty = _connectionOptions.BootstrapIfEmpty,
|
||||
PartialSync = partialSync,
|
||||
RemoteEncryption = _connectionOptions.GetRemoteEncryption(),
|
||||
PushOperationsThreshold = _connectionOptions.PushOperationsThreshold == 0
|
||||
? null
|
||||
: _connectionOptions.PushOperationsThreshold,
|
||||
PullBytesThreshold = _connectionOptions.PullBytesThreshold == 0
|
||||
? null
|
||||
: _connectionOptions.PullBytesThreshold,
|
||||
ForceLogicalMvccPull = _connectionOptions.ForceLogicalMvccPull,
|
||||
ExperimentalFeatures = string.IsNullOrWhiteSpace(_connectionOptions.SyncExperimentalFeatures)
|
||||
? null
|
||||
: _connectionOptions.SyncExperimentalFeatures,
|
||||
HttpClient = SyncHttpClientFactory?.Invoke(),
|
||||
};
|
||||
}
|
||||
|
||||
private void ValidateReplicaOptions()
|
||||
{
|
||||
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.");
|
||||
}
|
||||
|
||||
private void ValidateLocalOnlyOptions()
|
||||
{
|
||||
if (!string.IsNullOrWhiteSpace(_connectionOptions.AuthToken))
|
||||
@@ -393,6 +513,8 @@ public class TursoConnection : DbConnection
|
||||
throw new InvalidOperationException("Replica Path requires a remote Turso URL Data Source.");
|
||||
if (_connectionOptions.SyncInterval > 0)
|
||||
throw new InvalidOperationException("Sync Interval requires a remote embedded replica connection.");
|
||||
if (_connectionOptions.HasAdvancedReplicaOptions)
|
||||
throw new InvalidOperationException("Advanced sync options require a remote embedded replica connection.");
|
||||
if (_connectionOptions.Tls.HasValue)
|
||||
throw new InvalidOperationException("Tls requires a remote Turso URL Data Source.");
|
||||
}
|
||||
@@ -448,8 +570,12 @@ public class TursoConnection : DbConnection
|
||||
if (syncDatabase is null)
|
||||
return;
|
||||
|
||||
var ownsSyncDatabase = _ownsSyncDatabase;
|
||||
_syncDatabase = null;
|
||||
_ownsSyncDatabase = false;
|
||||
syncDatabase.ReleaseConnection();
|
||||
if (ownsSyncDatabase)
|
||||
syncDatabase.Dispose();
|
||||
}
|
||||
|
||||
private void CloseSyncReaders()
|
||||
|
||||
@@ -22,6 +22,8 @@ public class TursoConnectionOptions
|
||||
|
||||
public int DefaultTimeout => _builder.DefaultTimeout;
|
||||
|
||||
public bool Pooling => _builder.Pooling;
|
||||
|
||||
public string DataSource => _builder.DataSource;
|
||||
|
||||
public string AuthToken => _builder.AuthToken;
|
||||
@@ -32,14 +34,80 @@ public class TursoConnectionOptions
|
||||
|
||||
public int SyncInterval => _builder.SyncInterval;
|
||||
|
||||
public string SyncClientName => _builder.SyncClientName;
|
||||
|
||||
public int SyncLongPollTimeout => _builder.SyncLongPollTimeout;
|
||||
|
||||
public bool BootstrapIfEmpty => _builder.BootstrapIfEmpty;
|
||||
|
||||
public int PartialBootstrapPrefix => _builder.PartialBootstrapPrefix;
|
||||
|
||||
public string PartialBootstrapQuery => _builder.PartialBootstrapQuery;
|
||||
|
||||
public long PartialSyncSegmentSize => _builder.PartialSyncSegmentSize;
|
||||
|
||||
public bool PartialSyncPrefetch => _builder.PartialSyncPrefetch;
|
||||
|
||||
public string RemoteEncryptionCipher => _builder.RemoteEncryptionCipher;
|
||||
|
||||
public string RemoteEncryptionKey => _builder.RemoteEncryptionKey;
|
||||
|
||||
public long PushOperationsThreshold => _builder.PushOperationsThreshold;
|
||||
|
||||
public long PullBytesThreshold => _builder.PullBytesThreshold;
|
||||
|
||||
public bool ForceLogicalMvccPull => _builder.ForceLogicalMvccPull;
|
||||
|
||||
public string SyncExperimentalFeatures => _builder.SyncExperimentalFeatures;
|
||||
|
||||
public bool? Tls => _builder.Tls;
|
||||
|
||||
public bool IsRemote => IsRemoteDataSource(DataSource);
|
||||
|
||||
public bool IsReplica => IsRemote && !string.IsNullOrWhiteSpace(ReplicaPath);
|
||||
|
||||
public bool HasAdvancedReplicaOptions =>
|
||||
HasOption("Sync Client Name")
|
||||
|| HasOption("Sync Long Poll Timeout")
|
||||
|| HasOption("Bootstrap If Empty")
|
||||
|| HasOption("Partial Bootstrap Prefix")
|
||||
|| HasOption("Partial Bootstrap Query")
|
||||
|| HasOption("Partial Sync Segment Size")
|
||||
|| HasOption("Partial Sync Prefetch")
|
||||
|| HasOption("Remote Encryption Cipher")
|
||||
|| HasOption("Remote Encryption Key")
|
||||
|| HasOption("Push Operations Threshold")
|
||||
|| HasOption("Pull Bytes Threshold")
|
||||
|| HasOption("Force Logical MVCC Pull")
|
||||
|| HasOption("Sync Experimental Features");
|
||||
|
||||
public bool HasPartialSyncOptions =>
|
||||
HasOption("Partial Bootstrap Prefix")
|
||||
|| HasOption("Partial Bootstrap Query")
|
||||
|| HasOption("Partial Sync Segment Size")
|
||||
|| HasOption("Partial Sync Prefetch");
|
||||
|
||||
public TursoEncryptionCipher? GetEncryptionCipher() => _builder.GetEncryptionCipher();
|
||||
|
||||
public TursoRemoteEncryptionOptions? GetRemoteEncryption()
|
||||
{
|
||||
var cipher = RemoteEncryptionCipher;
|
||||
var key = RemoteEncryptionKey;
|
||||
if (string.IsNullOrWhiteSpace(cipher) && string.IsNullOrWhiteSpace(key))
|
||||
return null;
|
||||
if (string.IsNullOrWhiteSpace(cipher) || string.IsNullOrWhiteSpace(key))
|
||||
{
|
||||
throw new InvalidOperationException(
|
||||
"Remote Encryption Cipher and Remote Encryption Key must be specified together.");
|
||||
}
|
||||
|
||||
return new TursoRemoteEncryptionOptions
|
||||
{
|
||||
Cipher = TursoRemoteEncryptionOptions.ParseCipher(cipher),
|
||||
Key = key,
|
||||
};
|
||||
}
|
||||
|
||||
public Uri GetRemoteUri()
|
||||
{
|
||||
if (!Uri.TryCreate(DataSource, UriKind.Absolute, out var uri) || !IsRemoteScheme(uri.Scheme))
|
||||
@@ -55,6 +123,7 @@ public class TursoConnectionOptions
|
||||
var scheme = uri.Scheme.ToLowerInvariant() switch
|
||||
{
|
||||
"libsql" => Tls == false ? "http" : "https",
|
||||
"turso" => ValidateTls(uri.Scheme, expectedTls: true, normalizedScheme: "https"),
|
||||
"http" => ValidateTls(uri.Scheme, expectedTls: false),
|
||||
"https" => ValidateTls(uri.Scheme, expectedTls: true),
|
||||
"ws" => ValidateTls(uri.Scheme, expectedTls: false, normalizedScheme: "http"),
|
||||
@@ -78,6 +147,8 @@ public class TursoConnectionOptions
|
||||
return new TursoConnectionOptions(new TursoConnectionStringBuilder(connectionString));
|
||||
}
|
||||
|
||||
private bool HasOption(string keyword) => _builder.ContainsKey(keyword);
|
||||
|
||||
private static bool IsRemoteDataSource(string dataSource)
|
||||
{
|
||||
return Uri.TryCreate(dataSource, UriKind.Absolute, out var uri)
|
||||
@@ -87,6 +158,7 @@ public class TursoConnectionOptions
|
||||
private static bool IsRemoteScheme(string scheme)
|
||||
{
|
||||
return scheme.Equals("libsql", StringComparison.OrdinalIgnoreCase)
|
||||
|| scheme.Equals("turso", StringComparison.OrdinalIgnoreCase)
|
||||
|| scheme.Equals("http", StringComparison.OrdinalIgnoreCase)
|
||||
|| scheme.Equals("https", StringComparison.OrdinalIgnoreCase)
|
||||
|| scheme.Equals("ws", StringComparison.OrdinalIgnoreCase)
|
||||
|
||||
@@ -40,6 +40,32 @@ public sealed class TursoConnectionStringBuilder : DbConnectionStringBuilder
|
||||
["ReadYourWrites"] = "Read Your Writes",
|
||||
["Sync Interval"] = "Sync Interval",
|
||||
["SyncInterval"] = "Sync Interval",
|
||||
["Sync Client Name"] = "Sync Client Name",
|
||||
["SyncClientName"] = "Sync Client Name",
|
||||
["Sync Long Poll Timeout"] = "Sync Long Poll Timeout",
|
||||
["SyncLongPollTimeout"] = "Sync Long Poll Timeout",
|
||||
["Bootstrap If Empty"] = "Bootstrap If Empty",
|
||||
["BootstrapIfEmpty"] = "Bootstrap If Empty",
|
||||
["Partial Bootstrap Prefix"] = "Partial Bootstrap Prefix",
|
||||
["PartialBootstrapPrefix"] = "Partial Bootstrap Prefix",
|
||||
["Partial Bootstrap Query"] = "Partial Bootstrap Query",
|
||||
["PartialBootstrapQuery"] = "Partial Bootstrap Query",
|
||||
["Partial Sync Segment Size"] = "Partial Sync Segment Size",
|
||||
["PartialSyncSegmentSize"] = "Partial Sync Segment Size",
|
||||
["Partial Sync Prefetch"] = "Partial Sync Prefetch",
|
||||
["PartialSyncPrefetch"] = "Partial Sync Prefetch",
|
||||
["Remote Encryption Cipher"] = "Remote Encryption Cipher",
|
||||
["RemoteEncryptionCipher"] = "Remote Encryption Cipher",
|
||||
["Remote Encryption Key"] = "Remote Encryption Key",
|
||||
["RemoteEncryptionKey"] = "Remote Encryption Key",
|
||||
["Push Operations Threshold"] = "Push Operations Threshold",
|
||||
["PushOperationsThreshold"] = "Push Operations Threshold",
|
||||
["Pull Bytes Threshold"] = "Pull Bytes Threshold",
|
||||
["PullBytesThreshold"] = "Pull Bytes Threshold",
|
||||
["Force Logical MVCC Pull"] = "Force Logical MVCC Pull",
|
||||
["ForceLogicalMvccPull"] = "Force Logical MVCC Pull",
|
||||
["Sync Experimental Features"] = "Sync Experimental Features",
|
||||
["SyncExperimentalFeatures"] = "Sync Experimental Features",
|
||||
["Tls"] = "Tls",
|
||||
["TLS"] = "Tls",
|
||||
};
|
||||
@@ -151,6 +177,104 @@ public sealed class TursoConnectionStringBuilder : DbConnectionStringBuilder
|
||||
}
|
||||
}
|
||||
|
||||
public string SyncClientName
|
||||
{
|
||||
get => GetString("Sync Client Name");
|
||||
set => SetString("Sync Client Name", value);
|
||||
}
|
||||
|
||||
public int SyncLongPollTimeout
|
||||
{
|
||||
get => GetInt("Sync Long Poll Timeout", 0);
|
||||
set
|
||||
{
|
||||
ArgumentOutOfRangeException.ThrowIfNegative(value);
|
||||
this["Sync Long Poll Timeout"] = value;
|
||||
}
|
||||
}
|
||||
|
||||
public bool BootstrapIfEmpty
|
||||
{
|
||||
get => GetBool("Bootstrap If Empty", defaultValue: true);
|
||||
set => this["Bootstrap If Empty"] = value;
|
||||
}
|
||||
|
||||
public int PartialBootstrapPrefix
|
||||
{
|
||||
get => GetInt("Partial Bootstrap Prefix", 0);
|
||||
set
|
||||
{
|
||||
ArgumentOutOfRangeException.ThrowIfNegative(value);
|
||||
this["Partial Bootstrap Prefix"] = value;
|
||||
}
|
||||
}
|
||||
|
||||
public string PartialBootstrapQuery
|
||||
{
|
||||
get => GetString("Partial Bootstrap Query");
|
||||
set => SetString("Partial Bootstrap Query", value);
|
||||
}
|
||||
|
||||
public long PartialSyncSegmentSize
|
||||
{
|
||||
get => GetLong("Partial Sync Segment Size", 0);
|
||||
set
|
||||
{
|
||||
ArgumentOutOfRangeException.ThrowIfNegative(value);
|
||||
this["Partial Sync Segment Size"] = value;
|
||||
}
|
||||
}
|
||||
|
||||
public bool PartialSyncPrefetch
|
||||
{
|
||||
get => GetBool("Partial Sync Prefetch");
|
||||
set => this["Partial Sync Prefetch"] = value;
|
||||
}
|
||||
|
||||
public string RemoteEncryptionCipher
|
||||
{
|
||||
get => GetString("Remote Encryption Cipher");
|
||||
set => SetString("Remote Encryption Cipher", value);
|
||||
}
|
||||
|
||||
public string RemoteEncryptionKey
|
||||
{
|
||||
get => GetString("Remote Encryption Key");
|
||||
set => SetString("Remote Encryption Key", value);
|
||||
}
|
||||
|
||||
public long PushOperationsThreshold
|
||||
{
|
||||
get => GetLong("Push Operations Threshold", 0);
|
||||
set
|
||||
{
|
||||
ArgumentOutOfRangeException.ThrowIfNegative(value);
|
||||
this["Push Operations Threshold"] = value;
|
||||
}
|
||||
}
|
||||
|
||||
public long PullBytesThreshold
|
||||
{
|
||||
get => GetLong("Pull Bytes Threshold", 0);
|
||||
set
|
||||
{
|
||||
ArgumentOutOfRangeException.ThrowIfNegative(value);
|
||||
this["Pull Bytes Threshold"] = value;
|
||||
}
|
||||
}
|
||||
|
||||
public bool ForceLogicalMvccPull
|
||||
{
|
||||
get => GetBool("Force Logical MVCC Pull");
|
||||
set => this["Force Logical MVCC Pull"] = value;
|
||||
}
|
||||
|
||||
public string SyncExperimentalFeatures
|
||||
{
|
||||
get => GetString("Sync Experimental Features");
|
||||
set => SetString("Sync Experimental Features", value);
|
||||
}
|
||||
|
||||
public bool? Tls
|
||||
{
|
||||
get => GetNullableBool("Tls");
|
||||
@@ -252,6 +376,13 @@ public sealed class TursoConnectionStringBuilder : DbConnectionStringBuilder
|
||||
: defaultValue;
|
||||
}
|
||||
|
||||
private long GetLong(string keyword, long defaultValue)
|
||||
{
|
||||
return TryGetValue(keyword, out var value)
|
||||
? Convert.ToInt64(value, CultureInfo.InvariantCulture)
|
||||
: defaultValue;
|
||||
}
|
||||
|
||||
private void SetNullable<T>(string keyword, T? value)
|
||||
where T : struct
|
||||
{
|
||||
|
||||
@@ -51,6 +51,24 @@ public sealed class TursoRemoteEncryptionOptions
|
||||
ArgumentException.ThrowIfNullOrWhiteSpace(Key);
|
||||
_ = ReservedBytes;
|
||||
}
|
||||
|
||||
internal static TursoRemoteEncryptionCipher ParseCipher(string value)
|
||||
{
|
||||
ArgumentException.ThrowIfNullOrWhiteSpace(value);
|
||||
return value.Trim().ToLowerInvariant() switch
|
||||
{
|
||||
"aes256gcm" => TursoRemoteEncryptionCipher.Aes256Gcm,
|
||||
"aes128gcm" => TursoRemoteEncryptionCipher.Aes128Gcm,
|
||||
"chacha20poly1305" => TursoRemoteEncryptionCipher.ChaCha20Poly1305,
|
||||
"aegis128l" => TursoRemoteEncryptionCipher.Aegis128L,
|
||||
"aegis128x2" => TursoRemoteEncryptionCipher.Aegis128X2,
|
||||
"aegis128x4" => TursoRemoteEncryptionCipher.Aegis128X4,
|
||||
"aegis256" => TursoRemoteEncryptionCipher.Aegis256,
|
||||
"aegis256x2" => TursoRemoteEncryptionCipher.Aegis256X2,
|
||||
"aegis256x4" => TursoRemoteEncryptionCipher.Aegis256X4,
|
||||
_ => throw new InvalidOperationException($"Unknown remote encryption cipher: {value}"),
|
||||
};
|
||||
}
|
||||
}
|
||||
|
||||
public sealed class TursoPartialSyncOptions
|
||||
|
||||
@@ -333,6 +333,29 @@ public sealed class TursoManagedSyncTests
|
||||
reader.IsClosed.Should().BeTrue();
|
||||
}
|
||||
|
||||
[Test]
|
||||
public async Task ClosingAConnectionDoesNotDisposeTheExplicitSyncDatabase()
|
||||
{
|
||||
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)");
|
||||
}
|
||||
|
||||
var stats = await database.GetStatsAsync();
|
||||
await using var reopened = await database.ConnectAsync();
|
||||
|
||||
stats.Revision.Should().NotBeNull();
|
||||
using var query = new TursoCommand(reopened, "SELECT COUNT(*) FROM items");
|
||||
query.ExecuteScalar().Should().Be(0L);
|
||||
}
|
||||
|
||||
[Test]
|
||||
public async Task ConnectionQueuedBeforeDisposeIsRejectedAfterItGetsTheGate()
|
||||
{
|
||||
|
||||
@@ -27,14 +27,13 @@ public class TursoRemoteTests
|
||||
}
|
||||
|
||||
[Test]
|
||||
public void TestRemoteReplicaFailsBeforeNetworkAccess()
|
||||
public void TestRemoteReplicaConnectionStringIsRecognized()
|
||||
{
|
||||
using var connection = new TursoConnection(
|
||||
var options = TursoConnectionOptions.Parse(
|
||||
"Data Source=libsql://example.turso.io;Auth Token=secret;Replica Path=replica.db");
|
||||
|
||||
connection.Invoking(x => x.Open())
|
||||
.Should().Throw<NotSupportedException>()
|
||||
.WithMessage("Embedded replica connections are not supported yet by the .NET provider.*");
|
||||
options.IsReplica.Should().BeTrue();
|
||||
options.ReplicaPath.Should().Be("replica.db");
|
||||
}
|
||||
|
||||
[Test]
|
||||
|
||||
61
bindings/dotnet/src/Turso.Tests/TursoReplicaCloudTests.cs
Normal file
61
bindings/dotnet/src/Turso.Tests/TursoReplicaCloudTests.cs
Normal file
@@ -0,0 +1,61 @@
|
||||
using AwesomeAssertions;
|
||||
|
||||
namespace Turso.Tests;
|
||||
|
||||
[NonParallelizable]
|
||||
public sealed class TursoReplicaCloudTests
|
||||
{
|
||||
[Test]
|
||||
public async Task ExplicitPullConvergesWithRemoteChanges()
|
||||
{
|
||||
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 replica Cloud test.");
|
||||
|
||||
var tableName = "dotnet_replica_" + Guid.NewGuid().ToString("N");
|
||||
var directory = Path.Combine(
|
||||
TestContext.CurrentContext.WorkDirectory,
|
||||
"turso-cloud-replica-" + Guid.NewGuid().ToString("N"));
|
||||
Directory.CreateDirectory(directory);
|
||||
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={Path.Combine(directory, "replica.db")};Pooling=False");
|
||||
await replica.OpenAsync();
|
||||
await ExecuteNonQueryAsync(remote, $"UPDATE {tableName} SET value = 2 WHERE id = 1");
|
||||
|
||||
await replica.SyncAsync();
|
||||
|
||||
await using var query = replica.CreateCommand();
|
||||
query.CommandText = $"SELECT value FROM {tableName} WHERE id = 1";
|
||||
(await query.ExecuteScalarAsync()).Should().Be(2L);
|
||||
}
|
||||
finally
|
||||
{
|
||||
try
|
||||
{
|
||||
await ExecuteNonQueryAsync(remote, $"DROP TABLE IF EXISTS {tableName}");
|
||||
}
|
||||
finally
|
||||
{
|
||||
Directory.Delete(directory, recursive: true);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
private static async Task ExecuteNonQueryAsync(TursoConnection connection, string sql)
|
||||
{
|
||||
await using var command = connection.CreateCommand();
|
||||
command.CommandText = sql;
|
||||
await command.ExecuteNonQueryAsync();
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,265 @@
|
||||
using System.Data;
|
||||
using System.Net;
|
||||
using AwesomeAssertions;
|
||||
|
||||
namespace Turso.Tests;
|
||||
|
||||
[NonParallelizable]
|
||||
public sealed class TursoReplicaConnectionStringTests
|
||||
{
|
||||
[Test]
|
||||
public void ReplicaConnectionStringMapsAdvancedSyncOptions()
|
||||
{
|
||||
var builder = new TursoConnectionStringBuilder
|
||||
{
|
||||
DataSource = "turso://example.test",
|
||||
AuthToken = "secret",
|
||||
ReplicaPath = "replica.db",
|
||||
SyncClientName = "consumer",
|
||||
SyncLongPollTimeout = 2500,
|
||||
BootstrapIfEmpty = true,
|
||||
PartialBootstrapPrefix = 8192,
|
||||
PartialSyncSegmentSize = 4096,
|
||||
PartialSyncPrefetch = true,
|
||||
PushOperationsThreshold = 100,
|
||||
PullBytesThreshold = 65536,
|
||||
ForceLogicalMvccPull = true,
|
||||
SyncExperimentalFeatures = "views",
|
||||
};
|
||||
|
||||
using var connection = new TursoConnection(builder.ConnectionString);
|
||||
var options = connection.CreateReplicaOptions();
|
||||
|
||||
options.Path.Should().Be("replica.db");
|
||||
options.RemoteUri.Should().Be(new Uri("https://example.test/"));
|
||||
options.AuthToken.Should().Be("secret");
|
||||
options.ClientName.Should().Be("consumer");
|
||||
options.LongPollTimeout.Should().Be(TimeSpan.FromMilliseconds(2500));
|
||||
options.BootstrapIfEmpty.Should().BeTrue();
|
||||
options.PartialSync!.PrefixLength.Should().Be(8192);
|
||||
options.PartialSync.SegmentSize.Should().Be(4096);
|
||||
options.PartialSync.Prefetch.Should().BeTrue();
|
||||
options.PushOperationsThreshold.Should().Be(100);
|
||||
options.PullBytesThreshold.Should().Be(65536);
|
||||
options.ForceLogicalMvccPull.Should().BeTrue();
|
||||
options.ExperimentalFeatures.Should().Be("views");
|
||||
}
|
||||
|
||||
[Test]
|
||||
public void ReplicaConnectionStringMapsRemoteEncryption()
|
||||
{
|
||||
using var connection = new TursoConnection(
|
||||
"Data Source=turso://example.test;Replica Path=replica.db;"
|
||||
+ "Remote Encryption Cipher=aes256gcm;Remote Encryption Key=base64-key");
|
||||
|
||||
var options = connection.CreateReplicaOptions();
|
||||
|
||||
options.RemoteEncryption!.Cipher.Should().Be(TursoRemoteEncryptionCipher.Aes256Gcm);
|
||||
options.RemoteEncryption.Key.Should().Be("base64-key");
|
||||
}
|
||||
|
||||
[Test]
|
||||
public void LocalEncryptionKeysAreRejectedForRemoteReplicas()
|
||||
{
|
||||
using var connection = new TursoConnection(
|
||||
"Data Source=turso://example.test;Replica Path=replica.db;"
|
||||
+ "Encryption Cipher=aes256gcm;Encryption Key=hex-key");
|
||||
|
||||
connection.Invoking(x => x.CreateReplicaOptions())
|
||||
.Should().Throw<InvalidOperationException>()
|
||||
.WithMessage("*Remote Encryption Cipher*Remote Encryption Key*");
|
||||
}
|
||||
|
||||
[Test]
|
||||
public void PartialSyncModifiersRequireABootstrapStrategy()
|
||||
{
|
||||
using var connection = new TursoConnection(
|
||||
"Data Source=turso://example.test;Replica Path=replica.db;"
|
||||
+ "Partial Sync Segment Size=4096;Partial Sync Prefetch=True");
|
||||
|
||||
connection.CreateReplicaOptions().Invoking(options => options.Validate())
|
||||
.Should().Throw<InvalidOperationException>()
|
||||
.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)
|
||||
{
|
||||
using var connection = new TursoConnection(
|
||||
$"Data Source=turso://example.test;Replica Path=:memory:;Bootstrap If Empty=False;{option}");
|
||||
|
||||
connection.Invoking(x => x.Open())
|
||||
.Should().Throw<NotSupportedException>()
|
||||
.WithMessage($"{message}*");
|
||||
}
|
||||
|
||||
[TestCase(false)]
|
||||
[TestCase(true)]
|
||||
public async Task MemoryReplicaSupportsSynchronousAndAsynchronousOpen(bool openAsync)
|
||||
{
|
||||
using var httpClient = new HttpClient(new UnexpectedHttpHandler());
|
||||
TursoConnection.SyncHttpClientFactory = () => httpClient;
|
||||
try
|
||||
{
|
||||
using var connection = new TursoConnection(
|
||||
"Data Source=turso://example.test;Replica Path=:memory:;Bootstrap If Empty=False");
|
||||
|
||||
if (openAsync)
|
||||
await connection.OpenAsync();
|
||||
else
|
||||
connection.Open();
|
||||
|
||||
connection.State.Should().Be(ConnectionState.Open);
|
||||
connection.ExecuteNonQuery("CREATE TABLE items(value INTEGER)");
|
||||
using var command = new TursoCommand(connection, "SELECT COUNT(*) FROM items");
|
||||
command.ExecuteScalar().Should().Be(0L);
|
||||
}
|
||||
finally
|
||||
{
|
||||
TursoConnection.SyncHttpClientFactory = null;
|
||||
}
|
||||
}
|
||||
|
||||
[Test]
|
||||
public void FileReplicaCanBeClosedAndReopened()
|
||||
{
|
||||
var directory = Path.Combine(
|
||||
TestContext.CurrentContext.WorkDirectory,
|
||||
"turso-connection-replica-" + Guid.NewGuid().ToString("N"));
|
||||
Directory.CreateDirectory(directory);
|
||||
var path = Path.Combine(directory, "replica.db");
|
||||
var connectionString =
|
||||
$"Data Source=turso://example.test;Replica Path={path};Bootstrap If Empty=False";
|
||||
using var httpClient = new HttpClient(new UnexpectedHttpHandler());
|
||||
TursoConnection.SyncHttpClientFactory = () => httpClient;
|
||||
try
|
||||
{
|
||||
using (var created = new TursoConnection(connectionString))
|
||||
{
|
||||
created.Open();
|
||||
created.ExecuteNonQuery("CREATE TABLE persisted(value TEXT)");
|
||||
created.ExecuteNonQuery("INSERT INTO persisted VALUES ('yes')");
|
||||
}
|
||||
|
||||
using var reopened = new TursoConnection(connectionString);
|
||||
reopened.Open();
|
||||
using var query = new TursoCommand(reopened, "SELECT value FROM persisted");
|
||||
query.ExecuteScalar().Should().Be("yes");
|
||||
}
|
||||
finally
|
||||
{
|
||||
TursoConnection.SyncHttpClientFactory = null;
|
||||
Directory.Delete(directory, recursive: true);
|
||||
}
|
||||
}
|
||||
|
||||
[Test]
|
||||
public async Task CanceledAsyncOpenLeavesConnectionClosedAndReusable()
|
||||
{
|
||||
var handler = new CancelThenRejectHandler();
|
||||
using var httpClient = new HttpClient(handler);
|
||||
TursoConnection.SyncHttpClientFactory = () => httpClient;
|
||||
try
|
||||
{
|
||||
using var connection = new TursoConnection(
|
||||
"Data Source=turso://example.test;Replica Path=:memory:");
|
||||
using var cancellation = new CancellationTokenSource(TimeSpan.FromMilliseconds(100));
|
||||
|
||||
var canceledOpen = async () => await connection.OpenAsync(cancellation.Token);
|
||||
await canceledOpen.Should().ThrowAsync<OperationCanceledException>();
|
||||
connection.State.Should().Be(ConnectionState.Closed);
|
||||
|
||||
var nextOpen = async () => await connection.OpenAsync();
|
||||
await nextOpen.Should().ThrowAsync<TursoSyncException>();
|
||||
connection.State.Should().Be(ConnectionState.Closed);
|
||||
handler.RequestCount.Should().Be(2);
|
||||
}
|
||||
finally
|
||||
{
|
||||
TursoConnection.SyncHttpClientFactory = null;
|
||||
}
|
||||
}
|
||||
|
||||
[Test]
|
||||
public async Task ExplicitSyncPullsAndRecoversAfterCancellation()
|
||||
{
|
||||
var handler = new CancelThenRejectHandler();
|
||||
using var httpClient = new HttpClient(handler);
|
||||
TursoConnection.SyncHttpClientFactory = () => httpClient;
|
||||
try
|
||||
{
|
||||
using var connection = new TursoConnection(
|
||||
"Data Source=turso://example.test;Replica Path=:memory:;Bootstrap If Empty=False");
|
||||
await connection.OpenAsync();
|
||||
using var cancellation = new CancellationTokenSource(TimeSpan.FromMilliseconds(100));
|
||||
|
||||
var canceledSync = async () => await connection.SyncAsync(cancellation.Token);
|
||||
await canceledSync.Should().ThrowAsync<OperationCanceledException>();
|
||||
|
||||
var nextSync = async () => await connection.SyncAsync();
|
||||
await nextSync.Should().ThrowAsync<TursoSyncException>();
|
||||
handler.RequestCount.Should().Be(2);
|
||||
}
|
||||
finally
|
||||
{
|
||||
TursoConnection.SyncHttpClientFactory = null;
|
||||
}
|
||||
}
|
||||
|
||||
[Test]
|
||||
public void ClosingReplicaClosesActiveReadersBeforeOwnedDatabase()
|
||||
{
|
||||
using var httpClient = new HttpClient(new UnexpectedHttpHandler());
|
||||
TursoConnection.SyncHttpClientFactory = () => httpClient;
|
||||
try
|
||||
{
|
||||
using var connection = new TursoConnection(
|
||||
"Data Source=turso://example.test;Replica Path=:memory:;Bootstrap If Empty=False");
|
||||
connection.Open();
|
||||
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();
|
||||
}
|
||||
finally
|
||||
{
|
||||
TursoConnection.SyncHttpClientFactory = null;
|
||||
}
|
||||
}
|
||||
|
||||
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 CancelThenRejectHandler : 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([]),
|
||||
};
|
||||
}
|
||||
}
|
||||
}
|
||||
Reference in New Issue
Block a user