Path: redb/redb.Core/Providers/Base/SchemeSyncProviderBase.SchemaLock.cs Snapshot: redb, development snapshot 2026-12-06. This is the development state of the public mirrors; it may differ from the published packages. License: Apache-2.0. Repository: https://github.com/redbase-app/redb Page: https://redbase.app/src/dev-2026-12-06/redb/redb.Core/Providers/Base/SchemeSyncProviderBase.SchemaLock.cs ---- using System; using System.Threading; using System.Threading.Tasks; using Microsoft.Extensions.Logging; namespace redb.Core.Providers.Base; /// /// The schema lock around a scheme sync. Nodes of a cluster sync the same schemes at once: they start together, /// their modules share Props classes, a new version of a module adds a field on every node at the same moment. /// Two of them inserting the same structure failed on the unique keys of _schemes and _structures, /// two rebuilding the metadata cache of one scheme on its rows. /// /// /// A sync first runs as a check: the same code, reading only. The first write it reaches stops it, and the sync /// runs again under the schema lock of the service, now writing; a node that waited for the lock finds the work done /// and writes nothing. A scheme already in step (nearly every start) never reaches a write and never takes the lock. /// /// public abstract partial class SchemeSyncProviderBase { /// /// Runs work under the schema lock of the service that owns this provider (reentrant). Set by the service right /// after it builds the provider; left null, the sync writes without a lock, as a provider built on its own did. /// public Func, CancellationToken, Task>? RunUnderSchemaLock { get; set; } /// /// Receives the schema problems a sync meets (duplicate root structures it leaves alone): the service logs them as /// errors and lists them in . Left null, the provider logs them itself. /// public Action? SchemaProblemFound { get; set; } private void ReportSchemaProblem(Models.RedbSchemaProblem problem) { if (SchemaProblemFound != null) SchemaProblemFound(problem); else Logger?.LogError("{Problem}", problem.Message); } private enum SyncPass { Check, Write } // The pass of the sync running in this flow; null outside one. A sync nested in another (SyncSchemeAsync calling // SyncStructuresFromTypeAsync) belongs to the outer pass. private readonly AsyncLocal _syncPass = new(); /// Thrown at the first write of a check pass; never leaves . private sealed class SchemeWriteNeededException : Exception { } private bool IsCheckPass => _syncPass.Value == SyncPass.Check; /// Called before every write of a sync: a check pass stops here. private void BeforeSchemeWrite() { if (IsCheckPass) throw new SchemeWriteNeededException(); ForgetCachedSchemesIfRolledBack(); } // Transactions whose rollback already clears the scheme caches: one registration per transaction. private static readonly System.Runtime.CompilerServices.ConditionalWeakTable RollbackResetRegistered = new(); /// /// A sync that writes inside a transaction caches the schemes and structures it creates before the transaction /// ends. If it rolls back, those entries point at rows that do not exist (and ids that are never handed out /// again): the next save of the type would reference a missing scheme. The caches of this database are dropped /// on that rollback and refill from the database. /// private void ForgetCachedSchemesIfRolledBack() { if (Data.TransactionHooks.TransactionOf(Context) is not { } transaction) return; if (!RollbackResetRegistered.TryAdd(transaction, transaction)) return; Data.TransactionHooks.OnCompleted(Context, committed => { if (committed) return; Cache.ClearDomainIncludingClrTypes(); }); } private async Task GuardSchemeSyncAsync(Func> sync, CancellationToken cancellationToken) { // Inside a transaction of the caller the lock would be released before the caller commits, and the next node // would not see the rows written under it: such a sync runs as before, unguarded. if (_syncPass.Value != null || RunUnderSchemaLock == null || Context.IsInTransaction) return await sync(); _syncPass.Value = SyncPass.Check; try { return await sync(); } catch (SchemeWriteNeededException) { } T result = default!; await RunUnderSchemaLock(async () => { _syncPass.Value = SyncPass.Write; result = await sync(); }, cancellationToken); return result; } }