Seal cache transactions and expose coherent generations
This commit is contained in:
parent
e80383c33f
commit
72153a46a2
17 changed files with 185 additions and 21 deletions
|
|
@ -70,6 +70,37 @@ public sealed class DirectoryMessagePackBackingStore : CacheBackingStore
|
|||
/// </summary>
|
||||
public static string DefaultRecordDirectoryPath(string manifestPath) => manifestPath + ".records";
|
||||
|
||||
/// <summary>
|
||||
/// Reads one complete persisted generation without deserializing documents through a
|
||||
/// runtime registry. Indexed manifests are resolved only through the pages they name;
|
||||
/// orphaned pages from older generations are never included.
|
||||
/// </summary>
|
||||
public CultPersistedStoreSnapshot ReadPersistedGeneration()
|
||||
{
|
||||
lock (_mutationGate)
|
||||
using (AcquireCommitLease())
|
||||
{
|
||||
var manifest = ReadManifest();
|
||||
var indexed = string.Equals(manifest.FormatVersion, IndexedFormatVersion, StringComparison.Ordinal) ||
|
||||
string.Equals(manifest.FormatVersion, LegacyMetadataPageFormatVersion, StringComparison.Ordinal) ||
|
||||
string.Equals(manifest.FormatVersion, LegacyIndexedFormatVersion, StringComparison.Ordinal);
|
||||
var records = indexed
|
||||
? manifest.Records
|
||||
.OrderBy(record => record.Key, StringComparer.Ordinal)
|
||||
.Select(record => ReadPersistedRecordPage(record, manifest.FormatVersion, out _))
|
||||
.ToArray()
|
||||
: manifest.Records
|
||||
.OrderBy(record => record.Key, StringComparer.Ordinal)
|
||||
.ToArray();
|
||||
return new CultPersistedStoreSnapshot
|
||||
{
|
||||
FormatVersion = manifest.FormatVersion,
|
||||
SchemaCatalog = manifest.SchemaCatalog.ToArray(),
|
||||
Records = records
|
||||
};
|
||||
}
|
||||
}
|
||||
|
||||
/// <inheritdoc />
|
||||
public override void PullAll()
|
||||
{
|
||||
|
|
@ -496,20 +527,11 @@ public sealed class DirectoryMessagePackBackingStore : CacheBackingStore
|
|||
{
|
||||
var started = tracePages ? Stopwatch.GetTimestamp() : 0L;
|
||||
var metadata = records[index];
|
||||
var path = _manifestUsesImmutablePages
|
||||
? ContentAddressedRecordPath(metadata)
|
||||
: _manifestUsesMetadataPages
|
||||
? MetadataRecordPath(metadata)
|
||||
: LegacyRecordPath(metadata.Key);
|
||||
if (!File.Exists(path))
|
||||
throw new InvalidDataException($"Committed record page '{path}' is missing from the selected manifest generation.");
|
||||
var pagePayload = ReadAllBytesShared(path);
|
||||
if (_manifestUsesImmutablePages &&
|
||||
!HashPayload(pagePayload).SequenceEqual(metadata.Payload))
|
||||
throw new InvalidDataException($"Record page '{path}' does not match its committed content hash.");
|
||||
var record = CultDocumentMessagePackSerialization.DeserializePersistedRecord(pagePayload);
|
||||
if (!string.Equals(record.Key, metadata.Key, StringComparison.Ordinal))
|
||||
throw new InvalidDataException($"Record page '{path}' contains key '{record.Key}', expected '{metadata.Key}'.");
|
||||
var record = ReadPersistedRecordPage(
|
||||
metadata,
|
||||
_manifestUsesImmutablePages,
|
||||
_manifestUsesMetadataPages,
|
||||
out var pagePayload);
|
||||
var catalog = ResolveLegacyUncataloguedRecordCatalog(record, catalogEntries);
|
||||
recordReports[index] = Registry.ResolvePersistedSchemaReport(record.SchemaId, catalog);
|
||||
storedRecords[index] = ToStoredDocument(
|
||||
|
|
@ -797,6 +819,39 @@ public sealed class DirectoryMessagePackBackingStore : CacheBackingStore
|
|||
}
|
||||
}
|
||||
|
||||
private CultPersistedRecord ReadPersistedRecordPage(
|
||||
CultPersistedRecord metadata,
|
||||
string formatVersion,
|
||||
out byte[] pagePayload) =>
|
||||
ReadPersistedRecordPage(
|
||||
metadata,
|
||||
string.Equals(formatVersion, IndexedFormatVersion, StringComparison.Ordinal),
|
||||
string.Equals(formatVersion, LegacyMetadataPageFormatVersion, StringComparison.Ordinal),
|
||||
out pagePayload);
|
||||
|
||||
private CultPersistedRecord ReadPersistedRecordPage(
|
||||
CultPersistedRecord metadata,
|
||||
bool usesContentAddressedPages,
|
||||
bool usesMetadataPages,
|
||||
out byte[] pagePayload)
|
||||
{
|
||||
var path = usesContentAddressedPages
|
||||
? ContentAddressedRecordPath(metadata)
|
||||
: usesMetadataPages
|
||||
? MetadataRecordPath(metadata)
|
||||
: LegacyRecordPath(metadata.Key);
|
||||
if (!File.Exists(path))
|
||||
throw new InvalidDataException($"Committed record page '{path}' is missing from the selected manifest generation.");
|
||||
pagePayload = ReadAllBytesShared(path);
|
||||
if (usesContentAddressedPages &&
|
||||
!HashPayload(pagePayload).SequenceEqual(metadata.Payload))
|
||||
throw new InvalidDataException($"Record page '{path}' does not match its committed content hash.");
|
||||
var record = CultDocumentMessagePackSerialization.DeserializePersistedRecord(pagePayload);
|
||||
if (!string.Equals(record.Key, metadata.Key, StringComparison.Ordinal))
|
||||
throw new InvalidDataException($"Record page '{path}' contains key '{record.Key}', expected '{metadata.Key}'.");
|
||||
return record;
|
||||
}
|
||||
|
||||
private static string HashKey(string key)
|
||||
{
|
||||
using var sha256 = SHA256.Create();
|
||||
|
|
|
|||
|
|
@ -1577,10 +1577,12 @@ namespace GameCult.Caching
|
|||
try
|
||||
{
|
||||
await stageAsync().ConfigureAwait(false);
|
||||
transaction.Seal();
|
||||
changes = CommitTransaction(transaction, soft);
|
||||
}
|
||||
finally
|
||||
{
|
||||
transaction.Seal();
|
||||
_ambientTransaction.Value = null;
|
||||
_transactionGate.Release();
|
||||
}
|
||||
|
|
@ -1904,7 +1906,7 @@ namespace GameCult.Caching
|
|||
CultCacheTransaction transaction,
|
||||
bool soft)
|
||||
{
|
||||
var mutations = transaction.Mutations
|
||||
var mutations = transaction.SnapshotForCommit()
|
||||
.OrderBy(pair => pair.Key, StringComparer.Ordinal)
|
||||
.ToArray();
|
||||
if (mutations.Length == 0)
|
||||
|
|
@ -1978,16 +1980,71 @@ namespace GameCult.Caching
|
|||
|
||||
private sealed class CultCacheTransaction
|
||||
{
|
||||
private readonly object _gate = new();
|
||||
private readonly Dictionary<string, CultStoredDocument?> _mutations = new(StringComparer.Ordinal);
|
||||
private bool _sealed;
|
||||
|
||||
public IReadOnlyDictionary<string, CultStoredDocument?> Mutations => _mutations;
|
||||
public IReadOnlyDictionary<string, CultStoredDocument?> Mutations
|
||||
{
|
||||
get
|
||||
{
|
||||
lock (_gate)
|
||||
{
|
||||
ThrowIfSealedForAmbientAccess();
|
||||
return new Dictionary<string, CultStoredDocument?>(_mutations, StringComparer.Ordinal);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
public void Stage(CultStoredDocument stored) => _mutations[stored.Key.Value] = stored;
|
||||
public void Stage(CultStoredDocument stored)
|
||||
{
|
||||
lock (_gate)
|
||||
{
|
||||
ThrowIfSealedForAmbientAccess();
|
||||
_mutations[stored.Key.Value] = stored;
|
||||
}
|
||||
}
|
||||
|
||||
public void Delete(CultRecordKey key) => _mutations[key.Value] = null;
|
||||
public void Delete(CultRecordKey key)
|
||||
{
|
||||
lock (_gate)
|
||||
{
|
||||
ThrowIfSealedForAmbientAccess();
|
||||
_mutations[key.Value] = null;
|
||||
}
|
||||
}
|
||||
|
||||
public bool TryGet(CultRecordKey key, out CultStoredDocument? stored) =>
|
||||
_mutations.TryGetValue(key.Value, out stored);
|
||||
public bool TryGet(CultRecordKey key, out CultStoredDocument? stored)
|
||||
{
|
||||
lock (_gate)
|
||||
{
|
||||
ThrowIfSealedForAmbientAccess();
|
||||
return _mutations.TryGetValue(key.Value, out stored);
|
||||
}
|
||||
}
|
||||
|
||||
public void Seal()
|
||||
{
|
||||
lock (_gate)
|
||||
_sealed = true;
|
||||
}
|
||||
|
||||
public IReadOnlyDictionary<string, CultStoredDocument?> SnapshotForCommit()
|
||||
{
|
||||
lock (_gate)
|
||||
{
|
||||
if (!_sealed)
|
||||
throw new InvalidOperationException("A CultCache transaction must be sealed before commit.");
|
||||
return new Dictionary<string, CultStoredDocument?>(_mutations, StringComparer.Ordinal);
|
||||
}
|
||||
}
|
||||
|
||||
private void ThrowIfSealedForAmbientAccess()
|
||||
{
|
||||
if (_sealed)
|
||||
throw new InvalidOperationException(
|
||||
"This CultCache transaction has already completed; escaped async work cannot read or mutate it.");
|
||||
}
|
||||
}
|
||||
|
||||
internal CultStoredDocument CreateStoredDocument(Type documentType, object document, CultRecordKey? key = null, string? storedAt = null)
|
||||
|
|
|
|||
|
|
@ -1055,6 +1055,9 @@ namespace GameCult.Caching.Tests
|
|||
var compacted = CultDocumentMessagePackSerialization.DeserializeSnapshot(File.ReadAllBytes(filePath));
|
||||
Assert.That(compacted.SchemaCatalog, Is.Empty);
|
||||
Assert.That(compacted.Records, Is.Empty);
|
||||
var selectedGeneration = store.ReadPersistedGeneration();
|
||||
Assert.That(selectedGeneration.Records, Is.Empty,
|
||||
"a raw generation reader must not resurrect an orphaned page left by another process");
|
||||
}
|
||||
finally
|
||||
{
|
||||
|
|
@ -1432,6 +1435,55 @@ namespace GameCult.Caching.Tests
|
|||
}
|
||||
}
|
||||
|
||||
[Test]
|
||||
public async Task CultCache_Transaction_Rejects_Escaped_Async_Writes_After_Commit()
|
||||
{
|
||||
var root = Path.Combine(Path.GetTempPath(), $"cultcache-escaped-transaction-{Guid.NewGuid():N}");
|
||||
var manifest = Path.Combine(root, "state.cc");
|
||||
Directory.CreateDirectory(root);
|
||||
try
|
||||
{
|
||||
using var cache = new CultCache();
|
||||
cache.AddBackingStore(new DirectoryMessagePackBackingStore(manifest));
|
||||
var committedKey = new CultRecordKey("transaction:committed-parent");
|
||||
var escapedKey = new CultRecordKey("transaction:escaped-child");
|
||||
var releaseChild = new TaskCompletionSource<bool>(TaskCreationOptions.RunContinuationsAsynchronously);
|
||||
Task? escapedWrite = null;
|
||||
|
||||
await cache.ExecuteTransactionAsync(async () =>
|
||||
{
|
||||
await cache.UpsertAsync(
|
||||
new NamedTestEntry { Name = "parent", Value = "committed" },
|
||||
new CultRecordHandle<NamedTestEntry>(committedKey));
|
||||
escapedWrite = Task.Run(async () =>
|
||||
{
|
||||
await releaseChild.Task;
|
||||
await cache.UpsertAsync(
|
||||
new NamedTestEntry { Name = "child", Value = "must-fail" },
|
||||
new CultRecordHandle<NamedTestEntry>(escapedKey));
|
||||
});
|
||||
});
|
||||
|
||||
releaseChild.SetResult(true);
|
||||
Assert.That(escapedWrite, Is.Not.Null);
|
||||
Assert.That(
|
||||
async () => await escapedWrite!,
|
||||
Throws.TypeOf<InvalidOperationException>().With.Message.Contains("already completed"));
|
||||
Assert.That(cache.Get<NamedTestEntry>(committedKey)?.Value, Is.EqualTo("committed"));
|
||||
Assert.That(cache.Get<NamedTestEntry>(escapedKey), Is.Null);
|
||||
|
||||
using var reopened = new CultCache();
|
||||
reopened.AddBackingStore(new DirectoryMessagePackBackingStore(manifest));
|
||||
await reopened.PullAllBackingStoresAsync();
|
||||
Assert.That(reopened.Get<NamedTestEntry>(committedKey)?.Value, Is.EqualTo("committed"));
|
||||
Assert.That(reopened.Get<NamedTestEntry>(escapedKey), Is.Null);
|
||||
}
|
||||
finally
|
||||
{
|
||||
if (Directory.Exists(root)) Directory.Delete(root, recursive: true);
|
||||
}
|
||||
}
|
||||
|
||||
[Test]
|
||||
public async Task CultCache_Transaction_Observer_Writes_In_A_New_Commit()
|
||||
{
|
||||
|
|
|
|||
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
|
|
@ -1,7 +1,7 @@
|
|||
{
|
||||
"name": "org.gamecult.cultlib",
|
||||
"displayName": "CultLib",
|
||||
"version": "1.0.54",
|
||||
"version": "1.0.55",
|
||||
"unity": "2021.3",
|
||||
"description": "CultCache, CultNet, and CultMesh managed runtime assemblies for Unity.",
|
||||
"license": "MIT",
|
||||
|
|
|
|||
Loading…
Reference in a new issue