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.
|
||||
|
|
|
|||
174
tests/GameCult.Caching.Tests/CultCacheObserverTests.cs
Normal file
174
tests/GameCult.Caching.Tests/CultCacheObserverTests.cs
Normal file
|
|
@ -0,0 +1,174 @@
|
|||
#nullable enable
|
||||
using System;
|
||||
using System.Collections.Generic;
|
||||
using System.Linq;
|
||||
using GameCult.Caching;
|
||||
using GameCult.Caching.MessagePack;
|
||||
using MessagePack;
|
||||
using NUnit.Framework;
|
||||
using R3;
|
||||
|
||||
namespace GameCult.Caching.Tests
|
||||
{
|
||||
// Cut 2 of docs/cultcache-publication-cut.md: the cache keeps its own observers and catches per observer, so no
|
||||
// observer decides whether another receives a change. R3 routes a subscriber's exception to the unhandled handler;
|
||||
// these tests install a fail-fast (rethrowing) handler, the only way an exception reaches the cache.
|
||||
[NonParallelizable]
|
||||
public class CultCacheObserverTests
|
||||
{
|
||||
private static readonly CultDocumentRegistry Registry = CultDocumentRegistry.ForTypes(new[] { typeof(ObservedPing) });
|
||||
|
||||
private Action<Exception> _previousHandler = _ => { };
|
||||
|
||||
[SetUp]
|
||||
public void FailFast()
|
||||
{
|
||||
_previousHandler = ObservableSystem.GetUnhandledExceptionHandler();
|
||||
ObservableSystem.RegisterUnhandledExceptionHandler(exception => throw exception);
|
||||
}
|
||||
|
||||
[TearDown]
|
||||
public void Restore() => ObservableSystem.RegisterUnhandledExceptionHandler(_previousHandler);
|
||||
|
||||
[CultDocument("tests.observed_ping", "tests.observed_ping.v1")]
|
||||
[MessagePackObject(AllowPrivate = true)]
|
||||
internal sealed class ObservedPing
|
||||
{
|
||||
[Key(0)]
|
||||
public string Text = string.Empty;
|
||||
}
|
||||
|
||||
private static CultRecordKey KeyOf(string text) => new($"observed:{text}");
|
||||
|
||||
private static void Send(CultCache cache, params string[] texts) =>
|
||||
cache.Commit(batch =>
|
||||
{
|
||||
foreach (var text in texts)
|
||||
batch.Upsert(typeof(ObservedPing), new ObservedPing { Text = text }, KeyOf(text));
|
||||
});
|
||||
|
||||
[Test]
|
||||
public void AnEscapedObserverExceptionReachesTheWriterAfterEveryObserverSawEveryChange()
|
||||
{
|
||||
using var cache = new CultCache(Registry);
|
||||
var thrower = new List<string>();
|
||||
var later = new List<string>();
|
||||
using var first = cache.Watch<ObservedPing>().Subscribe(change =>
|
||||
{
|
||||
thrower.Add(change.Document!.Text);
|
||||
if (change.Document.Text == "boom")
|
||||
throw new InvalidOperationException("observer boom");
|
||||
});
|
||||
using var second = cache.Watch<ObservedPing>().Subscribe(change => later.Add(change.Document!.Text));
|
||||
|
||||
var escaped = Assert.Throws<InvalidOperationException>(() => Send(cache, "boom", "after"))!;
|
||||
|
||||
Assert.Multiple(() =>
|
||||
{
|
||||
Assert.That(escaped.Message, Is.EqualTo("observer boom"));
|
||||
Assert.That(later, Is.EqualTo(new[] { "boom", "after" }), "the observer after the thrower saw every change of the hold");
|
||||
Assert.That(thrower, Is.EqualTo(new[] { "boom", "after" }), "the thrower kept receiving after its own exception");
|
||||
Assert.That(cache.Get<ObservedPing>(KeyOf("boom")), Is.Not.Null, "the commit stands");
|
||||
Assert.That(cache.Get<ObservedPing>(KeyOf("after")), Is.Not.Null);
|
||||
});
|
||||
|
||||
Send(cache, "later");
|
||||
Assert.That(thrower, Is.EqualTo(new[] { "boom", "after", "later" }), "the thrower stayed subscribed");
|
||||
Assert.That(later, Is.EqualTo(new[] { "boom", "after", "later" }));
|
||||
}
|
||||
|
||||
[Test]
|
||||
public void SeveralEscapedObserverExceptionsArriveTogether()
|
||||
{
|
||||
using var cache = new CultCache(Registry);
|
||||
using var one = cache.Watch<ObservedPing>().Subscribe(_ => throw new InvalidOperationException("one"));
|
||||
using var two = cache.Watch<ObservedPing>().Subscribe(_ => throw new InvalidOperationException("two"));
|
||||
|
||||
var escaped = Assert.Throws<AggregateException>(() => Send(cache, "boom"))!;
|
||||
|
||||
Assert.That(escaped.InnerExceptions.Select(exception => exception.Message), Is.EqualTo(new[] { "one", "two" }));
|
||||
}
|
||||
|
||||
[Test]
|
||||
public void ObserversMayJoinAndLeaveDuringADeliveryWithoutBreakingTheOthers()
|
||||
{
|
||||
using var cache = new CultCache(Registry);
|
||||
var a = new List<long>();
|
||||
var b = new List<long>();
|
||||
var c = new List<long>();
|
||||
var d = new List<long>();
|
||||
IDisposable? leaving = null;
|
||||
IDisposable? joined = null;
|
||||
using var first = cache.Watch<ObservedPing>().Subscribe(change =>
|
||||
{
|
||||
a.Add(change.Sequence);
|
||||
if (a.Count != 1)
|
||||
return;
|
||||
leaving!.Dispose();
|
||||
joined = cache.Watch<ObservedPing>().Subscribe(next => c.Add(next.Sequence));
|
||||
});
|
||||
leaving = cache.Watch<ObservedPing>().Subscribe(change => b.Add(change.Sequence));
|
||||
using var last = cache.Watch<ObservedPing>().Subscribe(change => d.Add(change.Sequence));
|
||||
|
||||
Send(cache, "one", "two");
|
||||
joined?.Dispose();
|
||||
|
||||
Assert.Multiple(() =>
|
||||
{
|
||||
Assert.That(a, Is.EqualTo(new[] { 1L, 2L }));
|
||||
Assert.That(d, Is.EqualTo(new[] { 1L, 2L }), "an observer that did not move still saw everything");
|
||||
Assert.That(b, Does.Not.Contain(2L), "a disposed observer stops receiving");
|
||||
Assert.That(c, Is.EqualTo(new[] { 2L }), "an observer that joined mid-hold receives from the next change");
|
||||
});
|
||||
}
|
||||
|
||||
[Test]
|
||||
public void DisposeCompletesObserversAndACompletedCacheCompletesNewOnes()
|
||||
{
|
||||
var cache = new CultCache(Registry);
|
||||
var completed = 0;
|
||||
using var before = cache.Watch<ObservedPing>().Subscribe(_ => { }, _ => completed++);
|
||||
|
||||
cache.Dispose();
|
||||
Assert.That(completed, Is.EqualTo(1));
|
||||
|
||||
using var after = cache.Watch<ObservedPing>().Subscribe(_ => { }, _ => completed++);
|
||||
Assert.That(completed, Is.EqualTo(2), "subscribing to a disposed cache completes at once");
|
||||
}
|
||||
|
||||
// Completing an observer is publication too: every observer is completed, and a fail-fast handler's exception
|
||||
// reaches the disposer afterwards (an AggregateException for several).
|
||||
[Test]
|
||||
public void ACompletionThatEscapesReachesTheDisposerAfterEveryObserverCompleted()
|
||||
{
|
||||
var cache = new CultCache(Registry);
|
||||
var completed = new List<string>();
|
||||
using var one = cache.Watch<ObservedPing>().Subscribe(_ => { }, _ =>
|
||||
{
|
||||
completed.Add("one");
|
||||
throw new InvalidOperationException("one");
|
||||
});
|
||||
using var two = cache.Watch<ObservedPing>().Subscribe(_ => { }, _ =>
|
||||
{
|
||||
completed.Add("two");
|
||||
throw new InvalidOperationException("two");
|
||||
});
|
||||
|
||||
var escaped = Assert.Throws<AggregateException>(() => cache.Dispose())!;
|
||||
|
||||
Assert.That(completed, Is.EqualTo(new[] { "one", "two" }));
|
||||
Assert.That(escaped.InnerExceptions.Select(exception => exception.Message), Is.EqualTo(new[] { "one", "two" }));
|
||||
}
|
||||
|
||||
[Test]
|
||||
public void ASingleEscapedCompletionIsRethrownAsItself()
|
||||
{
|
||||
var cache = new CultCache(Registry);
|
||||
using var only = cache.Watch<ObservedPing>().Subscribe(_ => { }, _ => throw new InvalidOperationException("only"));
|
||||
|
||||
var escaped = Assert.Throws<InvalidOperationException>(() => cache.Dispose())!;
|
||||
|
||||
Assert.That(escaped.Message, Is.EqualTo("only"));
|
||||
}
|
||||
}
|
||||
}
|
||||
258
tests/GameCult.Caching.Tests/CultCacheProjectionTests.cs
Normal file
258
tests/GameCult.Caching.Tests/CultCacheProjectionTests.cs
Normal file
|
|
@ -0,0 +1,258 @@
|
|||
#nullable enable
|
||||
using System;
|
||||
using System.Collections.Generic;
|
||||
using System.IO;
|
||||
using System.Linq;
|
||||
using System.Threading;
|
||||
using GameCult.Caching;
|
||||
using GameCult.Caching.MessagePack;
|
||||
using MessagePack;
|
||||
using NUnit.Framework;
|
||||
using R3;
|
||||
|
||||
namespace GameCult.Caching.Tests
|
||||
{
|
||||
// Cut 1 of docs/cultcache-publication-cut.md: an admission reads every landing record's name and index values once,
|
||||
// before land and before any sequence is minted. A getter that throws refuses the whole change set.
|
||||
[NonParallelizable]
|
||||
public class CultCacheProjectionTests
|
||||
{
|
||||
private static readonly CultDocumentRegistry Registry = CultDocumentRegistry.ForTypes(new[] { typeof(ProjectedRecord) });
|
||||
|
||||
private string _directory = string.Empty;
|
||||
|
||||
[SetUp]
|
||||
public void Prepare()
|
||||
{
|
||||
_directory = Path.Combine(Path.GetTempPath(), $"cultlib-projection-{Guid.NewGuid():N}");
|
||||
Directory.CreateDirectory(_directory);
|
||||
ProjectedRecord.Armed = false;
|
||||
ProjectedRecord.Reads = 0;
|
||||
}
|
||||
|
||||
[TearDown]
|
||||
public void Cleanup()
|
||||
{
|
||||
ProjectedRecord.Armed = false;
|
||||
if (Directory.Exists(_directory))
|
||||
Directory.Delete(_directory, recursive: true);
|
||||
}
|
||||
|
||||
[CultDocument("tests.projected_record", "tests.projected_record.v1")]
|
||||
[MessagePackObject(AllowPrivate = true)]
|
||||
internal sealed class ProjectedRecord
|
||||
{
|
||||
public static long Reads;
|
||||
public static volatile bool Armed;
|
||||
[IgnoreMember] private string _name = string.Empty;
|
||||
[IgnoreMember] private string _code = string.Empty;
|
||||
|
||||
[Key(0)]
|
||||
[CultName]
|
||||
public string Name
|
||||
{
|
||||
get
|
||||
{
|
||||
Interlocked.Increment(ref Reads);
|
||||
if (Armed && _name == "boom")
|
||||
throw new InvalidOperationException("name getter boom");
|
||||
return _name;
|
||||
}
|
||||
set => _name = value;
|
||||
}
|
||||
|
||||
[Key(1)]
|
||||
[CultIndex("code")]
|
||||
public string Code
|
||||
{
|
||||
get
|
||||
{
|
||||
Interlocked.Increment(ref Reads);
|
||||
if (Armed && _code == "boom")
|
||||
throw new InvalidOperationException("index getter boom");
|
||||
return _code;
|
||||
}
|
||||
set => _code = value;
|
||||
}
|
||||
}
|
||||
|
||||
private static readonly CultRecordKey OkKey = new("projected:ok");
|
||||
private static readonly CultRecordKey BoomKey = new("projected:boom");
|
||||
|
||||
private static ProjectedRecord Ok() => new() { Name = "ok", Code = "ok-code" };
|
||||
|
||||
private static ProjectedRecord Boom(bool name) => name ? new ProjectedRecord { Name = "boom", Code = "boom-code" } : new ProjectedRecord { Name = "boom-name", Code = "boom" };
|
||||
|
||||
private string PathOf(string name) => Path.Combine(_directory, name);
|
||||
|
||||
private static CultCache Open(string path) => CultCacheMessagePack.Create(path, new CultCacheOpenOptions { Registry = Registry });
|
||||
|
||||
private static void Put(CultCache cache, ProjectedRecord document, CultRecordKey key) =>
|
||||
cache.Commit(batch => batch.Upsert(typeof(ProjectedRecord), document, key));
|
||||
|
||||
private static long SequenceOf(CultCache cache) => cache.GetWithSequence(OkKey).Sequence;
|
||||
|
||||
private static void StageBoth(CultCacheBatch batch, ProjectedRecord boom)
|
||||
{
|
||||
batch.Upsert(typeof(ProjectedRecord), Ok(), OkKey);
|
||||
batch.Upsert(typeof(ProjectedRecord), boom, BoomKey);
|
||||
}
|
||||
|
||||
[TestCase(true, "[CultName] member Name")]
|
||||
[TestCase(false, "index 'code' member Code")]
|
||||
public void ARefusedGetterMintsNothingAndChangesNothing(bool nameThrows, string member)
|
||||
{
|
||||
using var cache = new CultCache(Registry);
|
||||
var seen = new List<long>();
|
||||
using var watch = cache.Watch<ProjectedRecord>().Subscribe(change => seen.Add(change.Sequence));
|
||||
Put(cache, new ProjectedRecord { Name = "seed", Code = "seed-code" }, new CultRecordKey("projected:seed"));
|
||||
var before = SequenceOf(cache);
|
||||
seen.Clear();
|
||||
ProjectedRecord.Armed = true;
|
||||
|
||||
var refusal = Assert.Throws<InvalidOperationException>(() => cache.Commit(batch => StageBoth(batch, Boom(nameThrows))))!;
|
||||
|
||||
ProjectedRecord.Armed = false;
|
||||
Assert.Multiple(() =>
|
||||
{
|
||||
Assert.That(refusal.Message, Does.Contain(BoomKey.Value).And.Contain(member).And.Contain("getter boom"));
|
||||
Assert.That(SequenceOf(cache), Is.EqualTo(before), "a refused admission mints nothing");
|
||||
Assert.That(cache.Get<ProjectedRecord>(OkKey), Is.Null, "the good record did not land");
|
||||
Assert.That(cache.Get<ProjectedRecord>(BoomKey), Is.Null);
|
||||
Assert.That(cache.GetByName<ProjectedRecord>("ok"), Is.Null, "the name index holds nothing of the refused set");
|
||||
Assert.That(cache.GetByIndex<ProjectedRecord>("code", "ok-code"), Is.Null);
|
||||
Assert.That(seen, Is.Empty, "nothing was published");
|
||||
});
|
||||
|
||||
Put(cache, Ok(), OkKey);
|
||||
Assert.That(SequenceOf(cache), Is.EqualTo(before + 1), "the next write is previous + 1");
|
||||
Assert.That(seen, Is.EqualTo(new[] { before + 1 }));
|
||||
}
|
||||
|
||||
[Test]
|
||||
public void ARefusedSingleWriteMintsNothing()
|
||||
{
|
||||
using var cache = new CultCache(Registry);
|
||||
ProjectedRecord.Armed = true;
|
||||
|
||||
var refusal = Assert.Throws<InvalidOperationException>(() => Put(cache, Boom(true), BoomKey))!;
|
||||
|
||||
ProjectedRecord.Armed = false;
|
||||
Assert.That(refusal.Message, Does.Contain(BoomKey.Value));
|
||||
Assert.That(SequenceOf(cache), Is.EqualTo(0));
|
||||
Assert.That(cache.Get<ProjectedRecord>(BoomKey), Is.Null);
|
||||
}
|
||||
|
||||
[Test]
|
||||
public void ARefusedBatchLeavesAStoreByteIdenticalAndReopensWithNeitherKey()
|
||||
{
|
||||
var path = PathOf("projected.cc");
|
||||
using (var seed = Open(path))
|
||||
Put(seed, new ProjectedRecord { Name = "seed", Code = "seed-code" }, new CultRecordKey("projected:seed"));
|
||||
var before = File.ReadAllBytes(path);
|
||||
|
||||
using (var cache = Open(path))
|
||||
{
|
||||
ProjectedRecord.Armed = true;
|
||||
Assert.Throws<InvalidOperationException>(() => cache.Commit(batch => StageBoth(batch, Boom(true))));
|
||||
ProjectedRecord.Armed = false;
|
||||
Assert.That(File.ReadAllBytes(path), Is.EqualTo(before));
|
||||
}
|
||||
|
||||
using var reopened = Open(path);
|
||||
Assert.Multiple(() =>
|
||||
{
|
||||
Assert.That(reopened.Get<ProjectedRecord>(OkKey), Is.Null);
|
||||
Assert.That(reopened.Get<ProjectedRecord>(BoomKey), Is.Null);
|
||||
Assert.That(File.ReadAllBytes(path), Is.EqualTo(before));
|
||||
});
|
||||
}
|
||||
|
||||
[Test]
|
||||
public void ALoadWhoseGetterThrowsRefusesTheOpenAndLeavesTheFileByteIdentical()
|
||||
{
|
||||
var path = PathOf("poisoned.cc");
|
||||
using (var seed = Open(path))
|
||||
Put(seed, Boom(true), BoomKey);
|
||||
var before = File.ReadAllBytes(path);
|
||||
|
||||
ProjectedRecord.Armed = true;
|
||||
var refusal = Assert.Throws<InvalidOperationException>(() => Open(path))!;
|
||||
ProjectedRecord.Armed = false;
|
||||
|
||||
Assert.That(refusal.Message, Does.Contain(BoomKey.Value).And.Contain("[CultName] member Name"));
|
||||
Assert.That(File.ReadAllBytes(path), Is.EqualTo(before));
|
||||
}
|
||||
|
||||
// A counting getter: each landing record is read once for its name and once for its index, and never again by the
|
||||
// variant rules or the indexer. A variant re-resolved by a base edit lands too, and is read once.
|
||||
[Test]
|
||||
public void EachLandedRecordIsReadOncePerGetterIncludingAVariantDependent()
|
||||
{
|
||||
var codec = CultCacheMessagePack.CreateCodec(Registry);
|
||||
using var cache = new CultCache(Registry, codec);
|
||||
var baseKey = new CultRecordKey("projected:base");
|
||||
Put(cache, new ProjectedRecord { Name = "base", Code = "base-code" }, baseKey);
|
||||
cache.Commit(batch => batch.UpsertVariant(new CultRecordKey("projected:variant"), baseKey, new[]
|
||||
{
|
||||
cache.Override<ProjectedRecord>(nameof(ProjectedRecord.Name), "variant"),
|
||||
cache.Override<ProjectedRecord>(nameof(ProjectedRecord.Code), "variant-code")
|
||||
}));
|
||||
|
||||
// Resolving a variant serializes its base, and the serializer reads the same getters: count those reads apart.
|
||||
ProjectedRecord.Reads = 0;
|
||||
codec.Serialize(new ProjectedRecord(), typeof(ProjectedRecord), typeof(ProjectedRecord));
|
||||
var serializerReads = Interlocked.Read(ref ProjectedRecord.Reads);
|
||||
|
||||
ProjectedRecord.Reads = 0;
|
||||
Put(cache, new ProjectedRecord { Name = "base", Code = "base-code-2" }, baseKey);
|
||||
|
||||
// Two landing records (the base, and the variant re-resolved against it), two getters each, plus the one serialization.
|
||||
Assert.That(Interlocked.Read(ref ProjectedRecord.Reads), Is.EqualTo(4 + serializerReads));
|
||||
Assert.That(cache.GetByIndex<ProjectedRecord>("code", "base-code-2"), Is.Not.Null);
|
||||
Assert.That(cache.GetByName<ProjectedRecord>("variant"), Is.Not.Null);
|
||||
}
|
||||
|
||||
// The index rule counts the holders a commit leaves behind: a record removed by the same commit no longer holds its value.
|
||||
[Test]
|
||||
public void AVariantMayTakeAnIndexedValueFromARecordTheSameCommitRemoves()
|
||||
{
|
||||
using var cache = new CultCache(Registry, CultCacheMessagePack.CreateCodec(Registry));
|
||||
var baseKey = new CultRecordKey("projected:base");
|
||||
var holderKey = new CultRecordKey("projected:holder");
|
||||
Put(cache, new ProjectedRecord { Name = "base", Code = "base-code" }, baseKey);
|
||||
Put(cache, new ProjectedRecord { Name = "holder", Code = "shared" }, holderKey);
|
||||
|
||||
var landed = cache.Commit(batch =>
|
||||
{
|
||||
batch.Remove(holderKey);
|
||||
batch.UpsertVariant(new CultRecordKey("projected:variant"), baseKey, new[]
|
||||
{
|
||||
cache.Override<ProjectedRecord>(nameof(ProjectedRecord.Name), "variant"),
|
||||
cache.Override<ProjectedRecord>(nameof(ProjectedRecord.Code), "shared")
|
||||
});
|
||||
});
|
||||
|
||||
Assert.That(landed, Is.True);
|
||||
Assert.That(cache.GetByIndex<ProjectedRecord>("code", "shared"), Is.Not.Null);
|
||||
Assert.That(cache.Get<ProjectedRecord>(holderKey), Is.Null);
|
||||
}
|
||||
|
||||
// A blank name is no name: a variant and its base that are both blank do not shadow each other.
|
||||
[Test]
|
||||
public void ABlankNameIsNoNameSoBlankVariantAndBaseDoNotCollide()
|
||||
{
|
||||
using var cache = new CultCache(Registry, CultCacheMessagePack.CreateCodec(Registry));
|
||||
var baseKey = new CultRecordKey("projected:base");
|
||||
Put(cache, new ProjectedRecord { Name = "", Code = "base-code" }, baseKey);
|
||||
|
||||
cache.Commit(batch => batch.UpsertVariant(new CultRecordKey("projected:variant"), baseKey, new[]
|
||||
{
|
||||
cache.Override<ProjectedRecord>(nameof(ProjectedRecord.Name), ""),
|
||||
cache.Override<ProjectedRecord>(nameof(ProjectedRecord.Code), "variant-code")
|
||||
}));
|
||||
|
||||
Assert.That(cache.Get<ProjectedRecord>(new CultRecordKey("projected:variant")), Is.Not.Null);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
|
@ -0,0 +1,100 @@
|
|||
#nullable enable
|
||||
using System;
|
||||
using System.Collections.Concurrent;
|
||||
using System.Linq;
|
||||
using System.Threading.Tasks;
|
||||
using GameCult.Caching;
|
||||
using NUnit.Framework;
|
||||
using R3;
|
||||
using static GameCult.Networking.Tests.NetworkingTests;
|
||||
|
||||
namespace GameCult.Networking.Tests
|
||||
{
|
||||
[CultDocument("tests.publication_throwing_name", "tests.publication_throwing_name.v1")]
|
||||
[MessagePack.MessagePackObject]
|
||||
public sealed class PublicationThrowingName
|
||||
{
|
||||
[MessagePack.Key(0)]
|
||||
public string Text { get; set; } = string.Empty;
|
||||
|
||||
[MessagePack.Key(1)]
|
||||
[CultName]
|
||||
public string Name
|
||||
{
|
||||
get => Text == "boom" ? throw new InvalidOperationException("name getter boom") : Text;
|
||||
set { }
|
||||
}
|
||||
}
|
||||
|
||||
// Cache publication cuts 1 and 2 seen through CultNetDatabase: a refused or failing change never stalls the
|
||||
// publication and log of the changes after it. (Soul pass 3 probes P4 and P3.)
|
||||
[NonParallelizable]
|
||||
public sealed class CultCachePublicationIsolationTests
|
||||
{
|
||||
private static NetworkSchemaNote Note(string text) => new() { Schema = "tests.networking_note.v1", Text = text };
|
||||
private static string SchemaId => CultDocumentRegistry.Shared.GetRequired<NetworkSchemaNote>().SchemaId;
|
||||
|
||||
// An admission that a [CultName] getter refuses publishes nothing, leaves nothing in memory, and stalls nothing after it.
|
||||
[Test]
|
||||
public async Task ARefusedAdmissionLeavesNothingAndLaterChangesStillPublishAndLog()
|
||||
{
|
||||
var cache = new CultCache();
|
||||
var database = new CultNetDatabase(cache);
|
||||
var seen = new ConcurrentQueue<string?>();
|
||||
using var watch = database.Watch<NetworkSchemaNote>().Subscribe(change => seen.Enqueue(change.Document?.Text));
|
||||
var okKey = new CultRecordKey("pub:ok");
|
||||
var refusal = Assert.Throws<InvalidOperationException>(() => cache.Commit(batch =>
|
||||
{
|
||||
batch.Upsert(new PublicationThrowingName { Text = "ok" }, new CultRecordHandle<PublicationThrowingName>(okKey));
|
||||
batch.Upsert(new PublicationThrowingName { Text = "boom" }, new CultRecordHandle<PublicationThrowingName>(new CultRecordKey("pub:boomname")));
|
||||
}))!;
|
||||
|
||||
var after = new CultRecordKey("pub:after");
|
||||
await database.PutAsync(after, Note("after"));
|
||||
Assert.Multiple(() =>
|
||||
{
|
||||
Assert.That(refusal.Message, Does.Contain("pub:boomname").And.Contain("name getter boom"));
|
||||
Assert.That(cache.Get<PublicationThrowingName>(okKey), Is.Null, "the good record of a refused batch did not land");
|
||||
Assert.That(seen, Is.EqualTo(new[] { "after" }));
|
||||
Assert.That(database.LastWriteSequence(SchemaId, after), Is.Not.Null, "a later commit was never logged");
|
||||
});
|
||||
}
|
||||
|
||||
// One observer's escaped exception (a fail-fast R3 handler) reaches the writer and does not stall later changes.
|
||||
// A database write is published by the database after its cache write returns, so the failed write itself is not
|
||||
// published here; that ordering belongs to the CultNetDatabase cut.
|
||||
[Test]
|
||||
public async Task AnEscapedObserverExceptionReachesTheWriterAndDoesNotStallLaterChanges()
|
||||
{
|
||||
var previous = ObservableSystem.GetUnhandledExceptionHandler();
|
||||
ObservableSystem.RegisterUnhandledExceptionHandler(exception => throw exception);
|
||||
try
|
||||
{
|
||||
var cache = new CultCache();
|
||||
using var thrower = cache.Watch<NetworkSchemaNote>().Subscribe(change =>
|
||||
{
|
||||
if (change.Document?.Text == "boom") throw new InvalidOperationException("observer boom");
|
||||
});
|
||||
var database = new CultNetDatabase(cache);
|
||||
var seen = new ConcurrentQueue<string?>();
|
||||
using var watch = database.Watch<NetworkSchemaNote>().Subscribe(change => seen.Enqueue(change.Document?.Text));
|
||||
var boom = new CultRecordKey("pub:boom");
|
||||
var escaped = Assert.ThrowsAsync<InvalidOperationException>(() => database.PutAsync(boom, Note("boom")));
|
||||
|
||||
ObservableSystem.RegisterUnhandledExceptionHandler(previous);
|
||||
var after = new CultRecordKey("pub:after");
|
||||
await database.PutAsync(after, Note("after"));
|
||||
Assert.Multiple(() =>
|
||||
{
|
||||
Assert.That(escaped!.Message, Is.EqualTo("observer boom"));
|
||||
Assert.That(seen, Does.Contain("after"), "a later commit was never published");
|
||||
Assert.That(database.LastWriteSequence(SchemaId, after), Is.Not.Null, "a later commit was never logged");
|
||||
});
|
||||
}
|
||||
finally
|
||||
{
|
||||
ObservableSystem.RegisterUnhandledExceptionHandler(previous);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
Loading…
Reference in a new issue