Merge CultCache publication Cuts 1-2: project before mint, isolated observers
Soul verdict: merge. Before Cut 4 relies on sequence density: pin the publish-on-throw guard in Held and observer removal on unsubscribe. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
commit
2a1b8a8cda
5 changed files with 725 additions and 54 deletions
|
|
@ -77,14 +77,21 @@ which route wrote it.
|
|||
- An `OnUpdate` handler exception is rethrown to that caller after all of that
|
||||
call's changes are delivered (an `AggregateException` if several threw). If
|
||||
the call itself failed, its own exception is rethrown and handler exceptions
|
||||
are dropped. A `Watch` subscriber exception is not rethrown; it follows R3's
|
||||
unhandled-exception handling. A throwing handler cannot undo the store's
|
||||
adoption of a load; the store and cache already agree when publication starts.
|
||||
are dropped. Every `Watch` subscriber receives every change: R3 routes a
|
||||
subscriber's exception to its unhandled-exception handler, and if that handler
|
||||
rethrows (fail-fast), the exception is treated as an `OnUpdate` handler
|
||||
exception. The subscriber stays subscribed and the commit stands. A throwing
|
||||
handler cannot undo the store's adoption of a load; the store and cache
|
||||
already agree when publication starts.
|
||||
- A record's `[CultName]` and `[CultIndex]` getters run once per landing record,
|
||||
before the store is written and before any `Sequence` is minted. A getter that
|
||||
throws refuses the whole change set, loads included: nothing is written,
|
||||
minted or left in memory.
|
||||
- Pulling all stores pulls every attached store even if a handler throws during
|
||||
one store's load, then rethrows.
|
||||
- Hydration failure on open is loud: a corrupt store file, or a record whose
|
||||
schema the registry cannot resolve, makes the open throw and leaves the file
|
||||
byte-identical. Consumers never delete and rewrite a store they failed to
|
||||
schema the registry cannot resolve or whose name or index getter throws, makes
|
||||
the open throw and leaves the file byte-identical. Consumers never delete and rewrite a store they failed to
|
||||
open.
|
||||
|
||||
## Locking
|
||||
|
|
|
|||
|
|
@ -1806,7 +1806,11 @@ namespace GameCult.Caching
|
|||
// Keys holding a variant: derived from the entries by Apply, never decided anywhere else.
|
||||
private readonly HashSet<string> _variantKeys = new(StringComparer.Ordinal);
|
||||
private readonly ConditionalWeakTable<object, KeyBox> _handles = new();
|
||||
private readonly Subject<Change> _changes = new();
|
||||
// The cache's own observers, copy-on-write under _observerGate: publication reads one snapshot per change and
|
||||
// catches per observer, so no observer decides whether another receives a change.
|
||||
private Observer<Change>[] _observers = Array.Empty<Observer<Change>>();
|
||||
private bool _observersCompleted;
|
||||
private readonly object _observerGate = new();
|
||||
private readonly object _gate = new();
|
||||
private long _sequence;
|
||||
// The changes admitted by this thread's outermost hold, published by that hold when it exits.
|
||||
|
|
@ -1886,7 +1890,7 @@ namespace GameCult.Caching
|
|||
|
||||
public Observable<CultCacheDocumentChange<T>> Watch<T>() where T : class
|
||||
{
|
||||
return _changes
|
||||
return Observable.Create<Change>(Register)
|
||||
.Where(change => typeof(T).IsAssignableFrom(change.Stored.Descriptor.DocumentType))
|
||||
.Select(change => new CultCacheDocumentChange<T>(
|
||||
change.Kind,
|
||||
|
|
@ -1896,6 +1900,25 @@ namespace GameCult.Caching
|
|||
change.Sequence));
|
||||
}
|
||||
|
||||
private IDisposable Register(Observer<Change> observer)
|
||||
{
|
||||
lock (_observerGate)
|
||||
{
|
||||
if (!_observersCompleted)
|
||||
{
|
||||
_observers = _observers.Append(observer).ToArray();
|
||||
return Disposable.Create(() =>
|
||||
{
|
||||
lock (_observerGate)
|
||||
_observers = _observers.Where(held => !ReferenceEquals(held, observer)).ToArray();
|
||||
});
|
||||
}
|
||||
}
|
||||
|
||||
observer.OnCompleted();
|
||||
return Disposable.Empty;
|
||||
}
|
||||
|
||||
public Observable<CultCacheDocumentChange<T>> WatchRecord<T>(CultRecordKey key) where T : class
|
||||
{
|
||||
return Watch<T>().Where(change => change.Key.Equals(key));
|
||||
|
|
@ -2151,7 +2174,31 @@ namespace GameCult.Caching
|
|||
foreach (var store in BackingStores)
|
||||
store.Dispose();
|
||||
|
||||
_changes.Dispose();
|
||||
Observer<Change>[] completing;
|
||||
lock (_observerGate)
|
||||
{
|
||||
completing = _observers;
|
||||
_observers = Array.Empty<Observer<Change>>();
|
||||
_observersCompleted = true;
|
||||
}
|
||||
|
||||
var failures = new List<Exception>();
|
||||
foreach (var observer in completing)
|
||||
{
|
||||
try
|
||||
{
|
||||
observer.OnCompleted();
|
||||
}
|
||||
catch (Exception exception)
|
||||
{
|
||||
failures.Add(exception);
|
||||
}
|
||||
}
|
||||
|
||||
if (failures.Count == 1)
|
||||
ExceptionDispatchInfo.Capture(failures[0]).Throw();
|
||||
if (failures.Count > 1)
|
||||
throw new AggregateException(failures);
|
||||
}
|
||||
|
||||
internal static void RequireInstanceOf(Type documentType, object document)
|
||||
|
|
@ -2333,8 +2380,8 @@ namespace GameCult.Caching
|
|||
// Every admission runs in a hold. A nested hold on the same cache adds to the outermost one, which publishes
|
||||
// exactly its own changes after it leaves the gate, before it returns, on its caller's thread: observers never
|
||||
// run under the gate, and a write an observer makes is a new outermost hold. Cross-thread delivery order is not
|
||||
// guaranteed; each change carries the Sequence it was admitted with. Every change is delivered even if an
|
||||
// OnUpdate handler throws; then the first handler exception (an AggregateException for several) is rethrown.
|
||||
// guaranteed; each change carries the Sequence it was admitted with. Every change reaches every observer even
|
||||
// if an observer or an OnUpdate handler throws; then the first exception (an AggregateException for several) is rethrown.
|
||||
// If the body threw, its exception wins.
|
||||
internal T Held<T>(Func<T> body)
|
||||
{
|
||||
|
|
@ -2371,8 +2418,20 @@ namespace GameCult.Caching
|
|||
var failures = new List<Exception>();
|
||||
foreach (var (change, loaded) in changes)
|
||||
{
|
||||
// R3 routes a throwing subscriber to its unhandled-exception handler; OnNext does not throw.
|
||||
_changes.OnNext(change);
|
||||
// R3 routes a throwing subscriber to its unhandled-exception handler, and a fail-fast handler rethrows: every
|
||||
// observer still runs, the exception joins the failures, and the observer stays subscribed.
|
||||
foreach (var observer in Volatile.Read(ref _observers))
|
||||
{
|
||||
try
|
||||
{
|
||||
observer.OnNext(change);
|
||||
}
|
||||
catch (Exception exception)
|
||||
{
|
||||
failures.Add(exception);
|
||||
}
|
||||
}
|
||||
|
||||
if (!loaded)
|
||||
continue;
|
||||
try
|
||||
|
|
@ -2465,11 +2524,84 @@ namespace GameCult.Caching
|
|||
|
||||
// Variants this admission did not write whose base chain it changed: re-resolved, same delta, same storedAt.
|
||||
public List<CultStoredDocument> Dependents { get; } = new();
|
||||
|
||||
// Name and index values of every record that lands (Admitted and Dependents), by key. Filled once by Project.
|
||||
public Dictionary<string, Projection> Projections { get; } = new(StringComparer.Ordinal);
|
||||
}
|
||||
|
||||
// What a landing record's [CultName] and [CultIndex] getters said. Indexes holds only non-blank values.
|
||||
private sealed class Projection
|
||||
{
|
||||
public Projection(string? name, (string Alias, string Value)[] indexes)
|
||||
{
|
||||
Name = name;
|
||||
Indexes = indexes;
|
||||
}
|
||||
|
||||
public string? Name { get; }
|
||||
public (string Alias, string Value)[] Indexes { get; }
|
||||
}
|
||||
|
||||
// The only place an admission runs a name or index getter on a landing record. It runs before land and before any
|
||||
// sequence is minted, so a getter that throws refuses the whole admission with nothing written and nothing minted.
|
||||
private static void Project(VariantPlan plan)
|
||||
{
|
||||
foreach (var stored in plan.Admitted.Concat(plan.Dependents))
|
||||
{
|
||||
var descriptor = stored.Descriptor;
|
||||
var name = descriptor.NameAccessor == null ? null : NameRead(stored);
|
||||
var indexes = new List<(string Alias, string Value)>();
|
||||
foreach (var pair in descriptor.IndexAccessors)
|
||||
{
|
||||
var member = descriptor.RichMembers.First(candidate => candidate.IndexAlias == pair.Key).Member.Name;
|
||||
var value = Read(stored, $"index '{pair.Key}' member {member}", pair.Value);
|
||||
if (!string.IsNullOrWhiteSpace(value))
|
||||
indexes.Add((pair.Key, value!));
|
||||
}
|
||||
|
||||
plan.Projections[stored.Key.Value] = new Projection(name, indexes.ToArray());
|
||||
}
|
||||
}
|
||||
|
||||
// A blank name is no name.
|
||||
private static string? NameRead(CultStoredDocument stored) =>
|
||||
Read(stored, $"[CultName] member {stored.Descriptor.NameMember}", stored.Descriptor.NameAccessor!) is { Length: > 0 } name ? name : null;
|
||||
|
||||
private static string? Read(CultStoredDocument stored, string what, Func<object, string?> getter)
|
||||
{
|
||||
try
|
||||
{
|
||||
return getter(stored.Document);
|
||||
}
|
||||
catch (Exception exception)
|
||||
{
|
||||
throw new InvalidOperationException(
|
||||
$"Record {stored.Key.Value} ({stored.Descriptor.SchemaName}) is refused: its {what} threw: {exception.GetBaseException().Message}", exception);
|
||||
}
|
||||
}
|
||||
|
||||
// Every admission is judged here: variants resolved, then every landing record's name and index values read once,
|
||||
// then the rules that compare them. It refuses naming the keys, and mutates nothing.
|
||||
private VariantPlan Resolve(
|
||||
IReadOnlyList<CultStoredDocument> admitted,
|
||||
IReadOnlyList<CultStoredDocument> evicted,
|
||||
CacheBackingStore? source)
|
||||
{
|
||||
var plan = ResolveVariants(admitted, evicted, source);
|
||||
Project(plan);
|
||||
// The variant rules are judged only when a variant is involved.
|
||||
if (_variantKeys.Count != 0 || admitted.Any(stored => stored.Variant != null))
|
||||
{
|
||||
RefuseVariantNameSharing(plan);
|
||||
RefuseVariantIndexSharing(plan, evicted);
|
||||
}
|
||||
|
||||
return plan;
|
||||
}
|
||||
|
||||
// Resolves every admitted variant and every variant whose base chain this admission changes, base first, against
|
||||
// the post-admission set. It refuses a broken variant naming the keys, and mutates nothing.
|
||||
private VariantPlan Resolve(
|
||||
private VariantPlan ResolveVariants(
|
||||
IReadOnlyList<CultStoredDocument> admitted,
|
||||
IReadOnlyList<CultStoredDocument> evicted,
|
||||
CacheBackingStore? source)
|
||||
|
|
@ -2531,11 +2663,7 @@ namespace GameCult.Caching
|
|||
}
|
||||
|
||||
if (toResolve.Count == 0)
|
||||
{
|
||||
var unchanged = new VariantPlan(admitted);
|
||||
RefuseVariantIndexSharing(unchanged, incoming, gone);
|
||||
return unchanged;
|
||||
}
|
||||
return new VariantPlan(admitted);
|
||||
|
||||
var pending = new HashSet<string>(toResolve, StringComparer.Ordinal);
|
||||
var done = new Dictionary<string, CultStoredDocument>(StringComparer.Ordinal);
|
||||
|
|
@ -2546,7 +2674,6 @@ namespace GameCult.Caching
|
|||
var plan = new VariantPlan(admitted.Select(stored => done.TryGetValue(stored.Key.Value, out var resolved) ? resolved : stored).ToList());
|
||||
foreach (var key in toResolve.Where(key => !incoming.ContainsKey(key)))
|
||||
plan.Dependents.Add(done[key]);
|
||||
RefuseVariantIndexSharing(plan, incoming, gone);
|
||||
return plan;
|
||||
|
||||
CultStoredDocument ResolveOne(string key)
|
||||
|
|
@ -2610,21 +2737,6 @@ namespace GameCult.Caching
|
|||
var document = _codec.Deserialize(type, type, kept.Count == 0 ? payload : _codec.Overlay(payload, kept))
|
||||
?? throw new InvalidOperationException($"Variant {key} resolved to nothing.");
|
||||
|
||||
if (isVariant)
|
||||
{
|
||||
// R6: the name index maps one name to one key, so a variant that kept its base's name would shadow it.
|
||||
if (descriptor.NameAccessor?.Invoke(document) is { Length: > 0 } variantName)
|
||||
{
|
||||
for (var ancestor = baseStored; ancestor != null;
|
||||
ancestor = ancestor.Variant == null ? null : done.TryGetValue(ancestor.Variant.BaseKey, out var above) ? above : Lookup(ancestor.Variant.BaseKey))
|
||||
{
|
||||
if (descriptor.NameAccessor(ancestor.Document) == variantName)
|
||||
throw new InvalidOperationException(
|
||||
$"Variant {key} and its base {ancestor.Key.Value} are both named '{variantName}'; a variant must override its name.");
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
stack.RemoveAt(stack.Count - 1);
|
||||
return done[key] = isVariant
|
||||
? variant.Resolved(document)
|
||||
|
|
@ -2632,20 +2744,47 @@ namespace GameCult.Caching
|
|||
}
|
||||
}
|
||||
|
||||
// R6: the name index maps one name to one key, so a variant that kept its base's name would shadow it. A variant's
|
||||
// name is its projection; an ancestor that lands is read from its projection, one that stays is read as held.
|
||||
private void RefuseVariantNameSharing(VariantPlan plan)
|
||||
{
|
||||
var landing = plan.Admitted.Concat(plan.Dependents).ToDictionary(stored => stored.Key.Value, StringComparer.Ordinal);
|
||||
|
||||
// Resolution already refused a base that is missing or removed, so an ancestor is landing or held.
|
||||
CultStoredDocument? Ancestor(string key) =>
|
||||
landing.TryGetValue(key, out var landed) ? landed
|
||||
: _entries.TryGetValue(key, out var held) ? held : null;
|
||||
|
||||
string? NameOf(CultStoredDocument stored) =>
|
||||
plan.Projections.TryGetValue(stored.Key.Value, out var projection) ? projection.Name : NameRead(stored);
|
||||
|
||||
foreach (var variant in landing.Values.Where(stored => stored.Variant != null))
|
||||
{
|
||||
var variantName = plan.Projections[variant.Key.Value].Name;
|
||||
if (variantName == null)
|
||||
continue;
|
||||
for (var ancestor = Ancestor(variant.Variant!.BaseKey); ancestor != null;
|
||||
ancestor = ancestor.Variant == null ? null : Ancestor(ancestor.Variant.BaseKey))
|
||||
{
|
||||
if (NameOf(ancestor) == variantName)
|
||||
throw new InvalidOperationException(
|
||||
$"Variant {variant.Key.Value} and its base {ancestor.Key.Value} are both named '{variantName}'; a variant must override its name.");
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// The one index rule, judged on the commit's result whatever the write order: a variant may not share an indexed
|
||||
// value with another record. It reads the truthful held index (every holder of a value), minus the records this
|
||||
// commit replaces or removes, plus the records it lands. Plain-vs-plain sharing is not this rule's business.
|
||||
// A unique index maps a value to one key at lookup; a variant sharing it would be found in place of its
|
||||
// holder or lose the value, and the store would refuse to reopen.
|
||||
private void RefuseVariantIndexSharing(
|
||||
VariantPlan plan,
|
||||
IReadOnlyDictionary<string, CultStoredDocument> incoming,
|
||||
HashSet<string> gone)
|
||||
private void RefuseVariantIndexSharing(VariantPlan plan, IReadOnlyList<CultStoredDocument> evicted)
|
||||
{
|
||||
var landing = plan.Admitted.Concat(plan.Dependents).ToList();
|
||||
if (landing.All(stored => stored.Descriptor.IndexAccessors.Count == 0))
|
||||
return;
|
||||
var replaced = new HashSet<string>(incoming.Keys.Concat(gone).Concat(plan.Dependents.Select(stored => stored.Key.Value)), StringComparer.Ordinal);
|
||||
var replaced = new HashSet<string>(
|
||||
plan.Admitted.Concat(evicted).Concat(plan.Dependents).Select(stored => stored.Key.Value), StringComparer.Ordinal);
|
||||
var landingByKey = landing.ToDictionary(stored => stored.Key.Value, StringComparer.Ordinal);
|
||||
|
||||
bool IsVariant(string key) =>
|
||||
|
|
@ -2656,12 +2795,9 @@ namespace GameCult.Caching
|
|||
var landed = new Dictionary<((Type Type, string Alias) Index, string Value), List<string>>();
|
||||
foreach (var stored in landing)
|
||||
{
|
||||
foreach (var pair in stored.Descriptor.IndexAccessors)
|
||||
foreach (var (alias, value) in plan.Projections[stored.Key.Value].Indexes)
|
||||
{
|
||||
var value = pair.Value(stored.Document);
|
||||
if (string.IsNullOrWhiteSpace(value))
|
||||
continue;
|
||||
var index = (stored.Descriptor.DocumentType, pair.Key);
|
||||
var index = (stored.Descriptor.DocumentType, alias);
|
||||
landedValues.Add((stored, index, value));
|
||||
if (!landed.TryGetValue((index, value), out var landedKeys))
|
||||
landed[(index, value)] = landedKeys = new List<string>();
|
||||
|
|
@ -2733,7 +2869,7 @@ namespace GameCult.Caching
|
|||
|
||||
_entries[stored.Key.Value] = stored;
|
||||
_handles.AddOrUpdate(stored.Document, new KeyBox(stored.Key));
|
||||
Index(stored);
|
||||
Index(stored, plan.Projections[stored.Key.Value]);
|
||||
if (stored.Variant == null)
|
||||
_variantKeys.Remove(stored.Key.Value);
|
||||
else
|
||||
|
|
@ -2790,19 +2926,15 @@ namespace GameCult.Caching
|
|||
}
|
||||
}
|
||||
|
||||
private void Index(CultStoredDocument stored)
|
||||
private void Index(CultStoredDocument stored, Projection projection)
|
||||
{
|
||||
var type = stored.Descriptor.DocumentType;
|
||||
if (stored.Descriptor.IsGlobal)
|
||||
_globals[type] = stored.Key.Value;
|
||||
if (stored.Descriptor.NameAccessor?.Invoke(stored.Document) is { Length: > 0 } name)
|
||||
MapOf(_names, type)[name] = stored.Key.Value;
|
||||
foreach (var pair in stored.Descriptor.IndexAccessors)
|
||||
{
|
||||
var value = pair.Value(stored.Document);
|
||||
if (!string.IsNullOrWhiteSpace(value))
|
||||
AddHolder(_indexes, (type, pair.Key), value, stored.Key.Value);
|
||||
}
|
||||
if (projection.Name != null)
|
||||
MapOf(_names, type)[projection.Name] = stored.Key.Value;
|
||||
foreach (var (alias, value) in projection.Indexes)
|
||||
AddHolder(_indexes, (type, alias), value, stored.Key.Value);
|
||||
}
|
||||
|
||||
// Documents are mutable, so a name or index value may have changed since it was indexed: drop by key.
|
||||
|
|
|
|||
Loading…
Reference in a new issue