Merge remote-tracking branch 'origin/main' into hands/cultmath-snoise-grad
This commit is contained in:
commit
468915b058
99 changed files with 8066 additions and 130 deletions
189
contracts/cultmesh/content-vectors.cs-written.json
Normal file
189
contracts/cultmesh/content-vectors.cs-written.json
Normal file
File diff suppressed because one or more lines are too long
159
contracts/cultmesh/content-vectors.rs-written.json
Normal file
159
contracts/cultmesh/content-vectors.rs-written.json
Normal file
File diff suppressed because one or more lines are too long
|
|
@ -28,7 +28,7 @@
|
|||
"code": {
|
||||
"description": "Machine-readable refusal code (R-N). Additive: a v0 peer that does not know this field ignores it.",
|
||||
"type": ["string", "null"],
|
||||
"enum": [null, "selection_invalid", "cursor_stale", "cursor_invalid", "reference_outside_target"]
|
||||
"enum": [null, "selection_invalid", "cursor_stale", "cursor_invalid", "reference_outside_target", "variant_unsupported"]
|
||||
},
|
||||
"details": {
|
||||
"description": "Code-specific structured detail (R-N). Every field is populated only for the code that defines it; the others are null, not omitted.",
|
||||
|
|
@ -36,8 +36,8 @@
|
|||
"additionalProperties": false,
|
||||
"required": ["field", "value", "asOf", "current"],
|
||||
"properties": {
|
||||
"field": { "description": "selection_invalid: the selection field that failed.", "type": ["string", "null"] },
|
||||
"value": { "description": "selection_invalid: the offending value, when there is one string worth naming.", "type": ["string", "null"] },
|
||||
"field": { "description": "selection_invalid: the selection field that failed. variant_unsupported: \"subscriptionId\", when a subscription was ended.", "type": ["string", "null"] },
|
||||
"value": { "description": "selection_invalid: the offending value, when there is one string worth naming. variant_unsupported: the id of the subscription that ended.", "type": ["string", "null"] },
|
||||
"asOf": { "description": "cursor_stale: the cursor's own minted asOf.", "type": ["integer", "null"], "minimum": 0 },
|
||||
"current": { "description": "cursor_stale: the answering server's current asOf.", "type": ["integer", "null"], "minimum": 0 }
|
||||
}
|
||||
|
|
|
|||
436
docs/document-variants-cut.md
Normal file
436
docs/document-variants-cut.md
Normal file
|
|
@ -0,0 +1,436 @@
|
|||
# CultCache document variants: cut map (draft)
|
||||
|
||||
Date 2026-09-29. Imagination output for `docs/document-variants-target.md` (branch
|
||||
`codex/document-variants`). Body read at `origin/main` `268e0ef`. This map owns means only;
|
||||
the target owns ends and rulings 1-7. Nothing here is decided that the batch in section 4
|
||||
asks the operator to decide.
|
||||
|
||||
## 1. Probe facts (run, not inferred)
|
||||
|
||||
Probe: scratch clone `scratchpad/variant-probe` (commit `7b6de8e`, probe files only), run on
|
||||
Yggdrasil via `ygg-verify.sh` with images `dotnet`, `rust`, `python:3.12-slim`, `node:22`.
|
||||
Each runtime's current reader wrote a normal store, the bytes were altered four ways, and
|
||||
the store was reopened. Output in `scratchpad/probe-out/*.txt`.
|
||||
|
||||
| Altered store | C# | Python | TypeScript | Rust |
|
||||
| --- | --- | --- | --- | --- |
|
||||
| A. v1 header, record gains slot 4, payload empty | refuses, "read past end of stream" | refuses, "incomplete input" | refuses, "Offset outside DataView" | refuses (strict tuple), misleading legacy-envelope message |
|
||||
| B. v1, slot 4 plus a full payload | **loads the payload silently** | **loads silently** | **loads silently** | refuses |
|
||||
| C. header `cultcache.store.v2` | **ignores the header**; refused only by the empty payload | refuses, misleading "legacy envelopes" message | refuses | refuses |
|
||||
| D. payload holds the delta as a sparse array | **loads `Name=''`, `Max=99`** | **loads `name=None`** | refuses | loads; `get` of that key fails |
|
||||
|
||||
Consequences:
|
||||
- The **empty payload is the only tripwire every shipped reader trips**, pinned builds
|
||||
included (Aetheria pins `caching-unity-v1.4.0`). A variant record's payload must be empty,
|
||||
and the delta must live outside it.
|
||||
- A payload-as-delta encoding is ruled out: C# and Python misread it silently.
|
||||
- C# never checks `formatVersion` (`CultDocumentMessagePackSerialization.DeserializeSnapshot`
|
||||
defaults a missing one to v1). C#, Python and TypeScript skip extra record slots silently.
|
||||
These are latent defects today and become misreads when the format grows.
|
||||
- Every refusal is loud but none of them names the record. The target requires named refusals,
|
||||
so current readers need a small fix (C0).
|
||||
|
||||
Other Body facts that shape the map:
|
||||
- **CultNet has no member-path grammar.** `docs/cultnet-selection-cut.md` D2: "Declared
|
||||
aliases, not a field-path language". It reaches top-level declared `index`/`role` aliases
|
||||
only (`CultDocumentMemberView`). Nothing exists to reuse. See section 3.
|
||||
- **The schema catalog describes top-level members only.** A nested type (`BehaviorData`,
|
||||
`PerformanceStat`, `HardpointData`) appears only as a CLR type name. Soft drift and hard
|
||||
rejection cannot see below slot level.
|
||||
- **Resolution needs a codec, and the core has none.** `GameCult.Caching` holds objects. The
|
||||
MessagePack codec lives in `GameCult.Caching.MessagePack`. `CultInspectorModel` already
|
||||
takes the codec as two injected functions (`CultCacheMessagePack.CreateInspectorModel`).
|
||||
- **Same concrete type implies same home store.** `Home(type)` routes by type, so ruling 3
|
||||
("same store") falls out of ruling 6. No separate check is needed.
|
||||
- **The name index shadows silently.** `Index()` does `MapOf(_names, type)[name] = key`, so a
|
||||
second record with the same name overwrites the entry. A variant that inherits its base's
|
||||
name would make `GetByName` return one of the two, depending on apply order.
|
||||
- **Studio edits by whole-document upsert.** `CultInspectorEdit.Commit` calls
|
||||
`UpsertAsync(type, copy, key)`, and `Duplicate` clones through the codec.
|
||||
- **Raw readers bypass the cache.** In CultLib: `CultMesh.ReadSingleFileDocument`
|
||||
(`CultMeshSingleFileDocuments.cs:112`), plus its legacy snapshot decoder. In consumers:
|
||||
AetheriaEve `AetheriaRuntimeCatalogStore` (directory-store pages).
|
||||
- **Kotlin reads no store files.** It sees CultNet raw snapshots only.
|
||||
|
||||
## 2. Model page (step 0b)
|
||||
|
||||
| Kind | Named by | Over time | Decided by |
|
||||
| --- | --- | --- | --- |
|
||||
| Variant record | its own `CultRecordKey`, minted like any record; same `schemaId` as its type | created, re-overridden, rebased, removed; never converted to or from a plain record implicitly (Q1) | author through Studio or the variant write API; the cache validates |
|
||||
| Base reference | the base's key, in the record's variant slot | changed only by an explicit rebase; a base cannot be deleted while it has variants, unless the same batch rebases or removes them | author; the cache refuses a cycle, a missing base, a different concrete type, a global type |
|
||||
| Override entry | `(op, path, id, value)`; op is Set, Insert or Remove | added by editing; removed by clearing; survives base edits while its path resolves | author; the cache refuses entries a base edit strands (Q2); an entry whose member left the type soft-drifts with a warning (Q4 c) |
|
||||
| Member path | a sequence of `(slot, elementId)` steps; `slot` is the MessagePack `[Key]`; `elementId` is `""` unless the step enters an object-list element | a type change can invalidate it | the type's owner (slot authority); ids by the element's creator |
|
||||
| Element id | a `[CultElementId]` string member on an object-list element type; `""` means unset | minted by the cache on write when unset; copied unchanged into variants; a moved element is a new element | cache mints it; it is never retargeted |
|
||||
| Resolved view | `CultStoredDocument.Document` for a variant key | recomputed inside the hold that admits the variant, or any base on its chain | the cache only; never persisted, never written back (Q1) |
|
||||
| Index and name entries | as today, from the resolved view | a dependent's entries are dropped and re-added in the same `Apply` as its base change | the cache; a variant must override the `[CultName]` member (rule R6) |
|
||||
| Watches | as today; each re-resolved dependent emits `Updated` with its own `Sequence` | published in the same hold as the base change | the cache |
|
||||
| Compare-exchange | `(schemaId, storedAt)` of the stored delta (ruling 2) | a base change does not stamp its variants | the cache; the resolved view is not an identity |
|
||||
| Persisted format version | store header `formatVersion` | `cultcache.store.v2` when the store holds at least one variant; `v1` otherwise (Q5) | the writing store, from content |
|
||||
| Variant slot on the wire (CultNet) | **empty cell**: no CultNet message carries a delta today | C5 | ruling 4 decides deltas; the message shape is C5's design |
|
||||
| Dictionary entries, scalar lists, arrays | **empty cell**: no stable identity exists | whole-member Set only (Q7) | Q7 |
|
||||
| Template (non-item) bases | **empty cell**: parked by ruling 6 | none | not in these cuts |
|
||||
|
||||
## 3. Where the Body contradicts the target
|
||||
|
||||
1. **"A member path in CultNet's grammar"** (ruling 1 and fork 1 text) has nothing to reuse.
|
||||
CultNet selection deliberately has no path language. This map specifies a minimal slot
|
||||
path (section 2) owned by `GameCult.Caching`. If CultNet ever needs paths, it can adopt
|
||||
this one. Nothing is shared today, and nothing is invented twice.
|
||||
2. **"Overrides are subject to the same soft drift rules as full records"** conflicts with
|
||||
the ends list: "Loading refuses an override naming a member that does not exist on the
|
||||
type". Under soft drift, a persisted slot missing locally is ignored with a warning, so
|
||||
the two rules disagree for a dropped member. Below top level, the catalog has no shape to
|
||||
drift against at all. See Q4.
|
||||
3. **"Deletes first"** has little to delete: the feature is additive. The honest deletions
|
||||
are the silent extra-slot skips and C#'s ignored header. C0 puts them first.
|
||||
|
||||
## 4. Operator questions (one batch)
|
||||
|
||||
**Operator rulings, 2026-09-29, each asked on its own:**
|
||||
|
||||
- **Q1: (a)**, a plain `Upsert` at a variant's key is refused loudly.
|
||||
- **Q2: (a)**, a base edit removing an overridden element is refused unless the same batch
|
||||
resolves it. Operator's reading: "the very existence of that element in the child collection
|
||||
must become the new override state... you can't change the parent without also changing the
|
||||
child... that's the resolve part of (a)."
|
||||
- **Q3: ids everywhere, not opt-in.** Operator: "Opt-in sounds nice but consider the UX. We're
|
||||
planting a footgun if we don't require ids everywhere." Rollout: **required, minted on load**.
|
||||
The C# registry requires an id member on object-list element types. A store written before ids
|
||||
existed loads, and ids are minted once on its first write (C2's rewrite). Other runtimes carry
|
||||
the id as an ordinary member and enforce the rule when they gain variants. Each consumer's type
|
||||
edit is a sweep in its own repo after C2.
|
||||
- **Q4: (c) soft drift everywhere. This reverses the recommendation and supersedes the target's
|
||||
end "loading refuses ... an override naming a member that does not exist on the type".**
|
||||
Operator: "Soft drift everywhere aligns with the vision... the rationale for adopting
|
||||
migrationless changes is still valid for variants. Any member dropped in a type change is a
|
||||
design change, the reason for it to apply to the parent also applies to the variant." A
|
||||
dangling override, at any depth, is ignored with a warning naming the variant and the member,
|
||||
and the variant inherits the base value. The other broken-variant refusals (a base cycle, a
|
||||
missing base, an incompatible base type) stand.
|
||||
- **Q5: (a)**, the v2 header is written only when the store holds a variant.
|
||||
- **Q6: yes**, the directory store and CultNet refuse variants loudly until their own cuts.
|
||||
- **Q7: yes**, object-list elements are addressable by id, and dictionaries, scalar lists and
|
||||
arrays are replaced whole. The operator asked first whether design roles and quality levels
|
||||
use dictionaries. They do not: `CraftedItemData.Roles` is a `List<ItemRole>` and
|
||||
`FactionProduct.Roles` is a `List<ProductRole>` (Aetheria `ItemData.cs:316`,
|
||||
`FactionProduct.cs:30`). A market-segment product becomes a variant overriding one
|
||||
`ProductRole` by id.
|
||||
|
||||
*The questions as asked:*
|
||||
|
||||
**Q1. A plain `Upsert` of a whole document at a variant's key.** It happens when Studio's
|
||||
current edit commits, when AetherDb migrations do `batch.Upsert(type, doc, key)`, and on a
|
||||
CultNet remote write.
|
||||
- (a) Refuse it loudly. A variant changes only through the variant API. Flattening is an
|
||||
explicit, separate operation.
|
||||
- (b) Diff the document against the base and store the difference. Ids make the diff
|
||||
deterministic, but a value set equal to the base stops being an override without anyone
|
||||
saying so.
|
||||
- (c) Flatten silently (today's behaviour by default).
|
||||
- **Recommend (a).** Affects C1's write path, C3's edit commit, and every AetherDb migration
|
||||
(each skips variants or uses the variant API).
|
||||
|
||||
**Q2. A base edit that removes an element some variant overrides.**
|
||||
- (a) Refuse the commit unless the same batch clears or retargets those overrides. Studio
|
||||
offers keep, retarget or clear at edit time, and "keep" means the base edit is not
|
||||
committed. The store never holds a conflict, and loading refuses one.
|
||||
- (b) Persist the conflict. The override goes inert, readers get the resolved document
|
||||
without it, and Studio lists it.
|
||||
- **Recommend (a).** Option (b) makes a reader's resolved document silently differ from what
|
||||
the author wrote. Affects C2's validation, C3's rebase UI, and migrations that remove
|
||||
behaviours.
|
||||
|
||||
**Q3. Scope of "ids everywhere".**
|
||||
- (a) Every object-list element in every registered document type, in all 28 consumers. The
|
||||
registry refuses a type whose element types lack an id.
|
||||
- (b) Only document types that opt in with `[CultVariants]`. For those, the registry requires
|
||||
`[CultElementId]` on every object element type reachable through their lists, including
|
||||
union bases.
|
||||
- **Recommend (b).** Option (a) breaks 28 registries for a feature that one consumer uses.
|
||||
Affects C2 and Aetheria's adoption cut. A `BehaviorData` id needs a base slot above the
|
||||
subclasses' highest key (32), which adds about 30 nil bytes per behaviour unless Aetheria
|
||||
renumbers.
|
||||
|
||||
**Q4. Schema drift under overrides** (contradiction 2).
|
||||
- (a) Refuse loading when an override names a member missing at any depth, or holds a value
|
||||
that will not decode into the member's current type. Record this as a stated exception to
|
||||
soft drift in `cultcache-schema-compatibility.md`.
|
||||
- (b) Top-level overrides follow catalog soft drift (ignore with a warning); nested ones are
|
||||
refused.
|
||||
- **Recommend (a).** It follows the target's ends and is one rule. The cost: after a type
|
||||
change drops an overridden member, the catalog must be rewritten before the new build opens
|
||||
it.
|
||||
|
||||
**Q5. Format version.**
|
||||
- (a) Write `cultcache.store.v2` only when the store holds a variant. Stores without variants
|
||||
stay byte-identical `v1` for every consumer.
|
||||
- (b) Always write v2 after the upgrade.
|
||||
- **Recommend (a).** The empty payload remains the tripwire for pinned old C#, which ignores
|
||||
the header. Affects C0 and C1.
|
||||
|
||||
**Q6. Slice scope.** Should the directory store and CultNet refuse variants loudly until
|
||||
their own cuts? The directory store's only consumer is AetheriaEve's raw reader. CultNet
|
||||
must carry deltas (ruling 4), and no message can yet.
|
||||
- **Recommend yes.** It is two refusals. Otherwise C1 must design CultNet messages first.
|
||||
Affects C1's size and the order of C5.
|
||||
|
||||
**Q7. What is addressable below a member.** The proposal: object-list elements by id only.
|
||||
Dictionary entries, scalar lists and arrays are replaced whole.
|
||||
- **Recommend yes.** Aetheria's cases (`Hardpoints` whole; `Behaviors[id]...Max`) fit. Keyed
|
||||
dictionary addressing can be added later without a format change. Affects C2.
|
||||
|
||||
## 5. Cuts, in order
|
||||
|
||||
All cuts are in `F:\Projects\CultLib`. Rebase `codex/document-variants` (docs only) onto
|
||||
`origin/main`. Each cut is one Hands pass on that branch and merges to main after its Soul
|
||||
pass. Probes show that a C1 writer can merge safely before other runtimes change, because
|
||||
every reader refuses it. Verification uses `ygg-verify.sh /f/Projects/CultLib <rev> <image> '<cmd>'`.
|
||||
The command strings below are the `<cmd>`. Keep the job's exit status last.
|
||||
|
||||
Overlap: BP-1 (`cultmesh/rust-content-plane`) edits `docs/runtime-parity-scope.md`, which
|
||||
C0 also edits. Rebase after BP-1 merges. `codex/fix-node24-ajv-esm` has no diff against main.
|
||||
|
||||
### C0. Tripwires: every reader refuses what C1 will write, and names the record
|
||||
|
||||
Deletes:
|
||||
- The silent extra-slot skip in the C# record decoder
|
||||
(`CultDocumentMessagePackSerialization.ReadPersistedRecord`'s trailing `Skip` loop) and
|
||||
its copy in `CultMeshSingleFileDocuments.ReadLegacyPersistedRecord`.
|
||||
- The `?? "cultcache.store.v1"` defaulting of the header.
|
||||
- Python `raw_record[:4]` slicing.
|
||||
- The TypeScript and Python fallthrough to the legacy envelope decoder when the header is a
|
||||
`cultcache.store.*` string they do not know.
|
||||
|
||||
Adds, one rule in each runtime: a snapshot whose header is not `v1`, or whose record has more
|
||||
than 4 slots, is refused with a message that names the version or the record key, and says
|
||||
the store needs a runtime that resolves variants. C# accepts `v1` only, until C1 adds `v2`.
|
||||
|
||||
Keeps: every v1 byte and every v1 test.
|
||||
|
||||
Verification (rule: "unknown header or extra record slot is refused by name"). Each runtime
|
||||
gets one test, and each test's negative is fixture B from section 1 (full payload plus slot
|
||||
4) loading:
|
||||
- `dotnet`: `dotnet test tests/GameCult.Caching.Tests --filter FullyQualifiedName~PreCut2StoreFormat`
|
||||
- `node:22`: `npm install --no-audit --no-fund && cd packages/cultcache-ts && npm test`
|
||||
- `python:3.12-slim`: `pip install -q msgpack -e packages/cultcache-py && python -m unittest discover packages/cultcache-py/tests`
|
||||
- `rust`: `cd packages/cultcache-rs && cargo test` (message only; Rust already refuses)
|
||||
|
||||
Subtraction: about −20 lines of skip and fallthrough; +4 small refusals and 4 tests. Build:
|
||||
the 4 cache packages only.
|
||||
|
||||
### C1. C# core: variant records, top-level Set overrides, resolution in the admitting hold
|
||||
|
||||
Adds:
|
||||
- **`CultPersistedRecord.Variant`**, record slot 4: `[baseKey, overrides[]]`. Payload slot 3
|
||||
is empty for a variant. An override is `[op, path[], id, value]`.
|
||||
- Owner: `GameCult.Caching`.
|
||||
- Consumer: both file stores and Studio.
|
||||
- Invariant: an old reader refuses rather than misreads (section 1).
|
||||
- Why no existing owner serves: the payload cannot hold the delta (probe D).
|
||||
- **`CultStoredDocument.Variant`** (base key and overrides; null for plain records).
|
||||
`Document` stays the resolved view.
|
||||
- **A codec port on `CultCache`**: the `(serialize, deserialize)` pair `CultInspectorModel`
|
||||
already takes, lifted.
|
||||
- Owner: `GameCult.Caching.MessagePack`, supplied by `CultCacheMessagePack.Create`.
|
||||
- Consumers: resolution and the inspector model.
|
||||
- Invariant: one codec per cache; clones and override values use the store's encoding.
|
||||
- `CultInspectorModel`'s constructor takes the port instead of its own pair, so there is one
|
||||
pair, not two.
|
||||
- A cache without a codec refuses variant writes.
|
||||
- **Write API** on `CultCacheBatch`, with single-call equivalents: `UpsertVariant(key, baseKey,
|
||||
overrides)`, `Flatten(key)` (Q1a), `Remove` unchanged. Rebase is `UpsertVariant` with a new
|
||||
base.
|
||||
- **`Validate` resolves** every admitted variant and every dependent of an admitted or
|
||||
evicted base, in base-first order, against the post-batch set. It refuses, naming keys:
|
||||
a cycle; a missing base; a different concrete type; a global type; an evicted base with
|
||||
surviving variants; a variant whose resolved `[CultName]` equals its base's (R6); a plain
|
||||
`Upsert` at a variant key (Q1a). **Not refused (Q4 c, operator 2026-09-29):** an override
|
||||
naming a slot the type no longer has, or holding a value that no longer decodes into the
|
||||
member's type, soft-drifts exactly as the same member would on a plain record under
|
||||
`cultcache-schema-compatibility.md`. It is ignored with a warning naming the variant and
|
||||
the member, and the variant inherits the base value. One rule, the existing soft-drift
|
||||
path, never a variant-specific one.
|
||||
- **`Apply` re-resolves dependents** in the same hold. Each emits `Updated` and is re-indexed.
|
||||
A base change stamps no dependent `storedAt`.
|
||||
- **Header**: the store writes `v2` iff it holds a variant (Q5a) and reads `v1` and `v2`.
|
||||
- **Refusals** (Q6): `DirectoryMessagePackBackingStore` push and commit of a variant;
|
||||
`CultNetDocumentRegistry` row building for a variant; `CultMesh.ReadSingleFileDocument` of
|
||||
a variant key.
|
||||
- **Contracts**: the variant record section in `cultcache-persistence-format.md`; one
|
||||
sentence in `cultcache-schema-compatibility.md` saying overrides soft-drift like members
|
||||
(Q4 c, no exception); a "variants: C# resolves; others refuse" row in
|
||||
`runtime-parity-scope.md`.
|
||||
|
||||
Authority map:
|
||||
- Owner: `CultCache.Validate`/`Apply` owns the resolved view.
|
||||
- Inputs: stored deltas, base records, the codec.
|
||||
- Outputs: the resolved `Document`, index entries, changes.
|
||||
- Demoted: the resolved `Document` is no longer a writable owner for a variant key (Q1a).
|
||||
`storedAt` is the delta's identity only.
|
||||
- Forbidden writers: store `Loaded` callbacks never resolve; Studio never writes a resolved
|
||||
document to a variant key; CultNet never emits a variant row.
|
||||
- Shared paths: a load (`Admit` with a source), a single write, a batch and a remove all pass
|
||||
the same `Validate` and `Apply`. There is no second resolution path.
|
||||
|
||||
Verification. New `VariantTests.cs`; each rule gets a positive and a named negative:
|
||||
- a load with a variant resolves;
|
||||
- a base edit updates the variant's `Get`, `GetByName` and `GetByIndex`, and `Watch` sees both
|
||||
changes inside one publication, with no gap in `Sequence` between them. Negative: a
|
||||
subscriber observing the base change must already read the new variant.
|
||||
- `Expect` on the variant survives a base change;
|
||||
- each refusal case, and the refusal message names both keys;
|
||||
- the header is `v1` without variants and `v2` with them;
|
||||
- a read-only store resolves;
|
||||
- a variant round-trips byte-identically through flush.
|
||||
|
||||
Cross-runtime vectors: the Caching interop peer gains `write-variant --file`. A test in
|
||||
`packages/cultcache-ts/test/cult-cache.test.ts` asserts that TypeScript refuses that file by
|
||||
name; Python and Rust tests read the same fixture from `contracts/cultcache/variant-store.cc`.
|
||||
|
||||
Command, `dotnet`:
|
||||
`dotnet test tests/GameCult.Caching.Tests && dotnet test tests/GameCult.Networking.Tests --filter FullyQualifiedName~Registry`,
|
||||
then the C0 commands for `node:22`, `python` and `rust` against the new fixture.
|
||||
|
||||
Subtraction: the inspector's own codec pair collapses into the port; otherwise net additive,
|
||||
estimated +350 to 450 lines of core and +400 of tests. Build: the Caching and MessagePack
|
||||
projects, Caching.Tests, the Networking test filter, the interop peer.
|
||||
|
||||
**C1 status, 2026-09-29 (Self).** C1 landed on `hands/variants-c1` (`136adce`). Soul (Opus) found it
|
||||
not closeable, and a fix batch is in Hands:
|
||||
- **F1:** CultNet's live-change paths leak variants as plain records, which breaks Q6.
|
||||
- **F3:** an undecodable override soft-drifted where a plain record refuses to load.
|
||||
- **F4:** invalid overrides were accepted at write.
|
||||
- **F2:** an inherited unique index value shadows the base, and the winner depends on order.
|
||||
|
||||
**Self's readings and defaults, not new operator rulings:**
|
||||
- **Q4 (c) read literally:** an override follows the plain-record outcome. A missing slot
|
||||
soft-drifts; a value that no longer decodes refuses loudly, as a plain record does.
|
||||
- **Invalid overrides are refused at write.** Drift covers type changes after the fact, not
|
||||
bad writes.
|
||||
- **F2 extends R6 to indexes.** A commit that leaves a variant sharing an indexed value
|
||||
with another record is refused.
|
||||
- **One override per slot.**
|
||||
|
||||
**Open for the operator:** plain records with duplicate unique-index values are silently
|
||||
overwritten today. That predates variants. Fixing it could refuse existing stores.
|
||||
|
||||
### C2. C# element identity and nested paths (Set, Insert, Remove)
|
||||
|
||||
Adds:
|
||||
- **`[CultElementId]`** (a string member). **Ids everywhere, not opt-in (Q3, operator
|
||||
2026-09-29): there is no `[CultVariants]` attribute.** The C# registry requires an id member
|
||||
on every object element type reachable through a list in any registered document type,
|
||||
union bases included, and refuses a type that lacks one.
|
||||
- **Minting**: on write, the cache mints ids for unset ids in every type, and refuses a
|
||||
duplicate id within one list. A store written before ids existed loads, and its ids are
|
||||
minted on its first write (minted on load, per the operator's rollout ruling).
|
||||
- **Path steps below top level.**
|
||||
- **Insert** anchored after an id, where `""` means the head. An inserted run sits
|
||||
immediately after its anchor and before base elements added there later.
|
||||
- **Remove** by id.
|
||||
- **Canonical order**: removes, then inserts in list order, then sets by path.
|
||||
- **Q2a refusal**: a base commit that orphans an override is refused.
|
||||
- **Q7**: whole-member Set for dictionaries, scalar lists and arrays.
|
||||
- **`CultCache.MintElementIds()`**: the one-shot rewrite for existing stores (ruling 1). It
|
||||
upserts every record that has an unset id through the normal path.
|
||||
- **The consumer sweep (Q3 rollout).** About 28 consumers carry list-element types, and each
|
||||
needs an id member before it can take the CultLib that requires one. C2 ships the
|
||||
requirement. Self schedules the per-repo sweep, one small type edit per consumer, before
|
||||
those consumers bump. C2 lists the element types it finds per consumer, as data for that
|
||||
sweep.
|
||||
|
||||
Keeps: the C1 format unchanged. C2 fills path shapes that C1 refused.
|
||||
|
||||
Verification:
|
||||
- Two look-alike elements (two of one union subtype) get different overrides, and a base
|
||||
insert before them retargets nothing.
|
||||
- Rebase re-applies overrides by id. A missing id is refused, and the message names the
|
||||
variant, path and id.
|
||||
- A Set on a removed element is refused.
|
||||
- Minting is idempotent.
|
||||
- A registered type with an id-less list element type is refused, naming the type and member.
|
||||
- A store written before ids loads, and its ids are minted exactly once on first write
|
||||
(idempotent).
|
||||
- A C#-written nested-override fixture joins `contracts/cultcache/`.
|
||||
|
||||
Command: `dotnet test tests/GameCult.Caching.Tests`.
|
||||
|
||||
Estimate +300 lines and +350 of tests. Build: as C1, without Networking.
|
||||
|
||||
### C3. Studio: edit the delta
|
||||
|
||||
Adds, in `CultInspectorModel` (engine-free; the lowering stays a renderer):
|
||||
- For a variant edit, each member path is marked inherited or overridden.
|
||||
- `Commit` writes `UpsertVariant` with overrides equal to the prior overrides plus a
|
||||
structural diff by id. It is deterministic because ids exist.
|
||||
- An explicit "override" pins a value equal to its base's.
|
||||
- `ClearOverride(path)`.
|
||||
- `CreateVariant(record)` next to `Duplicate`; it prompts for a name (R6).
|
||||
- `Rebase(record, base)` returns a conflict list for Q2a before commit.
|
||||
|
||||
Lowering, in `CultCacheStudioWindow`/`Drawers`: an overridden marker and a revert control per
|
||||
member, a base link, and variant creation and rebase controls.
|
||||
|
||||
Verification:
|
||||
- `CultInspectorModelTests`: the diff produces exactly the touched paths; clear removes one
|
||||
entry; the pin survives an equal value; rebase conflicts are listed.
|
||||
- Negative: a Studio commit never calls a plain `Upsert` at a variant key.
|
||||
|
||||
Only the operator can check these in Unity against a copy of `Aetheria.cc`:
|
||||
- the markers read correctly;
|
||||
- clearing reverts the value live;
|
||||
- a hull variant replaces `Hardpoints`;
|
||||
- a laser variant changes one behaviour's `PerformanceStat.Max`;
|
||||
- a base edit shows in the open variant.
|
||||
|
||||
Then tag `caching-unity-v1.5.0`. **This is the point where Aetheria is unblocked.**
|
||||
|
||||
Estimate +250 model, +150 lowering, +250 tests. Build: Caching.Tests. The Unity package is
|
||||
checked by the operator in the editor.
|
||||
|
||||
### C4. Aetheria adoption (Aetheria repo, its own cut, after the release)
|
||||
|
||||
- Bump the package to `v1.5.0`.
|
||||
- Add `[CultElementId]` to every list-element type Aetheria's documents carry (ids everywhere, Q3). There is no per-type opt-in.
|
||||
- Add `[CultElementId]` to `BehaviorData` (base) and `HardpointData`.
|
||||
- Run `MintElementIds` once over `GameData/Aetheria.cc`.
|
||||
- AetherDb migrations skip variants or use the variant API (Q1a).
|
||||
- Re-author the families listed in section 6.
|
||||
|
||||
### C5. CultNet deltas (C# reference)
|
||||
|
||||
Adds a new raw-record message version that carries the variant slot, following selection D3:
|
||||
a v1 message string, so peers not in this cut refuse through their own dispatch. The C1
|
||||
refusal in `CultNetDocumentRegistry` is deleted. Scheduled when a CultNet consumer needs
|
||||
variants; none does today.
|
||||
|
||||
### Parked: TypeScript, Python and Rust resolution
|
||||
|
||||
Each runtime gets its own cut when a consumer that reads a variant-bearing store exists
|
||||
(ruling 5). None does. `Aetheria.cc` is read by C# only.
|
||||
|
||||
## 6. First payoff in `Aetheria.cc`
|
||||
|
||||
Scan of the live file (206 records, `v1`): records of one schema whose leaves differ by at
|
||||
most 20 percent, name excluded. This is a heuristic; the operator confirms the real families.
|
||||
|
||||
| Type | Records | Families that collapse | Records becoming variants |
|
||||
| --- | --- | --- | --- |
|
||||
| geardata | 32 | Refinery / Assembly Line / Deep Ore / Surface Ore / Shipyard (1 to 3 leaves differ); Small / Medium / Large Drive; RevvITup 2.0 / deep space burnout / Talaria; Skiron / Iapyx; Arctica / cold like my heart | 10 |
|
||||
| weaponitemdata | 18 | ChargeBlast SG / ChargeBlast+- (14 of 253 leaves differ); pswarm / scorched void policy; Earp / 6k Shooter; Spectra / ColdFire | 4 |
|
||||
| hulldata | 5 | Longinus / LonginusX (only `Behaviors`, `Hardpoints` and two cosmetic members differ) | 1 |
|
||||
|
||||
That is 15 of 55 equipment records. In most of these families the difference lies inside
|
||||
`Behaviors`, so element-level overrides (C2) are what pay. Top-level overrides alone would
|
||||
still copy each behaviour list.
|
||||
|
||||
## 7. Consumers
|
||||
|
||||
There are 28 projects: C# 13, Rust 9, TypeScript 10, Python 1, Kotlin 0 (Explore survey;
|
||||
dependency-level for most, read in detail for Aetheria and AetheriaEve).
|
||||
- **See variants:** Aetheria through C# `Get`, `GetByName` and `CultRecordRef` (resolved
|
||||
documents only), CultCache Studio (deltas), and AetherDb tools (must honour Q1).
|
||||
- **Must stay oblivious or refuse:** every other consumer. No other project reads
|
||||
`Aetheria.cc`. Raw readers refuse through the empty payload plus C0/C1: `CultMesh`
|
||||
single-file reads, AetheriaEve's directory-page reader (the directory store refuses
|
||||
variants, Q6), and Mimir (writer only).
|
||||
148
docs/document-variants-target.md
Normal file
148
docs/document-variants-target.md
Normal file
|
|
@ -0,0 +1,148 @@
|
|||
# CultCache Document Variants: Target
|
||||
|
||||
Date: 2026-09-17
|
||||
|
||||
Status: target, before any substrate map or cut map. This document owns the ends.
|
||||
A cut map, written after an Imagination pass over the Body, will own the means.
|
||||
Branch: `codex/document-variants`.
|
||||
|
||||
## Why
|
||||
|
||||
A CultCache record today is always complete. To make a bigger laser from a
|
||||
laser, an author copies the record and re-specifies every stat. For a ship hull
|
||||
with several hardpoint layouts, every layout is a full copy of the hull. When
|
||||
the base changes, each copy has to be found and edited by hand, and copies drift
|
||||
apart silently.
|
||||
|
||||
The first consumer is Aetheria's catalog (`F:\Projects\Aetheria\GameData\Aetheria.cc`),
|
||||
edited in CultCache Studio:
|
||||
|
||||
- **Hull variants:** one hull with several hardpoint layout options. A variant
|
||||
replaces the whole `HullData.Hardpoints` member.
|
||||
- **Item variants:** a bigger laser. A variant changes stats nested inside the
|
||||
design's behavior list, for example one behavior's `PerformanceStat.Max`.
|
||||
|
||||
## Rulings (operator, 2026-09-17)
|
||||
|
||||
- **This is a CultCache feature, not an Aetheria mechanism.** Operator: "Yes, this
|
||||
is absolutely a CultCache feature, write it up in CultLib".
|
||||
- **A variant is stored as a delta from its base and resolved by the cache.** A
|
||||
record stores a reference to its base plus a sparse set of overrides. The
|
||||
cache resolves it; readers see complete documents. The operator chose this
|
||||
over two alternatives. Authoring-only variants in Studio over flattened stored
|
||||
copies leave a derived cache pretending to be data. Per-type variant records
|
||||
in each consumer rebuild the feature bespoke for every type.
|
||||
|
||||
## Ends
|
||||
|
||||
- **Readers see complete documents.** `Get`, `GetAll`, lookups by name and by
|
||||
index, watches and snapshots return resolved documents. No consumer outside
|
||||
the cache and its authoring tools handles a delta.
|
||||
- **A base change reaches its variants.** Editing a base changes every variant
|
||||
that does not override the edited value. Watches, indexes and name lookups
|
||||
observe that change on the variants too, in the same commit that changed the
|
||||
base.
|
||||
- **A variant is a record.** It has its own key and name, and references to it
|
||||
behave like references to any record. In Aetheria a lot's design and a
|
||||
product's design can name a variant directly.
|
||||
- **Studio edits the delta.** It shows which values a variant inherits and which
|
||||
it overrides, and it can clear an override so the base value applies again.
|
||||
- **Loading refuses a broken variant loudly and names the records.** Cases:
|
||||
- a cycle of bases;
|
||||
- a base that does not exist;
|
||||
- a base whose type the variant's type cannot inherit from;
|
||||
- ~~an override naming a member that does not exist on the type~~ **superseded 2026-09-29
|
||||
(operator, variants Q4 c): a dangling override soft-drifts like any dropped member, ignored
|
||||
with a warning; see `document-variants-cut.md` section 4.**
|
||||
|
||||
Deleting a base that still has variants is refused.
|
||||
|
||||
## Invariants that must survive
|
||||
|
||||
- **Wire parity** for the persisted format (`src/GameCult.Caching/Contracts/cultcache-persistence-format.md`,
|
||||
`docs/persisted-record-encoding.md`). Every runtime that reads a store holding
|
||||
variants resolves them identically, or refuses the store loudly. Which
|
||||
runtimes resolve is decided in the map, against
|
||||
`docs/runtime-parity-scope.md`; none may misread silently.
|
||||
- **One home store per type**, and atomic single-store commit
|
||||
(`cultcache-store-composition.md`). A base change and the resulting variant
|
||||
changes are one commit, not a repair that runs afterwards.
|
||||
- **Schema compatibility** (`cultcache-schema-compatibility.md`): overrides are
|
||||
subject to the same semantic identity, soft drift and hard rejection rules as
|
||||
full records.
|
||||
- **Compare-exchange** (`Expect`, `ExpectUnchanged`) keeps a single meaning for
|
||||
variants. The map settles whether it tests the stored delta or the resolved
|
||||
document; it must not mean both.
|
||||
|
||||
## Fork rulings (operator, 2026-09-17)
|
||||
|
||||
- **1, granularity: stable element identity, ids everywhere** (operator, 2026-09-17: "ids
|
||||
everywhere").
|
||||
- Every object element in a list carries a stable id, minted when the element is created.
|
||||
This is the approach of sequence CRDTs (RGA, YATA/Yjs, Automerge, Fugue).
|
||||
- Matching algorithms (Myers, diff3, GumTree) are heuristics. They fail on look-alike
|
||||
elements such as two `EnergyDraw` behaviors, which is why identity is minted, not
|
||||
inferred.
|
||||
- An override addresses an element id plus a member path in CultNet's grammar. An
|
||||
insertion is a new element anchored after an existing id; a removal names the
|
||||
removed id. Index addressing is out.
|
||||
- Rebasing is deterministic. An override whose element id exists in the new base
|
||||
re-applies. One whose element is missing is an explicit conflict that Studio shows,
|
||||
to keep, retarget or clear; it is never silently retargeted.
|
||||
- Existing stores get ids minted once, by a rewrite.
|
||||
- **2, where resolution lives: at load, kept in memory** (operator: "agreed"). Resolution
|
||||
computes a variant's complete document from its base chain and its overrides.
|
||||
- The cache holds both the stored delta and the resolved document.
|
||||
- A base edit re-resolves its variants inside the same commit, so watches and indexes
|
||||
observe the change atomically.
|
||||
- Compare-exchange (`Expect`) tests the stored delta. The resolved document is derived.
|
||||
- **3, cross-store bases: no.** A variant and its base live in the same store.
|
||||
- **4, CultNet: deltas.**
|
||||
- **5, runtimes: C# first.** TypeScript, Python, Rust and Kotlin refuse a store
|
||||
or snapshot containing variants, loudly, until each implements resolution.
|
||||
- **6, type change: the same concrete type only** (operator: "agreed").
|
||||
- An override can only name members the base type has, and rebasing requires the same
|
||||
type.
|
||||
- A variant whose type differs from its base's is refused loudly.
|
||||
- Subtype variants are parked until real content needs a template base. A record
|
||||
flagged as a template, not a real item, may be the smaller feature.
|
||||
- **7, clearing and rebasing.**
|
||||
- Clearing an override removes that member from the variant's stored delta. A member
|
||||
that is not overridden is not stored.
|
||||
- Rebasing (changing a variant's base) is supported. Operator: "rebasing is a nice
|
||||
tool to have, things can get annoying otherwise".
|
||||
|
||||
## Open forks, for the Imagination pass to map and the operator to rule
|
||||
|
||||
1. **Override granularity.**
|
||||
- Top-level members are enough for hardpoint layouts.
|
||||
- A bigger laser needs overrides inside list elements. Addressing list
|
||||
elements by index is fragile: an insertion into the base silently retargets
|
||||
every variant's overrides.
|
||||
- Candidates: stable element identity (for example a behavior's type within its
|
||||
design); replacing whole list elements only; or addressing paths.
|
||||
- CultNet's selection work already resolves member paths per leaf type,
|
||||
inherited members included (`docs/cultnet-selection-cut.md`). A variant's
|
||||
delta addressing should reuse that grammar, not invent a second one.
|
||||
2. **Where resolution lives:** at load in the cache core, lazily on read, or as a
|
||||
materialized view the cache maintains. This affects memory, watch cost, and
|
||||
the compare-exchange meaning.
|
||||
3. **Base and variant across stores.** Can a variant in one store name a base in
|
||||
another (a run-store variant of a catalog record)? This interacts with
|
||||
one-home-store routing and read-only stores.
|
||||
4. **CultNet.** Do variants travel as deltas, or resolved? A subscriber that
|
||||
receives only resolved documents needs no resolver; one that edits needs
|
||||
deltas.
|
||||
5. **Runtime scope.** Which of C#, TypeScript, Python, Rust and Kotlin resolve,
|
||||
and which refuse a store containing variants.
|
||||
6. **Type change.** May a variant's type be a subtype of its base's type,
|
||||
adding members, or must the two types match?
|
||||
7. **Clearing and reparenting.** What clearing an override writes, and whether
|
||||
a variant can change its base.
|
||||
|
||||
## Not in scope
|
||||
|
||||
- Scaling or formula variants ("every stat times 1.5"). An override states a
|
||||
value. Generated authoring can compute values.
|
||||
- Any Aetheria catalog content. Aetheria adopts the feature after a release, as
|
||||
its own cut.
|
||||
|
|
@ -13,6 +13,11 @@ Cross-runtime parity has three layers:
|
|||
- Wire parity: shared CultCache file/state contracts, schema-v0 MessagePack
|
||||
documents, transport profiles, and RUDP packets must cross runtime boundaries
|
||||
without translation folklore.
|
||||
Every store reader refuses, by name, a header or record slot it does not
|
||||
understand (vectors: `tests/vectors/document-variants-c0`).
|
||||
Document variants: C# resolves them (`cultcache.store.v2`); every other runtime,
|
||||
CultMesh single-file reads, the directory store and CultNet refuse a variant by name
|
||||
(vector written by C#: `tests/vectors/document-variants-c1`).
|
||||
- Feature parity: each runtime must expose the CultCache/CultNet/CultMesh
|
||||
surfaces needed for its intended role, with unsupported production-server
|
||||
ownership called out plainly.
|
||||
|
|
@ -73,6 +78,23 @@ to speak CultNet or participate in CultMesh.
|
|||
`tests/GameCult.Networking.Tests/SelectionParityVectorTests.cs` carry the
|
||||
semantic ones. A single rows-to-bytes path driving both halves in one call
|
||||
remains its own cut (R-AR) and is not part of this claim.
|
||||
- CultMesh content plane (`cultmesh.content_chunk_request.v1` and `.response.v1`
|
||||
plus the CDN manifest, C#/Rust only): byte parity in both directions (manifest metadata keeps its wire key order and a
|
||||
duplicate key is refused, as the reference refuses it), and the reference's answer
|
||||
to a chunk request, including its failure spellings: every bad request is
|
||||
answered `found: false`, never refused at decode.
|
||||
`packages/cultnet-rs/tests/content.rs` and
|
||||
`tests/GameCult.Mesh.Tests/CultMeshContentVectorTests.cs` judge
|
||||
`contracts/cultmesh/content-vectors.cs-written.json` and
|
||||
`content-vectors.rs-written.json`. Rust carries these chunks only on the
|
||||
session the client already holds (see `src/GameCult.Mesh/docs/transport-planes.md`);
|
||||
it has no authenticated content connector, so it claims no TCP+TLS or QUIC
|
||||
content path.
|
||||
Recorded limits: a caller that passes `max_bytes = u64::MAX` to `fetch_content` gets an unbounded
|
||||
body, because the reference refuses artifacts over `int.MaxValue` bytes and Rust bounds them only by the
|
||||
caller's cap.
|
||||
`normalize_hash` matches the `sha256:` prefix ASCII-case-insensitively while C# `OrdinalIgnoreCase` may
|
||||
also match non-ASCII forms (for example `ſha256:`); unprobed, and it affects hostile input only.
|
||||
|
||||
## Expansion Work Outside The Current Parity Claim
|
||||
|
||||
|
|
|
|||
|
|
@ -14,6 +14,8 @@ from .backing_store import (
|
|||
)
|
||||
|
||||
STORE_FORMAT_VERSION = "cultcache.store.v1"
|
||||
_STORE_FORMAT_PREFIX = "cultcache.store."
|
||||
_PERSISTED_RECORD_SLOTS = 4
|
||||
|
||||
|
||||
class JsonLinesBackingStore:
|
||||
|
|
@ -153,7 +155,14 @@ def _encode_v1_snapshot(envelopes: list[CultCacheEnvelope]) -> list[Any]:
|
|||
|
||||
|
||||
def _decode_v1_snapshot(decoded: Any) -> list[CultCacheEnvelope] | None:
|
||||
if not isinstance(decoded, list) or not decoded or decoded[0] != STORE_FORMAT_VERSION:
|
||||
if not isinstance(decoded, list) or not decoded:
|
||||
return None
|
||||
if isinstance(decoded[0], str) and decoded[0].startswith(_STORE_FORMAT_PREFIX) and decoded[0] != STORE_FORMAT_VERSION:
|
||||
raise ValueError(
|
||||
f"CultCache store format {decoded[0]!r} is not readable; this runtime reads {STORE_FORMAT_VERSION!r} only. "
|
||||
"The store needs a runtime that resolves document variants."
|
||||
)
|
||||
if decoded[0] != STORE_FORMAT_VERSION:
|
||||
return None
|
||||
if len(decoded) < 3 or not isinstance(decoded[1], list) or not isinstance(decoded[2], list):
|
||||
raise ValueError("CultCache v1 snapshot must contain a schema catalog and record array")
|
||||
|
|
@ -169,7 +178,12 @@ def _decode_v1_snapshot(decoded: Any) -> list[CultCacheEnvelope] | None:
|
|||
for raw_record in decoded[2]:
|
||||
if not isinstance(raw_record, list) or len(raw_record) < 4:
|
||||
raise ValueError("CultCache persisted records must be MessagePack arrays")
|
||||
key, schema_id, stored_at, payload = raw_record[:4]
|
||||
if len(raw_record) > _PERSISTED_RECORD_SLOTS:
|
||||
raise ValueError(
|
||||
f"CultCache record {raw_record[0]!r} (schema {raw_record[1]!r}) has {len(raw_record)} slots; "
|
||||
f"this runtime reads {_PERSISTED_RECORD_SLOTS}. The store needs a runtime that resolves document variants."
|
||||
)
|
||||
key, schema_id, stored_at, payload = raw_record
|
||||
if not isinstance(key, str) or not key:
|
||||
raise ValueError("CultCache persisted records must declare a key")
|
||||
if not isinstance(schema_id, str) or not schema_id:
|
||||
|
|
|
|||
|
|
@ -802,5 +802,45 @@ class CultCacheTests(unittest.TestCase):
|
|||
self.assertEqual(cache.get_required_envelope(document, "item:one").key, "item:one")
|
||||
|
||||
|
||||
# Shared refusal vectors: tests/vectors/document-variants-c0, read by every runtime's tests.
|
||||
_VECTORS = Path(__file__).resolve().parents[3] / "tests" / "vectors" / "document-variants-c0"
|
||||
_ITEM_SCHEMA_ID = "sha256:88d3fdf0a927acf3b163940d8f8c7fe62b3316542ce771a67ec8bc038f594788"
|
||||
|
||||
def _pull_vector(self, name: str) -> list[CultCacheEnvelope]:
|
||||
with tempfile.TemporaryDirectory() as tmp:
|
||||
store_path = Path(tmp) / "store.msgpack"
|
||||
store_path.write_bytes((self._VECTORS / name).read_bytes())
|
||||
return SingleFileMessagePackBackingStore(store_path).pull_all()
|
||||
|
||||
def test_single_file_refuses_unknown_header_by_name(self) -> None:
|
||||
with self.assertRaises(ValueError) as caught:
|
||||
self._pull_vector("unknown-header.msgpack")
|
||||
self.assertIn("cultcache.store.v9", str(caught.exception))
|
||||
|
||||
def test_single_file_refuses_extra_record_slot_naming_the_record(self) -> None:
|
||||
with self.assertRaises(ValueError) as caught:
|
||||
self._pull_vector("extra-slot-full-payload.msgpack")
|
||||
self.assertIn("item:anvil", str(caught.exception))
|
||||
self.assertIn(self._ITEM_SCHEMA_ID, str(caught.exception))
|
||||
|
||||
def test_single_file_refuses_variant_store_by_version_or_record(self) -> None:
|
||||
with self.assertRaises(ValueError) as caught:
|
||||
self._pull_vector("variant-v2.msgpack")
|
||||
message = str(caught.exception)
|
||||
self.assertTrue("cultcache.store.v2" in message or "item:anvil-big" in message, message)
|
||||
|
||||
def test_single_file_refuses_the_csharp_written_variant_store_by_version_or_record(self) -> None:
|
||||
with self.assertRaises(ValueError) as caught:
|
||||
self._pull_vector("../document-variants-c1/variant-store.msgpack")
|
||||
message = str(caught.exception)
|
||||
self.assertTrue("cultcache.store.v2" in message or "laser-big" in message, message)
|
||||
|
||||
def test_v1_store_written_at_the_base_commit_still_reads_byte_for_byte(self) -> None:
|
||||
envelopes = self._pull_vector("v1-base.msgpack")
|
||||
self.assertEqual([(e.key, e.type) for e in envelopes], [("alpha", "vectors.item"), ("beta", "vectors.item")])
|
||||
self.assertEqual(envelopes[0].payload, b"\x92\xa5alpha\x01")
|
||||
self.assertEqual(envelopes[1].payload, b"\x92\xa4beta\x02")
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
unittest.main()
|
||||
|
|
|
|||
|
|
@ -271,7 +271,7 @@ struct PersistedSchemaCatalogMember(
|
|||
Option<String>,
|
||||
);
|
||||
|
||||
#[derive(Clone, Debug, serde::Serialize, serde::Deserialize)]
|
||||
#[derive(Clone, Debug, serde::Serialize)]
|
||||
struct PersistedRecord(
|
||||
String,
|
||||
String,
|
||||
|
|
@ -279,6 +279,67 @@ struct PersistedRecord(
|
|||
#[serde(with = "serde_bytes")] Vec<u8>,
|
||||
);
|
||||
|
||||
impl<'de> serde::Deserialize<'de> for PersistedRecord {
|
||||
/// Reads the four v1 slots and refuses a fifth, naming the record. A record with more
|
||||
/// slots was written by a runtime that resolves document variants.
|
||||
fn deserialize<D: serde::Deserializer<'de>>(deserializer: D) -> std::result::Result<Self, D::Error> {
|
||||
use serde::de::{Error, IgnoredAny, SeqAccess, Visitor};
|
||||
|
||||
struct RecordVisitor;
|
||||
impl<'de> Visitor<'de> for RecordVisitor {
|
||||
type Value = PersistedRecord;
|
||||
|
||||
fn expecting(&self, formatter: &mut std::fmt::Formatter) -> std::fmt::Result {
|
||||
formatter.write_str("a CultCache persisted record of 4 slots")
|
||||
}
|
||||
|
||||
fn visit_seq<A: SeqAccess<'de>>(self, mut seq: A) -> std::result::Result<PersistedRecord, A::Error> {
|
||||
let key: String = seq.next_element()?.ok_or_else(|| A::Error::invalid_length(0, &self))?;
|
||||
let schema_id: String = seq.next_element()?.ok_or_else(|| A::Error::invalid_length(1, &self))?;
|
||||
let stored_at: String = seq.next_element()?.ok_or_else(|| A::Error::invalid_length(2, &self))?;
|
||||
let payload: serde_bytes::ByteBuf =
|
||||
seq.next_element()?.ok_or_else(|| A::Error::invalid_length(3, &self))?;
|
||||
if seq.next_element::<IgnoredAny>()?.is_some() {
|
||||
return Err(A::Error::custom(format!(
|
||||
"CultCache record {key:?} (schema {schema_id:?}) has more than 4 slots; this runtime reads 4. The store needs a runtime that resolves document variants."
|
||||
)));
|
||||
}
|
||||
Ok(PersistedRecord(key, schema_id, stored_at, payload.into_vec()))
|
||||
}
|
||||
}
|
||||
|
||||
deserializer.deserialize_seq(RecordVisitor)
|
||||
}
|
||||
}
|
||||
|
||||
/// The store header string, or `None` when the bytes are not a snapshot-shaped array
|
||||
/// (the legacy envelope array starts with a map).
|
||||
fn store_header(bytes: &[u8]) -> Option<String> {
|
||||
struct Header(String);
|
||||
impl<'de> serde::Deserialize<'de> for Header {
|
||||
fn deserialize<D: serde::Deserializer<'de>>(deserializer: D) -> std::result::Result<Self, D::Error> {
|
||||
struct HeaderVisitor;
|
||||
impl<'de> serde::de::Visitor<'de> for HeaderVisitor {
|
||||
type Value = Header;
|
||||
|
||||
fn expecting(&self, formatter: &mut std::fmt::Formatter) -> std::fmt::Result {
|
||||
formatter.write_str("an array whose first slot is the store header")
|
||||
}
|
||||
|
||||
fn visit_seq<A: serde::de::SeqAccess<'de>>(self, mut seq: A) -> std::result::Result<Header, A::Error> {
|
||||
let header: String = seq
|
||||
.next_element()?
|
||||
.ok_or_else(|| <A::Error as serde::de::Error>::invalid_length(0, &self))?;
|
||||
while seq.next_element::<serde::de::IgnoredAny>()?.is_some() {}
|
||||
Ok(Header(header))
|
||||
}
|
||||
}
|
||||
deserializer.deserialize_seq(HeaderVisitor)
|
||||
}
|
||||
}
|
||||
rmp_serde::from_slice::<Header>(bytes).ok().map(|header| header.0)
|
||||
}
|
||||
|
||||
#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]
|
||||
pub struct PushAllOptions {
|
||||
pub soft: bool,
|
||||
|
|
@ -658,9 +719,11 @@ impl SingleFileMessagePackBackingStore {
|
|||
if bytes.is_empty() {
|
||||
return Ok(Vec::new());
|
||||
}
|
||||
decode_store_snapshot(&bytes)
|
||||
.or_else(|_| rmp_serde::from_slice(&bytes))
|
||||
.with_context(|| format!("failed to decode MessagePack {}", self.path.display()))
|
||||
match store_header(&bytes) {
|
||||
Some(header) if header.starts_with("cultcache.store.") => decode_store_snapshot(&bytes),
|
||||
_ => rmp_serde::from_slice(&bytes).map_err(anyhow::Error::from),
|
||||
}
|
||||
.map_err(|error| anyhow!("failed to decode MessagePack {}: {error:#}", self.path.display()))
|
||||
}
|
||||
|
||||
/// Reads one filesystem snapshot without creating or opening the sibling
|
||||
|
|
@ -2518,11 +2581,15 @@ fn encode_store_snapshot(entries: &[CultCacheEnvelope]) -> Result<PersistedStore
|
|||
}
|
||||
|
||||
fn decode_store_snapshot(bytes: &[u8]) -> Result<Vec<CultCacheEnvelope>> {
|
||||
if let Some(header) = store_header(bytes) {
|
||||
if header != "cultcache.store.v1" {
|
||||
return Err(anyhow!(
|
||||
"CultCache store format {header:?} is not readable; this runtime reads \"cultcache.store.v1\" only. The store needs a runtime that resolves document variants."
|
||||
));
|
||||
}
|
||||
}
|
||||
let snapshot: PersistedStoreSnapshot =
|
||||
rmp_serde::from_slice(bytes).context("failed to decode CultCache v1 snapshot")?;
|
||||
if snapshot.0 != "cultcache.store.v1" {
|
||||
return Err(anyhow!("unsupported CultCache snapshot {}", snapshot.0));
|
||||
}
|
||||
|
||||
let catalog = snapshot
|
||||
.1
|
||||
|
|
@ -4573,4 +4640,62 @@ mod tests {
|
|||
assert_eq!(store.pull_all_read_only_snapshot()?, vec![admitted]);
|
||||
Ok(())
|
||||
}
|
||||
|
||||
// Shared refusal vectors: tests/vectors/document-variants-c0, read by every runtime's tests.
|
||||
const ITEM_SCHEMA_ID: &str = "sha256:88d3fdf0a927acf3b163940d8f8c7fe62b3316542ce771a67ec8bc038f594788";
|
||||
|
||||
fn pull_vector(name: &str) -> Result<Vec<CultCacheEnvelope>> {
|
||||
let temp = tempfile::tempdir()?;
|
||||
let path = temp.path().join("store.msgpack");
|
||||
let vector = std::path::Path::new(env!("CARGO_MANIFEST_DIR"))
|
||||
.join("../../tests/vectors/document-variants-c0")
|
||||
.join(name);
|
||||
std::fs::copy(vector, &path)?;
|
||||
SingleFileMessagePackBackingStore::new(&path).pull_all()
|
||||
}
|
||||
|
||||
fn refusal(name: &str) -> String {
|
||||
format!("{:#}", pull_vector(name).unwrap_err())
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn single_file_refuses_unknown_header_by_name() {
|
||||
assert!(refusal("unknown-header.msgpack").contains("cultcache.store.v9"));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn single_file_refuses_extra_record_slot_naming_the_record() {
|
||||
let message = refusal("extra-slot-full-payload.msgpack");
|
||||
assert!(message.contains("item:anvil"), "{message}");
|
||||
assert!(message.contains(ITEM_SCHEMA_ID), "{message}");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn single_file_refuses_variant_store_by_version_or_record() {
|
||||
let message = refusal("variant-v2.msgpack");
|
||||
assert!(
|
||||
message.contains("cultcache.store.v2") || message.contains("item:anvil-big"),
|
||||
"{message}"
|
||||
);
|
||||
}
|
||||
|
||||
// The store the C# runtime wrote through its own variant API (tests/vectors/document-variants-c1).
|
||||
#[test]
|
||||
fn single_file_refuses_the_csharp_written_variant_store_by_version_or_record() {
|
||||
let message = refusal("../document-variants-c1/variant-store.msgpack");
|
||||
assert!(
|
||||
message.contains("cultcache.store.v2") || message.contains("laser-big"),
|
||||
"{message}"
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn v1_store_written_at_the_base_commit_still_reads_byte_for_byte() -> Result<()> {
|
||||
let envelopes = pull_vector("v1-base.msgpack")?;
|
||||
let rows: Vec<_> = envelopes.iter().map(|e| (e.key.as_str(), e.r#type.as_str())).collect();
|
||||
assert_eq!(rows, vec![("alpha", "vectors.item"), ("beta", "vectors.item")]);
|
||||
assert_eq!(envelopes[0].payload, b"\x92\xa5alpha\x01");
|
||||
assert_eq!(envelopes[1].payload, b"\x92\xa4beta\x02");
|
||||
Ok(())
|
||||
}
|
||||
}
|
||||
|
|
|
|||
|
|
@ -45,7 +45,7 @@
|
|||
},
|
||||
"homepage": "https://github.com/GameCult/CultLib/tree/main/packages/cultcache-ts#readme",
|
||||
"engines": {
|
||||
"node": ">=18"
|
||||
"node": ">=20"
|
||||
},
|
||||
"dependencies": {
|
||||
"@msgpack/msgpack": "^3.1.3",
|
||||
|
|
|
|||
|
|
@ -1,5 +1,7 @@
|
|||
import { decode } from "@msgpack/msgpack";
|
||||
|
||||
import { STORE_FORMAT_VERSION, isV1Snapshot, requireV1RecordSlots } from "./store-format";
|
||||
|
||||
export interface CultCacheInspection {
|
||||
filePath: string;
|
||||
fileSizeBytes: number;
|
||||
|
|
@ -39,8 +41,6 @@ export interface InspectedRecord {
|
|||
payloadDecodeError?: string;
|
||||
}
|
||||
|
||||
const STORE_FORMAT_VERSION = "cultcache.store.v1";
|
||||
|
||||
export function inspectCultCacheBytes(
|
||||
filePath: string,
|
||||
bytes: Uint8Array,
|
||||
|
|
@ -197,6 +197,7 @@ function decodeV1Record(value: unknown, catalogBySchemaId: Map<string, Inspected
|
|||
throw new Error("CultCache persisted records must be MessagePack arrays.");
|
||||
}
|
||||
|
||||
requireV1RecordSlots(value);
|
||||
const [key = "", schemaId = "", storedAt = "", payload = new Uint8Array()] = value;
|
||||
if (!isNonEmptyString(key) || !isNonEmptyString(schemaId) || !isNonEmptyString(storedAt)) {
|
||||
throw new Error("CultCache persisted records must declare key, schemaId, and storedAt.");
|
||||
|
|
@ -349,10 +350,6 @@ function toJsonSafe(value: unknown): unknown {
|
|||
return value;
|
||||
}
|
||||
|
||||
function isV1Snapshot(value: unknown): value is unknown[] {
|
||||
return Array.isArray(value) && value[0] === STORE_FORMAT_VERSION;
|
||||
}
|
||||
|
||||
function isRecord(value: unknown): value is Record<string, unknown> {
|
||||
return typeof value === "object" && value !== null;
|
||||
}
|
||||
|
|
|
|||
|
|
@ -4,6 +4,7 @@ import { dirname, resolve } from "node:path";
|
|||
import { decode, encode } from "@msgpack/msgpack";
|
||||
import { z } from "zod";
|
||||
|
||||
import { STORE_FORMAT_VERSION, isV1Snapshot, requireV1RecordSlots } from "./store-format";
|
||||
import type {
|
||||
CacheBackingStore,
|
||||
CultCacheEnvelope,
|
||||
|
|
@ -12,8 +13,6 @@ import type {
|
|||
PushAllOptions,
|
||||
} from "./types";
|
||||
|
||||
const STORE_FORMAT_VERSION = "cultcache.store.v1";
|
||||
|
||||
const envelopeSchema = z.object({
|
||||
key: z.string().min(1),
|
||||
type: z.string().min(1),
|
||||
|
|
@ -285,7 +284,7 @@ function encodeCatalogMember(member: CultCacheSchemaCatalogMember): unknown[] {
|
|||
}
|
||||
|
||||
function decodeSnapshot(decoded: unknown): DecodedSnapshot | undefined {
|
||||
if (!Array.isArray(decoded) || decoded.length === 0 || decoded[0] !== STORE_FORMAT_VERSION) {
|
||||
if (!isV1Snapshot(decoded)) {
|
||||
return undefined;
|
||||
}
|
||||
|
||||
|
|
@ -436,6 +435,7 @@ function decodeRecord(value: unknown): PersistedRecord {
|
|||
throw new Error("CultCache persisted records must be MessagePack arrays.");
|
||||
}
|
||||
|
||||
requireV1RecordSlots(value);
|
||||
const [key = "", schemaId = "", storedAt = "", payload = new Uint8Array()] = value;
|
||||
if (!isNonEmptyString(key) || !isNonEmptyString(schemaId) || !isNonEmptyString(storedAt)) {
|
||||
throw new Error("CultCache persisted records must declare key, schemaId, and storedAt.");
|
||||
|
|
|
|||
33
packages/cultcache-ts/src/store-format.ts
Normal file
33
packages/cultcache-ts/src/store-format.ts
Normal file
|
|
@ -0,0 +1,33 @@
|
|||
export const STORE_FORMAT_VERSION = "cultcache.store.v1";
|
||||
|
||||
const STORE_FORMAT_PREFIX = "cultcache.store.";
|
||||
const PERSISTED_RECORD_SLOTS = 4;
|
||||
|
||||
/**
|
||||
* True for a v1 snapshot, false for anything that is not a CultCache store header (the legacy
|
||||
* envelope array). Any other `cultcache.store.*` header is refused by name.
|
||||
*/
|
||||
export function isV1Snapshot(decoded: unknown): decoded is unknown[] {
|
||||
if (!Array.isArray(decoded) || typeof decoded[0] !== "string" || !decoded[0].startsWith(STORE_FORMAT_PREFIX)) {
|
||||
return false;
|
||||
}
|
||||
|
||||
if (decoded[0] !== STORE_FORMAT_VERSION) {
|
||||
throw new Error(
|
||||
`CultCache store format "${decoded[0]}" is not readable; this runtime reads "${STORE_FORMAT_VERSION}" only. ` +
|
||||
"The store needs a runtime that resolves document variants.",
|
||||
);
|
||||
}
|
||||
|
||||
return true;
|
||||
}
|
||||
|
||||
/** Refuses a persisted record with more slots than v1 defines, naming its key and schema id. */
|
||||
export function requireV1RecordSlots(record: unknown[]): void {
|
||||
if (record.length > PERSISTED_RECORD_SLOTS) {
|
||||
throw new Error(
|
||||
`CultCache record "${String(record[0])}" (schema "${String(record[1])}") has ${record.length} slots; ` +
|
||||
`this runtime reads ${PERSISTED_RECORD_SLOTS}. The store needs a runtime that resolves document variants.`,
|
||||
);
|
||||
}
|
||||
}
|
||||
|
|
@ -1413,3 +1413,55 @@ async function runJsonCommand(
|
|||
|
||||
return JSON.parse(trimmed.split(/\r?\n/).at(-1) as string);
|
||||
}
|
||||
|
||||
// Shared refusal vectors: tests/vectors/document-variants-c0, read by every runtime's tests.
|
||||
const variantVectors = resolve(cultLibRoot, "tests", "vectors", "document-variants-c0");
|
||||
const itemSchemaId = "sha256:88d3fdf0a927acf3b163940d8f8c7fe62b3316542ce771a67ec8bc038f594788";
|
||||
|
||||
async function pullVector(name: string): Promise<CultCacheEnvelope[]> {
|
||||
const dir = await mkdtemp(join(tmpdir(), "cultcache-vector-"));
|
||||
const file = join(dir, "store.msgpack");
|
||||
await writeFile(file, await readFile(join(variantVectors, name)));
|
||||
return new SingleFileMessagePackBackingStore(file).pullAll();
|
||||
}
|
||||
|
||||
test("SingleFileMessagePackBackingStore refuses an unknown store header by name", async () => {
|
||||
await assert.rejects(() => pullVector("unknown-header.msgpack"), /cultcache\.store\.v9/u);
|
||||
});
|
||||
|
||||
test("SingleFileMessagePackBackingStore refuses an extra record slot naming the record", async () => {
|
||||
await assert.rejects(
|
||||
() => pullVector("extra-slot-full-payload.msgpack"),
|
||||
(error: Error) => error.message.includes("item:anvil") && error.message.includes(itemSchemaId),
|
||||
);
|
||||
});
|
||||
|
||||
test("SingleFileMessagePackBackingStore refuses a variant store by version or record", async () => {
|
||||
await assert.rejects(
|
||||
() => pullVector("variant-v2.msgpack"),
|
||||
(error: Error) => error.message.includes("cultcache.store.v2") || error.message.includes("item:anvil-big"),
|
||||
);
|
||||
});
|
||||
|
||||
test("SingleFileMessagePackBackingStore refuses the C#-written variant store by version or record", async () => {
|
||||
await assert.rejects(
|
||||
() => pullVector("../document-variants-c1/variant-store.msgpack"),
|
||||
(error: Error) => error.message.includes("cultcache.store.v2") || error.message.includes("laser-big"),
|
||||
);
|
||||
});
|
||||
|
||||
test("CultCache inspector refuses the same vectors by name", async () => {
|
||||
const inspect = async (name: string) => inspectCultCacheBytes(name, await readFile(join(variantVectors, name)));
|
||||
await assert.rejects(() => inspect("unknown-header.msgpack"), /cultcache\.store\.v9/u);
|
||||
await assert.rejects(
|
||||
() => inspect("extra-slot-full-payload.msgpack"),
|
||||
(error: Error) => error.message.includes("item:anvil") && error.message.includes(itemSchemaId),
|
||||
);
|
||||
});
|
||||
|
||||
test("a v1 store written at the base commit still reads byte for byte", async () => {
|
||||
const envelopes = await pullVector("v1-base.msgpack");
|
||||
assert.deepEqual(envelopes.map((entry) => [entry.key, entry.type]), [["alpha", "vectors.item"], ["beta", "vectors.item"]]);
|
||||
assert.deepEqual([...envelopes[0]!.payload], [0x92, 0xa5, 0x61, 0x6c, 0x70, 0x68, 0x61, 0x01]);
|
||||
assert.deepEqual([...envelopes[1]!.payload], [0x92, 0xa4, 0x62, 0x65, 0x74, 0x61, 0x02]);
|
||||
});
|
||||
|
|
|
|||
|
|
@ -37,7 +37,7 @@
|
|||
"directory": "packages/cultmesh-browser"
|
||||
},
|
||||
"engines": {
|
||||
"node": ">=18"
|
||||
"node": ">=20"
|
||||
},
|
||||
"dependencies": {
|
||||
"@msgpack/msgpack": "^3.1.3",
|
||||
|
|
|
|||
|
|
@ -40,7 +40,7 @@
|
|||
},
|
||||
"homepage": "https://github.com/GameCult/CultLib/tree/main/packages/cultmesh-ts#readme",
|
||||
"engines": {
|
||||
"node": ">=18"
|
||||
"node": ">=20"
|
||||
},
|
||||
"dependencies": {
|
||||
"@msgpack/msgpack": "^3.1.2",
|
||||
|
|
|
|||
|
|
@ -28,7 +28,7 @@
|
|||
"code": {
|
||||
"description": "Machine-readable refusal code (R-N). Additive: a v0 peer that does not know this field ignores it.",
|
||||
"type": ["string", "null"],
|
||||
"enum": [null, "selection_invalid", "cursor_stale", "cursor_invalid", "reference_outside_target"]
|
||||
"enum": [null, "selection_invalid", "cursor_stale", "cursor_invalid", "reference_outside_target", "variant_unsupported"]
|
||||
},
|
||||
"details": {
|
||||
"description": "Code-specific structured detail (R-N). Every field is populated only for the code that defines it; the others are null, not omitted.",
|
||||
|
|
@ -36,8 +36,8 @@
|
|||
"additionalProperties": false,
|
||||
"required": ["field", "value", "asOf", "current"],
|
||||
"properties": {
|
||||
"field": { "description": "selection_invalid: the selection field that failed.", "type": ["string", "null"] },
|
||||
"value": { "description": "selection_invalid: the offending value, when there is one string worth naming.", "type": ["string", "null"] },
|
||||
"field": { "description": "selection_invalid: the selection field that failed. variant_unsupported: \"subscriptionId\", when a subscription was ended.", "type": ["string", "null"] },
|
||||
"value": { "description": "selection_invalid: the offending value, when there is one string worth naming. variant_unsupported: the id of the subscription that ended.", "type": ["string", "null"] },
|
||||
"asOf": { "description": "cursor_stale: the cursor's own minted asOf.", "type": ["integer", "null"], "minimum": 0 },
|
||||
"current": { "description": "cursor_stale: the answering server's current asOf.", "type": ["integer", "null"], "minimum": 0 }
|
||||
}
|
||||
|
|
|
|||
445
packages/cultnet-rs/examples/idunn_runtime_fixture.rs
Normal file
445
packages/cultnet-rs/examples/idunn_runtime_fixture.rs
Normal file
|
|
@ -0,0 +1,445 @@
|
|||
//! Generate the Idunn runtime fixtures that cultnet-ts is tested against.
|
||||
//!
|
||||
//! The Rust owner builds every input: real enrolled identities, an Expected that
|
||||
//! passes `validate`, an Activation issued by `IdunnRuntimeActivationLaunch`, the
|
||||
//! bundle files written through `SingleFileMessagePackBackingStore`, and
|
||||
//! runtime-presence vectors signed by the Rust signers. Each vector is also run
|
||||
//! through `authenticate_runtime_presence_claim` and
|
||||
//! `correlate_runtime_presence_claim` before it is written, so the bytes
|
||||
//! committed to the TypeScript tests are ones this verifier accepted (or, for
|
||||
//! the low-capacity vector, ones it correlates to the typed capacity
|
||||
//! disagreement). Ed25519 is deterministic, so the TypeScript signer must
|
||||
//! reproduce each vector byte for byte from the same fields.
|
||||
//!
|
||||
//! A `stateful` set is the lease-bound shape: Expected carries a state
|
||||
//! lineage and requires a write lease, and Rust issues `lease.cc` naming the
|
||||
//! warming vector's digest. Its warming vector is sequence 1; the active and
|
||||
//! degraded vectors are sequence 2 and bind to that lease. Two further leases are
|
||||
//! deliberately wrong (`lease-other-warming.cc` names a different warming digest,
|
||||
//! `lease-other-target.cc` names another target) for refusal tests.
|
||||
//!
|
||||
//! Linux only: the provider identity is bound to `/etc/machine-id`, and the
|
||||
//! generated `machine-id` file records the value the identities were bound to.
|
||||
//!
|
||||
//! Usage: idunn_runtime_fixture <out-dir> <spec>...
|
||||
//!
|
||||
//! The specification is command-line flags. `@<file>` splices in a response
|
||||
//! file: one flag per line, `--flag value` split at the first whitespace, blank
|
||||
//! lines and `#` lines ignored. CultLib's own sets are
|
||||
//! `packages/cultnet-ts/test/fixtures/idunn-runtime/fixture.args`.
|
||||
//!
|
||||
//! Global flags:
|
||||
//! --source-repository <repo> Expected.source_repository (default github.com/GameCult/Example)
|
||||
//! --detail <text> presence detail (default route-observation:route-challenge-1)
|
||||
//!
|
||||
//! `--set <dir>` opens a fixture set written to `<out-dir>/<dir>`; the flags
|
||||
//! below apply to the set most recently opened:
|
||||
//! --target <name> required
|
||||
//! --transport <t> --stable <endpoint> --candidate <endpoint> required: the route
|
||||
//! --capability <name> default `<target>.api`
|
||||
//! --schema <schema> default `<capability>.v1`
|
||||
//! --health-contract <contract> default `<target>.runtime-health`
|
||||
//! --minimum-capacity <n> default 1; above 1 also writes presence-active-below-minimum.bin
|
||||
//! --stateful state lineage, write lease and lease vectors
|
||||
//! --state-schema-generation <id> stateful only; default state-v1
|
||||
//! --lease-other-target <name> stateful only; default the first other set's target
|
||||
//! --dependency k=v,k=v,... repeatable; keys kind, capability, schema, provider,
|
||||
//! endpoint (required), compatibility (v1), capacity (1),
|
||||
//! startup (before-promotion), authority (managed-incarnation),
|
||||
//! projection (one hex digit the digest is filled with, 5)
|
||||
|
||||
use std::collections::BTreeMap;
|
||||
use std::fs;
|
||||
use std::path::Path;
|
||||
|
||||
use anyhow::{Context, Result, bail, ensure};
|
||||
use cultcache_rs::{
|
||||
CacheBackingStore, CultCacheEnvelope, DatabaseEntry, SingleFileMessagePackBackingStore,
|
||||
};
|
||||
use cultnet_rs::{
|
||||
GameCultProviderHealthIdentity, GameCultRuntimeCapability,
|
||||
GameCultRuntimePresenceHealthPurpose, GameCultRuntimePresenceHealthRecord,
|
||||
IDUNN_EXPECTED_INCARNATION_SCHEMA, IDUNN_PROCESS_WRITE_LEASE_SCHEMA,
|
||||
IDUNN_RUNTIME_ACTIVATION_SCHEMA, IdunnExpectedCapability, IdunnExpectedDependency,
|
||||
IdunnExpectedIncarnationRecord, IdunnExpectedRoute, IdunnProcessWriteLeaseRecord,
|
||||
IdunnRuntimeActivationLaunch, IdunnRuntimeActivationRecord,
|
||||
IdunnRuntimeActivationSigner, IdunnServiceIdentity, RuntimePresenceAuthenticationContext,
|
||||
authenticate_runtime_presence_claim, correlate_runtime_presence_claim,
|
||||
enroll_service_identity_at, verify_runtime_authority,
|
||||
};
|
||||
|
||||
/// The TypeScript tests pin the same values; drift shows up as a byte mismatch.
|
||||
const OBSERVED_AT: u64 = 1_790_000_000_000;
|
||||
const ISSUED_AT: u64 = OBSERVED_AT - 5_000;
|
||||
const SEQUENCE: u64 = 1;
|
||||
const STORED_AT: &str = "2026-01-01T00:00:00.000Z";
|
||||
|
||||
struct Spec {
|
||||
source_repository: String,
|
||||
detail: String,
|
||||
sets: Vec<Set>,
|
||||
}
|
||||
|
||||
#[derive(Default)]
|
||||
struct Set {
|
||||
dir: String,
|
||||
target: String,
|
||||
transport: String,
|
||||
stable: String,
|
||||
candidate: String,
|
||||
capability: Option<String>,
|
||||
schema: Option<String>,
|
||||
health_contract: Option<String>,
|
||||
minimum_capacity: u32,
|
||||
stateful: bool,
|
||||
state_schema_generation: Option<String>,
|
||||
lease_other_target: Option<String>,
|
||||
dependencies: Vec<IdunnExpectedDependency>,
|
||||
}
|
||||
|
||||
fn expand(args: impl Iterator<Item = String>) -> Result<Vec<String>> {
|
||||
let mut flat = Vec::new();
|
||||
for arg in args {
|
||||
let Some(file) = arg.strip_prefix('@') else {
|
||||
flat.push(arg);
|
||||
continue;
|
||||
};
|
||||
for line in fs::read_to_string(file).with_context(|| format!("reading {file}"))?.lines() {
|
||||
let line = line.trim();
|
||||
if line.is_empty() || line.starts_with('#') {
|
||||
continue;
|
||||
}
|
||||
match line.split_once(char::is_whitespace) {
|
||||
Some((flag, value)) => flat.extend([flag.to_string(), value.trim().to_string()]),
|
||||
None => flat.push(line.to_string()),
|
||||
}
|
||||
}
|
||||
}
|
||||
Ok(flat)
|
||||
}
|
||||
|
||||
fn dependency(text: &str) -> Result<IdunnExpectedDependency> {
|
||||
let mut fields = BTreeMap::new();
|
||||
for pair in text.split(',') {
|
||||
let (key, value) = pair
|
||||
.split_once('=')
|
||||
.with_context(|| format!("dependency field `{pair}` is not key=value"))?;
|
||||
ensure!(fields.insert(key, value).is_none(), "dependency key `{key}` repeated");
|
||||
}
|
||||
let mut take = |key: &str, default: Option<&str>| -> Result<String> {
|
||||
match (fields.remove(key), default) {
|
||||
(Some(value), _) => Ok(value.to_string()),
|
||||
(None, Some(default)) => Ok(default.to_string()),
|
||||
(None, None) => bail!("dependency needs `{key}`"),
|
||||
}
|
||||
};
|
||||
let dependency = IdunnExpectedDependency {
|
||||
kind: take("kind", None)?,
|
||||
capability: take("capability", None)?,
|
||||
schema: take("schema", None)?,
|
||||
compatibility: take("compatibility", Some("v1"))?,
|
||||
minimum_capacity: take("capacity", Some("1"))?.parse()?,
|
||||
startup: take("startup", Some("before-promotion"))?,
|
||||
provider_id: Some(take("provider", None)?),
|
||||
provider_authority: Some(take("authority", Some("managed-incarnation"))?),
|
||||
provider_expected_projection_sha256: Some(digest(
|
||||
take("projection", Some("5"))?.chars().next().context("empty projection")?,
|
||||
)),
|
||||
provider_endpoint: Some(take("endpoint", None)?),
|
||||
};
|
||||
ensure!(fields.is_empty(), "unknown dependency keys {:?}", fields.keys().collect::<Vec<_>>());
|
||||
Ok(dependency)
|
||||
}
|
||||
|
||||
fn parse(args: impl Iterator<Item = String>) -> Result<Spec> {
|
||||
let mut spec = Spec {
|
||||
source_repository: "github.com/GameCult/Example".into(),
|
||||
detail: "route-observation:route-challenge-1".into(),
|
||||
sets: Vec::new(),
|
||||
};
|
||||
let mut args = expand(args)?.into_iter();
|
||||
while let Some(flag) = args.next() {
|
||||
let mut value = || args.next().with_context(|| format!("{flag} needs a value"));
|
||||
match flag.as_str() {
|
||||
"--source-repository" => spec.source_repository = value()?,
|
||||
"--detail" => spec.detail = value()?,
|
||||
"--set" => spec.sets.push(Set { dir: value()?, minimum_capacity: 1, ..Set::default() }),
|
||||
_ => {
|
||||
let set = spec.sets.last_mut().with_context(|| format!("{flag} before any --set"))?;
|
||||
match flag.as_str() {
|
||||
"--target" => set.target = value()?,
|
||||
"--transport" => set.transport = value()?,
|
||||
"--stable" => set.stable = value()?,
|
||||
"--candidate" => set.candidate = value()?,
|
||||
"--capability" => set.capability = Some(value()?),
|
||||
"--schema" => set.schema = Some(value()?),
|
||||
"--health-contract" => set.health_contract = Some(value()?),
|
||||
"--minimum-capacity" => set.minimum_capacity = value()?.parse()?,
|
||||
"--stateful" => set.stateful = true,
|
||||
"--state-schema-generation" => set.state_schema_generation = Some(value()?),
|
||||
"--lease-other-target" => set.lease_other_target = Some(value()?),
|
||||
"--dependency" => set.dependencies.push(dependency(&value()?)?),
|
||||
other => bail!("unknown flag {other}"),
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
ensure!(!spec.sets.is_empty(), "no --set given");
|
||||
for set in &spec.sets {
|
||||
for (name, field) in [
|
||||
("target", &set.target),
|
||||
("transport", &set.transport),
|
||||
("stable", &set.stable),
|
||||
("candidate", &set.candidate),
|
||||
] {
|
||||
ensure!(!field.is_empty(), "set {} needs --{name}", set.dir);
|
||||
}
|
||||
}
|
||||
Ok(spec)
|
||||
}
|
||||
|
||||
fn main() -> Result<()> {
|
||||
let mut args = std::env::args().skip(1);
|
||||
let Some(out) = args.next() else {
|
||||
bail!("usage: idunn_runtime_fixture <out-dir> <spec>... (see the file header)");
|
||||
};
|
||||
let spec = parse(args)?;
|
||||
let machine_id = fs::read_to_string("/etc/machine-id")?;
|
||||
fs::create_dir_all(&out)?;
|
||||
fs::write(Path::new(&out).join("machine-id"), machine_id.trim())?;
|
||||
let idunn = enroll_service_identity_at::<IdunnServiceIdentity>(
|
||||
&Path::new(&out).join("idunn-identity.private"),
|
||||
)?;
|
||||
let idunn_anchor = idunn.trust_anchor()?;
|
||||
fs::remove_file(Path::new(&out).join("idunn-identity.private"))?;
|
||||
let _ = fs::remove_file(Path::new(&out).join("idunn-identity.private.lock"));
|
||||
for set in &spec.sets {
|
||||
build(Path::new(&out).join(&set.dir).as_path(), &spec, set, &idunn, &idunn_anchor)?;
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
|
||||
fn digest(byte: char) -> String {
|
||||
format!("sha256-{}", byte.to_string().repeat(64))
|
||||
}
|
||||
|
||||
fn build(
|
||||
dir: &Path,
|
||||
spec: &Spec,
|
||||
set: &Set,
|
||||
idunn: &cultnet_rs::ServiceIdentitySigner<IdunnServiceIdentity>,
|
||||
idunn_anchor: &cultnet_rs::ServiceIdentityTrustAnchor,
|
||||
) -> Result<()> {
|
||||
fs::create_dir_all(dir)?;
|
||||
let provider_path = dir.join("provider-identity.credential");
|
||||
let provider = enroll_service_identity_at::<GameCultProviderHealthIdentity>(&provider_path)?;
|
||||
let provider_anchor = provider.trust_anchor()?;
|
||||
let _ = fs::remove_file(dir.join("provider-identity.credential.lock"));
|
||||
|
||||
let capability = set.capability.clone().unwrap_or_else(|| format!("{}.api", set.target));
|
||||
let capability_schema = set.schema.clone().unwrap_or_else(|| format!("{capability}.v1"));
|
||||
let expected = IdunnExpectedIncarnationRecord {
|
||||
schema_version: IDUNN_EXPECTED_INCARNATION_SCHEMA.into(),
|
||||
target: set.target.clone(),
|
||||
plan_id: digest('1'),
|
||||
incarnation_id: format!("{}/incarnation-1", set.target),
|
||||
sealed_release_id: digest('2'),
|
||||
source_repository: spec.source_repository.clone(),
|
||||
source_revision: "a".repeat(40),
|
||||
recipe_sha256: digest('3'),
|
||||
runtime_id: format!("{}-yggdrasil", set.target),
|
||||
expected_signer_identity_id: provider_anchor.identity_id.clone(),
|
||||
health_contract: set.health_contract.clone().unwrap_or_else(|| format!("{}.runtime-health", set.target)),
|
||||
artifact_sha256: digest('4'),
|
||||
state_schema_generation: set.stateful.then(|| set.state_schema_generation.clone().unwrap_or_else(|| "state-v1".into())),
|
||||
state_contract_sha256: set.stateful.then(|| digest('7')),
|
||||
write_lease_required: set.stateful,
|
||||
route: Some(IdunnExpectedRoute {
|
||||
route_id: format!("{}-route", set.target),
|
||||
transport: set.transport.clone(),
|
||||
stable_endpoint: set.stable.clone(),
|
||||
candidate_endpoint: set.candidate.clone(),
|
||||
}),
|
||||
capabilities: vec![IdunnExpectedCapability {
|
||||
capability: capability.clone(),
|
||||
schema: capability_schema.clone(),
|
||||
compatibility: "v1".into(),
|
||||
minimum_capacity: set.minimum_capacity,
|
||||
}],
|
||||
dependencies: set.dependencies.clone(),
|
||||
};
|
||||
expected.validate()?;
|
||||
|
||||
let launch = IdunnRuntimeActivationLaunch::issue(&expected, digest('6'), ISSUED_AT, idunn)?;
|
||||
let mut credential = Vec::new();
|
||||
let activation = launch.write_credential(&mut credential)?;
|
||||
ensure!(credential.len() == 32, "activation credential is a 32-byte seed");
|
||||
fs::write(dir.join("activation-key.seed"), &credential)?;
|
||||
let activation_signer = IdunnRuntimeActivationSigner::from_credential_reader(&credential[..])?;
|
||||
|
||||
write_record(
|
||||
&dir.join("expected.cc"),
|
||||
&expected.target,
|
||||
IdunnExpectedIncarnationRecord::TYPE,
|
||||
IDUNN_EXPECTED_INCARNATION_SCHEMA,
|
||||
expected.canonical_bytes()?,
|
||||
)?;
|
||||
write_record(
|
||||
&dir.join("activation.cc"),
|
||||
&expected.target,
|
||||
IdunnRuntimeActivationRecord::TYPE,
|
||||
IDUNN_RUNTIME_ACTIVATION_SCHEMA,
|
||||
activation.canonical_bytes()?,
|
||||
)?;
|
||||
|
||||
let authority =
|
||||
verify_runtime_authority(&expected, &activation, idunn_anchor, &provider_anchor.public_key)?;
|
||||
let sign_vector = |name: &str,
|
||||
state: &str,
|
||||
capacity: u32,
|
||||
sequence: u64,
|
||||
write_lease_sha256: Option<String>,
|
||||
disagreement: Option<&str>|
|
||||
-> Result<String> {
|
||||
let mut presence = GameCultRuntimePresenceHealthRecord {
|
||||
schema_version: cultnet_rs::GAMECULT_RUNTIME_PRESENCE_HEALTH_SCHEMA.into(),
|
||||
target: expected.target.clone(),
|
||||
expected_projection_sha256: activation.expected_projection_sha256.clone(),
|
||||
plan_id: expected.plan_id.clone(),
|
||||
incarnation_id: expected.incarnation_id.clone(),
|
||||
sealed_release_id: expected.sealed_release_id.clone(),
|
||||
activation_witness_sha256: activation.canonical_sha256()?,
|
||||
state_schema_generation: expected.state_schema_generation.clone(),
|
||||
state_contract_sha256: expected.state_contract_sha256.clone(),
|
||||
runtime_id: expected.runtime_id.clone(),
|
||||
runtime_instance_id: activation.runtime_instance_id.clone(),
|
||||
bound_endpoint: Some(set.candidate.clone()),
|
||||
capabilities: vec![GameCultRuntimeCapability {
|
||||
capability: capability.clone(),
|
||||
schema: capability_schema.clone(),
|
||||
compatibility: "v1".into(),
|
||||
capacity,
|
||||
}],
|
||||
health_contract: expected.health_contract.clone(),
|
||||
state: state.into(),
|
||||
detail: spec.detail.clone(),
|
||||
write_lease_sha256,
|
||||
signer_identity_id: provider_anchor.identity_id.clone(),
|
||||
publisher_sequence: sequence,
|
||||
observed_at_unix_millis: OBSERVED_AT,
|
||||
signature_algorithm: "ed25519".into(),
|
||||
signature: Vec::new(),
|
||||
activation_signer_identity_id: activation_signer.identity_id(),
|
||||
activation_signature: Vec::new(),
|
||||
};
|
||||
let proof = presence.canonical_proof_payload()?;
|
||||
presence.signature = provider
|
||||
.sign::<GameCultRuntimePresenceHealthPurpose>(&proof)
|
||||
.signature;
|
||||
presence.activation_signature = activation_signer.sign_presence_proof(&presence)?;
|
||||
let bytes = rmp_serde::to_vec(&presence)?;
|
||||
|
||||
let claim = authenticate_runtime_presence_claim(
|
||||
&bytes,
|
||||
&authority,
|
||||
RuntimePresenceAuthenticationContext {
|
||||
trusted_received_at_unix_millis: OBSERVED_AT + 1_000,
|
||||
maximum_age_millis: 30_000,
|
||||
maximum_future_skew_millis: 0,
|
||||
},
|
||||
)?;
|
||||
let presence_sha256 = claim.signed_presence_sha256().to_string();
|
||||
let correlation = correlate_runtime_presence_claim(claim, &authority)?;
|
||||
let codes: Vec<&str> = correlation
|
||||
.disagreements()
|
||||
.iter()
|
||||
.map(|entry| entry.code.as_str())
|
||||
.collect();
|
||||
match disagreement {
|
||||
None => ensure!(codes.is_empty(), "{name}: unexpected disagreements {codes:?}"),
|
||||
Some(code) => ensure!(codes == [code], "{name}: expected only {code}, got {codes:?}"),
|
||||
}
|
||||
fs::write(dir.join(name), bytes)?;
|
||||
Ok(presence_sha256)
|
||||
};
|
||||
|
||||
if !set.stateful {
|
||||
sign_vector("presence-active.bin", "active", set.minimum_capacity, SEQUENCE, None, None)?;
|
||||
sign_vector("presence-warming.bin", "warming", set.minimum_capacity, SEQUENCE, None, None)?;
|
||||
if set.minimum_capacity > 1 {
|
||||
sign_vector(
|
||||
"presence-active-below-minimum.bin",
|
||||
"active",
|
||||
set.minimum_capacity - 1,
|
||||
SEQUENCE,
|
||||
None,
|
||||
Some("expected-capability-000-capacity"),
|
||||
)?;
|
||||
}
|
||||
return Ok(());
|
||||
}
|
||||
|
||||
// Lease-bound set. The warming vector comes first because the lease names it.
|
||||
let warming_sha256 =
|
||||
sign_vector("presence-warming.bin", "warming", set.minimum_capacity, SEQUENCE, None, None)?;
|
||||
let activation_sha256 = activation.canonical_sha256()?;
|
||||
let lease_for = |target: &str, warming_presence_sha256: &str| IdunnProcessWriteLeaseRecord {
|
||||
schema_version: IDUNN_PROCESS_WRITE_LEASE_SCHEMA.into(),
|
||||
target: target.into(),
|
||||
expected_projection_sha256: activation.expected_projection_sha256.clone(),
|
||||
plan_id: expected.plan_id.clone(),
|
||||
incarnation_id: expected.incarnation_id.clone(),
|
||||
sealed_release_id: expected.sealed_release_id.clone(),
|
||||
activation_witness_sha256: activation_sha256.clone(),
|
||||
state_schema_generation: expected.state_schema_generation.clone().unwrap_or_default(),
|
||||
state_contract_sha256: expected.state_contract_sha256.clone().unwrap_or_default(),
|
||||
runtime_id: expected.runtime_id.clone(),
|
||||
runtime_instance_id: activation.runtime_instance_id.clone(),
|
||||
warming_presence_sha256: warming_presence_sha256.into(),
|
||||
lease_epoch: 1,
|
||||
issued_at_unix_millis: OBSERVED_AT - 1_000,
|
||||
};
|
||||
let other_target_name = set.lease_other_target.clone().unwrap_or_else(|| {
|
||||
spec.sets.iter().map(|other| other.target.clone()).find(|target| *target != set.target).unwrap_or_else(|| format!("{}-other", set.target))
|
||||
});
|
||||
let lease = lease_for(&set.target, &warming_sha256);
|
||||
let other_warming = lease_for(&set.target, &digest('d'));
|
||||
let other_target = lease_for(&other_target_name, &warming_sha256);
|
||||
for (name, record) in [
|
||||
("lease.cc", &lease),
|
||||
("lease-other-warming.cc", &other_warming),
|
||||
("lease-other-target.cc", &other_target),
|
||||
] {
|
||||
let bytes = record.canonical_bytes()?;
|
||||
ensure!(
|
||||
IdunnProcessWriteLeaseRecord::decode_canonical(&bytes)? == *record,
|
||||
"{name}: lease does not round-trip"
|
||||
);
|
||||
write_record(
|
||||
&dir.join(name),
|
||||
&record.target,
|
||||
IdunnProcessWriteLeaseRecord::TYPE,
|
||||
IDUNN_PROCESS_WRITE_LEASE_SCHEMA,
|
||||
bytes,
|
||||
)?;
|
||||
}
|
||||
let lease_sha256 = lease.canonical_sha256()?;
|
||||
for (name, state) in [("presence-active.bin", "active"), ("presence-degraded.bin", "degraded")] {
|
||||
sign_vector(name, state, set.minimum_capacity, SEQUENCE + 1, Some(lease_sha256.clone()), None)?;
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
|
||||
fn write_record(path: &Path, key: &str, kind: &str, schema: &str, payload: Vec<u8>) -> Result<()> {
|
||||
SingleFileMessagePackBackingStore::new(path).push(&CultCacheEnvelope {
|
||||
key: key.into(),
|
||||
r#type: kind.into(),
|
||||
payload,
|
||||
stored_at: STORED_AT.into(),
|
||||
schema_id: Some(schema.into()),
|
||||
})?;
|
||||
let mut lock = path.as_os_str().to_owned();
|
||||
lock.push(".lock");
|
||||
let _ = fs::remove_file(lock);
|
||||
Ok(())
|
||||
}
|
||||
426
packages/cultnet-rs/src/content.rs
Normal file
426
packages/cultnet-rs/src/content.rs
Normal file
|
|
@ -0,0 +1,426 @@
|
|||
//! CultMesh content plane: chunking, hashing, manifest shape and validation, answering one chunk
|
||||
//! request, and verifying a fetched body. Mirrors `CultMeshCdn` (`CultMeshCdn.cs`) and
|
||||
//! `CultMeshLegacyRudpContentServer` (`CultMeshContentSessions.cs`); the two chunk messages are
|
||||
//! `CultNetMessage::ContentChunkRequest`/`ContentChunkResponse` in `contracts.rs`.
|
||||
//!
|
||||
//! This is the only owner of these rules in Rust. A consumer hands `fetch_content` a transport
|
||||
//! closure and gets verified bytes; it never hashes, chunks or validates a manifest itself.
|
||||
|
||||
use anyhow::{Result, anyhow, bail};
|
||||
use serde::{Deserialize, Serialize};
|
||||
use sha2::{Digest, Sha256};
|
||||
|
||||
use crate::CultNetMessage;
|
||||
|
||||
/// One chunk of a packed body. `chunk_hash` is lowercase SHA-256 hex of `payload`.
|
||||
#[derive(Clone, Debug, PartialEq, Eq)]
|
||||
pub struct CultMeshCdnChunk {
|
||||
pub chunk_hash: String,
|
||||
pub payload: Vec<u8>,
|
||||
}
|
||||
|
||||
/// `CultMeshCdnChunkRef`. Encodes as the reference's positional array under every encoder.
|
||||
#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)]
|
||||
#[serde(from = "ChunkRefWire", into = "ChunkRefWire")]
|
||||
pub struct CultMeshCdnChunkRef {
|
||||
pub chunk_hash: String,
|
||||
pub offset: i64,
|
||||
pub size_bytes: i32,
|
||||
pub record_key: String,
|
||||
}
|
||||
|
||||
/// `CultMeshCdnArtifactManifest`. Encodes as the reference's positional array (keys 0-9).
|
||||
#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)]
|
||||
#[serde(from = "ManifestWire", into = "ManifestWire")]
|
||||
pub struct CultMeshCdnArtifactManifest {
|
||||
pub artifact_id: String,
|
||||
pub kind: String,
|
||||
pub version: String,
|
||||
pub content_hash: String,
|
||||
pub size_bytes: i64,
|
||||
pub mime_type: String,
|
||||
pub created_at_utc: String,
|
||||
pub chunks: Vec<CultMeshCdnChunkRef>,
|
||||
pub tags: Vec<String>,
|
||||
/// Caller metadata in wire order. The reference writes a `Dictionary` in insertion order and
|
||||
/// refuses a duplicate key at read, so this keeps the order it was read in and refuses a duplicate.
|
||||
pub metadata: Vec<(String, String)>,
|
||||
}
|
||||
|
||||
// The tuple mirrors: `to_vec_named` would write a map for a named-field struct, but a tuple
|
||||
// struct is an array under every serde encoder.
|
||||
#[derive(Serialize, Deserialize)]
|
||||
struct ChunkRefWire(String, i64, i32, String);
|
||||
|
||||
#[derive(Serialize, Deserialize)]
|
||||
struct ManifestWire(
|
||||
String,
|
||||
String,
|
||||
String,
|
||||
String,
|
||||
i64,
|
||||
String,
|
||||
String,
|
||||
Vec<CultMeshCdnChunkRef>,
|
||||
Vec<String>,
|
||||
#[serde(with = "ordered_map")] Vec<(String, String)>,
|
||||
);
|
||||
|
||||
/// A string map that keeps its key order and refuses a duplicate key, as `Dictionary<string, string>`
|
||||
/// deserialises. `Vec<(String, String)>` is the in-memory shape; the wire shape is a msgpack map.
|
||||
mod ordered_map {
|
||||
use std::fmt;
|
||||
|
||||
use serde::de::{self, MapAccess, Visitor};
|
||||
use serde::{Deserializer, Serializer};
|
||||
|
||||
pub fn serialize<S: Serializer>(pairs: &[(String, String)], serializer: S) -> Result<S::Ok, S::Error> {
|
||||
serializer.collect_map(pairs.iter().map(|(key, value)| (key, value)))
|
||||
}
|
||||
|
||||
pub fn deserialize<'de, D: Deserializer<'de>>(deserializer: D) -> Result<Vec<(String, String)>, D::Error> {
|
||||
struct Pairs;
|
||||
impl<'de> Visitor<'de> for Pairs {
|
||||
type Value = Vec<(String, String)>;
|
||||
|
||||
fn expecting(&self, formatter: &mut fmt::Formatter) -> fmt::Result {
|
||||
formatter.write_str("a map of strings")
|
||||
}
|
||||
|
||||
fn visit_map<A: MapAccess<'de>>(self, mut map: A) -> Result<Self::Value, A::Error> {
|
||||
let mut seen = std::collections::HashSet::new();
|
||||
let mut pairs = Vec::new();
|
||||
while let Some((key, value)) = map.next_entry::<String, String>()? {
|
||||
if !seen.insert(key.clone()) {
|
||||
return Err(de::Error::custom(format!("duplicate metadata key '{key}'")));
|
||||
}
|
||||
pairs.push((key, value));
|
||||
}
|
||||
Ok(pairs)
|
||||
}
|
||||
}
|
||||
deserializer.deserialize_map(Pairs)
|
||||
}
|
||||
}
|
||||
|
||||
impl From<CultMeshCdnChunkRef> for ChunkRefWire {
|
||||
fn from(value: CultMeshCdnChunkRef) -> Self {
|
||||
Self(value.chunk_hash, value.offset, value.size_bytes, value.record_key)
|
||||
}
|
||||
}
|
||||
|
||||
impl From<ChunkRefWire> for CultMeshCdnChunkRef {
|
||||
fn from(value: ChunkRefWire) -> Self {
|
||||
Self {
|
||||
chunk_hash: value.0,
|
||||
offset: value.1,
|
||||
size_bytes: value.2,
|
||||
record_key: value.3,
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
impl From<CultMeshCdnArtifactManifest> for ManifestWire {
|
||||
fn from(value: CultMeshCdnArtifactManifest) -> Self {
|
||||
Self(
|
||||
value.artifact_id,
|
||||
value.kind,
|
||||
value.version,
|
||||
value.content_hash,
|
||||
value.size_bytes,
|
||||
value.mime_type,
|
||||
value.created_at_utc,
|
||||
value.chunks,
|
||||
value.tags,
|
||||
value.metadata,
|
||||
)
|
||||
}
|
||||
}
|
||||
|
||||
impl From<ManifestWire> for CultMeshCdnArtifactManifest {
|
||||
fn from(value: ManifestWire) -> Self {
|
||||
Self {
|
||||
artifact_id: value.0,
|
||||
kind: value.1,
|
||||
version: value.2,
|
||||
content_hash: value.3,
|
||||
size_bytes: value.4,
|
||||
mime_type: value.5,
|
||||
created_at_utc: value.6,
|
||||
chunks: value.7,
|
||||
tags: value.8,
|
||||
metadata: value.9,
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
fn sha256_hex(bytes: &[u8]) -> String {
|
||||
format!("{:x}", Sha256::digest(bytes))
|
||||
}
|
||||
|
||||
fn chunk_record_key(hash: &str) -> String {
|
||||
format!("mesh:cdn:chunk:{hash}")
|
||||
}
|
||||
|
||||
/// `CultMeshCdn.NormalizeHash`: an optional case-insensitive `sha256:` prefix is stripped, then the
|
||||
/// rest is trimmed and lowercased. A blank hash is refused.
|
||||
pub fn normalize_hash(hash: &str) -> Result<String> {
|
||||
if hash.trim().is_empty() {
|
||||
bail!("Hash must be non-empty.");
|
||||
}
|
||||
let stripped = match hash.get(..7) {
|
||||
Some(prefix) if prefix.eq_ignore_ascii_case("sha256:") => &hash[7..],
|
||||
_ => hash,
|
||||
};
|
||||
Ok(stripped.trim().to_lowercase())
|
||||
}
|
||||
|
||||
/// A hash the client will put on the wire or compare against: normalized and not empty.
|
||||
fn non_empty_hash(hash: &str) -> Result<String> {
|
||||
let normalized = normalize_hash(hash)?;
|
||||
if normalized.is_empty() {
|
||||
bail!("Hash must be non-empty.");
|
||||
}
|
||||
Ok(normalized)
|
||||
}
|
||||
|
||||
/// `CultMeshCdn.PackArtifact`: splits `bytes` into content-addressed chunks and builds the manifest.
|
||||
/// An empty body packs as one zero-length chunk, as the reference does.
|
||||
pub fn pack_content(
|
||||
artifact_id: &str,
|
||||
kind: &str,
|
||||
version: &str,
|
||||
mime_type: &str,
|
||||
created_at_utc: &str,
|
||||
bytes: &[u8],
|
||||
chunk_size: usize,
|
||||
) -> Result<(CultMeshCdnArtifactManifest, Vec<CultMeshCdnChunk>)> {
|
||||
if artifact_id.trim().is_empty() {
|
||||
bail!("Artifact id must be non-empty.");
|
||||
}
|
||||
if chunk_size == 0 || i32::try_from(chunk_size).is_err() {
|
||||
bail!("ChunkSizeBytes must be greater than zero and fit in an int.");
|
||||
}
|
||||
let pieces: Vec<&[u8]> = if bytes.is_empty() {
|
||||
vec![bytes]
|
||||
} else {
|
||||
bytes.chunks(chunk_size).collect()
|
||||
};
|
||||
let mut offset = 0i64;
|
||||
let mut chunks = Vec::with_capacity(pieces.len());
|
||||
let mut refs = Vec::with_capacity(pieces.len());
|
||||
for piece in pieces {
|
||||
let chunk_hash = sha256_hex(piece);
|
||||
refs.push(CultMeshCdnChunkRef {
|
||||
record_key: chunk_record_key(&chunk_hash),
|
||||
chunk_hash: chunk_hash.clone(),
|
||||
offset,
|
||||
// A piece is at most `chunk_size` bytes, which fits an i32 (checked above).
|
||||
size_bytes: piece.len() as i32,
|
||||
});
|
||||
offset += piece.len() as i64;
|
||||
chunks.push(CultMeshCdnChunk {
|
||||
chunk_hash,
|
||||
payload: piece.to_vec(),
|
||||
});
|
||||
}
|
||||
let manifest = CultMeshCdnArtifactManifest {
|
||||
artifact_id: artifact_id.to_string(),
|
||||
kind: non_blank_or(kind, "asset"),
|
||||
version: version.to_string(),
|
||||
content_hash: sha256_hex(bytes),
|
||||
size_bytes: bytes.len() as i64,
|
||||
mime_type: non_blank_or(mime_type, "application/octet-stream"),
|
||||
created_at_utc: created_at_utc.to_string(),
|
||||
chunks: refs,
|
||||
tags: Vec::new(),
|
||||
metadata: Vec::new(),
|
||||
};
|
||||
validate_manifest(&manifest)?;
|
||||
Ok((manifest, chunks))
|
||||
}
|
||||
|
||||
fn non_blank_or(value: &str, default: &str) -> String {
|
||||
if value.trim().is_empty() {
|
||||
default.to_string()
|
||||
} else {
|
||||
value.to_string()
|
||||
}
|
||||
}
|
||||
|
||||
/// The chunk list in offset order, as the reference reads it (`OrderBy(chunk => chunk.Offset)`).
|
||||
fn in_offset_order(manifest: &CultMeshCdnArtifactManifest) -> Vec<&CultMeshCdnChunkRef> {
|
||||
let mut refs: Vec<&CultMeshCdnChunkRef> = manifest.chunks.iter().collect();
|
||||
refs.sort_by_key(|chunk| chunk.offset);
|
||||
refs
|
||||
}
|
||||
|
||||
/// `CultMeshCdn.ValidateManifestShape`: non-negative size, chunks contiguous from offset 0 once
|
||||
/// sorted by offset, non-negative chunk sizes, and chunk sizes summing to the manifest size.
|
||||
pub fn validate_manifest(manifest: &CultMeshCdnArtifactManifest) -> Result<()> {
|
||||
if manifest.size_bytes < 0 {
|
||||
bail!("CDN artifact manifest has a negative size.");
|
||||
}
|
||||
let mut expected_offset = 0i64;
|
||||
for chunk in in_offset_order(manifest) {
|
||||
if chunk.offset != expected_offset {
|
||||
bail!("CDN artifact chunks are not contiguous.");
|
||||
}
|
||||
if chunk.size_bytes < 0 {
|
||||
bail!("CDN artifact chunk has a negative size.");
|
||||
}
|
||||
expected_offset = expected_offset
|
||||
.checked_add(i64::from(chunk.size_bytes))
|
||||
.ok_or_else(|| anyhow!("CDN artifact chunk sizes overflow."))?;
|
||||
}
|
||||
if expected_offset != manifest.size_bytes {
|
||||
bail!("CDN artifact chunk sizes do not sum to the manifest size.");
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
|
||||
/// `CultMeshCdn.ValidateChunk`: the chunk's size and full SHA-256 must be what the reference and
|
||||
/// the chunk's own claim say. `ref_hash` is already normalized.
|
||||
fn validate_chunk(
|
||||
ref_hash: &str,
|
||||
ref_size: i32,
|
||||
claimed_hash: &str,
|
||||
claimed_size: i64,
|
||||
payload: &[u8],
|
||||
) -> Result<()> {
|
||||
if i64::try_from(payload.len()).ok() != Some(i64::from(ref_size)) || claimed_size != i64::from(ref_size) {
|
||||
bail!("CDN artifact chunk payload metadata does not match its manifest reference.");
|
||||
}
|
||||
let actual = sha256_hex(payload);
|
||||
if ref_hash != actual || normalize_hash(claimed_hash)? != actual {
|
||||
bail!("CDN artifact chunk hash does not match its payload.");
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
|
||||
/// `CultMeshLegacyRudpContentServer.HandleAsync`, in its validation order: message id, hash
|
||||
/// normalisation, record-key agreement with `mesh:cdn:chunk:<hash>`, lookup, then size and hash of
|
||||
/// what is served. A failure is `found: false` with an empty payload and the reference's
|
||||
/// `<ExceptionKind>: <message>` in `error`; it is never silence. `lookup` takes the normalized hash.
|
||||
pub fn answer_content_chunk_request<'a>(
|
||||
request: &CultNetMessage,
|
||||
lookup: impl Fn(&str) -> Option<&'a [u8]>,
|
||||
) -> CultNetMessage {
|
||||
let CultNetMessage::ContentChunkRequest {
|
||||
message_id,
|
||||
chunk_hash,
|
||||
record_key,
|
||||
expected_size_bytes,
|
||||
} = request
|
||||
else {
|
||||
return CultNetMessage::Error {
|
||||
error: "not a cultmesh.content_chunk_request.v1 message".to_string(),
|
||||
code: None,
|
||||
details: None,
|
||||
};
|
||||
};
|
||||
let served = (|| -> std::result::Result<(String, Vec<u8>), String> {
|
||||
if message_id.trim().is_empty() {
|
||||
return Err("InvalidDataException: Content chunk request requires a message identity.".to_string());
|
||||
}
|
||||
// The handler normalises the wire hash, then `CreateRecordKey` normalises that result again
|
||||
// (and spells its parameter `chunkHash`); the lookup, the size check and the hash check all
|
||||
// use the second result, and the answer echoes the first.
|
||||
let blank = |parameter: &str| format!("ArgumentException: Hash must be non-empty. (Parameter '{parameter}')");
|
||||
let hash = normalize_hash(chunk_hash).map_err(|_| blank("ChunkHash"))?;
|
||||
let canonical = normalize_hash(&hash).map_err(|_| blank("chunkHash"))?;
|
||||
if !record_key.trim().is_empty() && *record_key != chunk_record_key(&canonical) {
|
||||
return Err("InvalidDataException: Content chunk record key disagrees with its content hash.".to_string());
|
||||
}
|
||||
let payload = lookup(&canonical).ok_or_else(|| "FileNotFoundException: Content chunk is not available.".to_string())?;
|
||||
validate_chunk(&canonical, *expected_size_bytes, &canonical, payload.len() as i64, payload)
|
||||
.map_err(|error| format!("InvalidDataException: {error}"))?;
|
||||
Ok((hash, payload.to_vec()))
|
||||
})();
|
||||
match served {
|
||||
Ok((hash, payload)) => CultNetMessage::ContentChunkResponse {
|
||||
message_id: message_id.clone(),
|
||||
found: true,
|
||||
chunk_hash: hash,
|
||||
size_bytes: *expected_size_bytes,
|
||||
payload,
|
||||
error: String::new(),
|
||||
},
|
||||
Err(error) => CultNetMessage::ContentChunkResponse {
|
||||
message_id: message_id.clone(),
|
||||
found: false,
|
||||
chunk_hash: chunk_hash.clone(),
|
||||
size_bytes: 0,
|
||||
payload: Vec::new(),
|
||||
error,
|
||||
},
|
||||
}
|
||||
}
|
||||
|
||||
/// The client half: fetches every chunk of `manifest` through `ask`, one in flight, in offset
|
||||
/// order, and returns the body only after each chunk and then the whole body verify. `max_bytes`
|
||||
/// is checked against the manifest before the first request. `ask` sends a request on the
|
||||
/// caller's session and returns the answer; it owns transport, this function owns verification.
|
||||
pub fn fetch_content(
|
||||
manifest: &CultMeshCdnArtifactManifest,
|
||||
max_bytes: u64,
|
||||
mut ask: impl FnMut(CultNetMessage) -> Result<CultNetMessage>,
|
||||
) -> Result<Vec<u8>> {
|
||||
validate_manifest(manifest)?;
|
||||
if manifest.size_bytes as u64 > max_bytes {
|
||||
bail!(
|
||||
"CDN artifact of {} bytes exceeds the {max_bytes}-byte cap.",
|
||||
manifest.size_bytes
|
||||
);
|
||||
}
|
||||
// Everything the client will send or compare is settled before the first request. A zero-size
|
||||
// chunk is legal only as an empty body's single chunk (the reference packs it so); anywhere else
|
||||
// it is a request that yields nothing, and a manifest of them is a request flood.
|
||||
let ordered = in_offset_order(manifest);
|
||||
if ordered.len() > 1 && ordered.iter().any(|chunk| chunk.size_bytes == 0) {
|
||||
bail!("CDN artifact has a zero-size chunk beside other chunks.");
|
||||
}
|
||||
let content_hash = non_empty_hash(&manifest.content_hash)?;
|
||||
let hashes = ordered
|
||||
.iter()
|
||||
.map(|chunk| non_empty_hash(&chunk.chunk_hash))
|
||||
.collect::<Result<Vec<_>>>()?;
|
||||
let mut body = Vec::new();
|
||||
for (chunk, hash) in ordered.into_iter().zip(hashes) {
|
||||
let message_id = uuid::Uuid::new_v4().simple().to_string();
|
||||
let record_key = if chunk.record_key.trim().is_empty() {
|
||||
chunk_record_key(&hash)
|
||||
} else {
|
||||
chunk.record_key.clone()
|
||||
};
|
||||
let answer = ask(CultNetMessage::ContentChunkRequest {
|
||||
message_id: message_id.clone(),
|
||||
chunk_hash: hash.clone(),
|
||||
record_key,
|
||||
expected_size_bytes: chunk.size_bytes,
|
||||
})?;
|
||||
let CultNetMessage::ContentChunkResponse {
|
||||
message_id: answered,
|
||||
found,
|
||||
chunk_hash,
|
||||
size_bytes,
|
||||
payload,
|
||||
error,
|
||||
} = answer
|
||||
else {
|
||||
bail!("chunk '{hash}' was answered with something other than a content chunk response");
|
||||
};
|
||||
if answered != message_id {
|
||||
bail!("chunk '{hash}' was answered for message '{answered}', not '{message_id}'");
|
||||
}
|
||||
if !found {
|
||||
bail!("content provider rejected chunk '{hash}': {error}");
|
||||
}
|
||||
validate_chunk(&hash, chunk.size_bytes, &chunk_hash, i64::from(size_bytes), &payload)?;
|
||||
body.extend_from_slice(&payload);
|
||||
}
|
||||
if sha256_hex(&body) != content_hash {
|
||||
bail!("CDN artifact content hash does not match its manifest.");
|
||||
}
|
||||
Ok(body)
|
||||
}
|
||||
|
|
@ -250,7 +250,7 @@ impl CultNetShardDescriptor {
|
|||
}
|
||||
}
|
||||
|
||||
/// Machine-readable `cultnet.error.v0` refusal code (R-N). Mirrors the four strings
|
||||
/// Machine-readable `cultnet.error.v0` refusal code (R-N). Mirrors the five strings
|
||||
/// `contracts/cultnet/cultnet.error.schema.json` enumerates for `code`; a peer that receives a fifth
|
||||
/// string it does not know refuses to decode rather than guess a meaning for it.
|
||||
#[derive(Clone, Copy, Debug, PartialEq, Eq, Serialize, Deserialize)]
|
||||
|
|
@ -260,6 +260,7 @@ pub enum CultNetErrorCode {
|
|||
CursorStale,
|
||||
CursorInvalid,
|
||||
ReferenceOutsideTarget,
|
||||
VariantUnsupported,
|
||||
}
|
||||
|
||||
impl CultNetErrorCode {
|
||||
|
|
@ -269,6 +270,7 @@ impl CultNetErrorCode {
|
|||
Self::CursorStale => "cursor_stale",
|
||||
Self::CursorInvalid => "cursor_invalid",
|
||||
Self::ReferenceOutsideTarget => "reference_outside_target",
|
||||
Self::VariantUnsupported => "variant_unsupported",
|
||||
}
|
||||
}
|
||||
|
||||
|
|
@ -278,6 +280,7 @@ impl CultNetErrorCode {
|
|||
"cursor_stale" => Ok(Self::CursorStale),
|
||||
"cursor_invalid" => Ok(Self::CursorInvalid),
|
||||
"reference_outside_target" => Ok(Self::ReferenceOutsideTarget),
|
||||
"variant_unsupported" => Ok(Self::VariantUnsupported),
|
||||
other => Err(anyhow!("ErrorMessage.Code {other:?} is not a recognized cultnet.error.v0 code")),
|
||||
}
|
||||
}
|
||||
|
|
@ -508,6 +511,26 @@ pub enum CultNetMessage {
|
|||
#[serde(default, skip_serializing_if = "Option::is_none")]
|
||||
source_runtime_id: Option<String>,
|
||||
},
|
||||
/// `cultmesh.content_chunk_request.v1`. Mirrors `CultMeshContentChunkRequestMessage`; raw path.
|
||||
#[serde(rename = "cultmesh.content_chunk_request.v1", rename_all = "camelCase")]
|
||||
ContentChunkRequest {
|
||||
message_id: String,
|
||||
chunk_hash: String,
|
||||
record_key: String,
|
||||
expected_size_bytes: i32,
|
||||
},
|
||||
/// `cultmesh.content_chunk_response.v1`. Mirrors `CultMeshContentChunkResponseMessage`. `payload`
|
||||
/// is `bin`, so it travels the raw path; the serde attribute never runs on the wire.
|
||||
#[serde(rename = "cultmesh.content_chunk_response.v1", rename_all = "camelCase")]
|
||||
ContentChunkResponse {
|
||||
message_id: String,
|
||||
found: bool,
|
||||
chunk_hash: String,
|
||||
size_bytes: i32,
|
||||
#[serde(with = "serde_bytes")]
|
||||
payload: Vec<u8>,
|
||||
error: String,
|
||||
},
|
||||
}
|
||||
|
||||
fn messagepack_base64_encoding() -> String {
|
||||
|
|
@ -529,6 +552,8 @@ pub fn parse_cultnet_message(
|
|||
"cultnet.document_put_raw.v0"
|
||||
| "cultnet.snapshot_response_raw.v0"
|
||||
| "cultnet.snapshot_response_raw.v1"
|
||||
| "cultmesh.content_chunk_request.v1"
|
||||
| "cultmesh.content_chunk_response.v1"
|
||||
| "cultnet.error.v0",
|
||||
) => parse_raw_cultnet_schema_message(wire_value)?,
|
||||
_ => {
|
||||
|
|
@ -553,6 +578,8 @@ pub fn encode_cultnet_message_for_wire(
|
|||
CultNetMessage::DocumentPutRaw { .. }
|
||||
| CultNetMessage::SnapshotResponseRaw { .. }
|
||||
| CultNetMessage::SnapshotResponseRawV1 { .. }
|
||||
| CultNetMessage::ContentChunkRequest { .. }
|
||||
| CultNetMessage::ContentChunkResponse { .. }
|
||||
| CultNetMessage::Error { .. } => encode_raw_cultnet_schema_message(message),
|
||||
_ => Ok(rmp_serde::from_slice(&rmp_serde::to_vec(
|
||||
&serde_json::to_value(message)?,
|
||||
|
|
@ -777,6 +804,10 @@ fn validate_message(message: &CultNetMessage) -> Result<()> {
|
|||
validate_shard_descriptor(shard)?;
|
||||
}
|
||||
}
|
||||
// The reference's serializer accepts any content chunk message. It refuses a bad request in
|
||||
// its handler and answers `found: false` (`answer_content_chunk_request`); a bad response is
|
||||
// refused by `fetch_content`'s verification. Refusing either here would leave a peer in silence.
|
||||
CultNetMessage::ContentChunkRequest { .. } | CultNetMessage::ContentChunkResponse { .. } => {}
|
||||
CultNetMessage::OperationRequest {
|
||||
message_id,
|
||||
service_id,
|
||||
|
|
@ -1044,6 +1075,23 @@ fn parse_raw_cultnet_schema_message(input: &rmpv::Value) -> Result<CultNetMessag
|
|||
)?,
|
||||
})
|
||||
}
|
||||
"cultmesh.content_chunk_request.v1" => Ok(CultNetMessage::ContentChunkRequest {
|
||||
message_id: legacy_string_or_nil(get("messageId"), "messageId")?,
|
||||
chunk_hash: legacy_string_or_nil(get("chunkHash"), "chunkHash")?,
|
||||
record_key: legacy_string_or_nil(get("recordKey"), "recordKey")?,
|
||||
expected_size_bytes: require_legacy_i32(get("expectedSizeBytes"), "expectedSizeBytes")?,
|
||||
}),
|
||||
"cultmesh.content_chunk_response.v1" => Ok(CultNetMessage::ContentChunkResponse {
|
||||
message_id: require_legacy_string(get("messageId"), "messageId")?,
|
||||
found: require_legacy_bool(get("found"), "found")?,
|
||||
chunk_hash: require_legacy_string(get("chunkHash"), "chunkHash")?,
|
||||
size_bytes: require_legacy_i32(get("sizeBytes"), "sizeBytes")?,
|
||||
payload: get("payload")
|
||||
.and_then(rmpv::Value::as_slice)
|
||||
.ok_or_else(|| anyhow!("payload must be binary data"))?
|
||||
.to_vec(),
|
||||
error: require_legacy_string(get("error"), "error")?,
|
||||
}),
|
||||
"cultnet.error.v0" => {
|
||||
let code = get("code")
|
||||
.filter(|value| !value.is_nil())
|
||||
|
|
@ -1209,6 +1257,43 @@ fn encode_raw_cultnet_schema_message(message: &CultNetMessage) -> Result<rmpv::V
|
|||
.unwrap_or(rmpv::Value::Nil),
|
||||
),
|
||||
],
|
||||
CultNetMessage::ContentChunkRequest {
|
||||
message_id,
|
||||
chunk_hash,
|
||||
record_key,
|
||||
expected_size_bytes,
|
||||
} => vec![
|
||||
(
|
||||
rmpv::Value::from("schemaVersion"),
|
||||
rmpv::Value::from("cultmesh.content_chunk_request.v1"),
|
||||
),
|
||||
(rmpv::Value::from("messageId"), rmpv::Value::from(message_id.as_str())),
|
||||
(rmpv::Value::from("chunkHash"), rmpv::Value::from(chunk_hash.as_str())),
|
||||
(rmpv::Value::from("recordKey"), rmpv::Value::from(record_key.as_str())),
|
||||
(
|
||||
rmpv::Value::from("expectedSizeBytes"),
|
||||
rmpv::Value::from(*expected_size_bytes),
|
||||
),
|
||||
],
|
||||
CultNetMessage::ContentChunkResponse {
|
||||
message_id,
|
||||
found,
|
||||
chunk_hash,
|
||||
size_bytes,
|
||||
payload,
|
||||
error,
|
||||
} => vec![
|
||||
(
|
||||
rmpv::Value::from("schemaVersion"),
|
||||
rmpv::Value::from("cultmesh.content_chunk_response.v1"),
|
||||
),
|
||||
(rmpv::Value::from("messageId"), rmpv::Value::from(message_id.as_str())),
|
||||
(rmpv::Value::from("found"), rmpv::Value::from(*found)),
|
||||
(rmpv::Value::from("chunkHash"), rmpv::Value::from(chunk_hash.as_str())),
|
||||
(rmpv::Value::from("sizeBytes"), rmpv::Value::from(*size_bytes)),
|
||||
(rmpv::Value::from("payload"), rmpv::Value::Binary(payload.clone())),
|
||||
(rmpv::Value::from("error"), rmpv::Value::from(error.as_str())),
|
||||
],
|
||||
// R-N: matches the landed C# `CultNetErrorMessage`
|
||||
// (src/GameCult.Networking/CultNetSchemaMessages.cs) key for key and in its declared
|
||||
// order - schemaVersion, error, routingHint, code, details - with every optional key
|
||||
|
|
@ -1422,6 +1507,13 @@ fn require_legacy_u32(value: Option<&rmpv::Value>, field_name: &str) -> Result<u
|
|||
u32::try_from(number).map_err(|_| anyhow!("{field_name} does not fit in u32"))
|
||||
}
|
||||
|
||||
fn require_legacy_i32(value: Option<&rmpv::Value>, field_name: &str) -> Result<i32> {
|
||||
let number = value
|
||||
.and_then(rmpv::Value::as_i64)
|
||||
.ok_or_else(|| anyhow!("{field_name} must be an integer"))?;
|
||||
i32::try_from(number).map_err(|_| anyhow!("{field_name} does not fit in i32"))
|
||||
}
|
||||
|
||||
fn require_legacy_u64(value: Option<&rmpv::Value>, field_name: &str) -> Result<u64> {
|
||||
value
|
||||
.and_then(rmpv::Value::as_u64)
|
||||
|
|
@ -1632,6 +1724,15 @@ fn require_legacy_bytes(value: Option<&rmpv::Value>, field_name: &str) -> Result
|
|||
Ok(URL_SAFE_NO_PAD.encode(bytes))
|
||||
}
|
||||
|
||||
/// A string the reference reads back as null when its writer set it to null (msgpack nil), which its
|
||||
/// handlers treat as blank. Only content chunk requests use it: they are answered, never dropped.
|
||||
fn legacy_string_or_nil(value: Option<&rmpv::Value>, field_name: &str) -> Result<String> {
|
||||
match value {
|
||||
Some(rmpv::Value::Nil) => Ok(String::new()),
|
||||
other => require_legacy_string(other, field_name),
|
||||
}
|
||||
}
|
||||
|
||||
fn require_legacy_string(value: Option<&rmpv::Value>, field_name: &str) -> Result<String> {
|
||||
let value = value
|
||||
.and_then(rmpv::Value::as_str)
|
||||
|
|
|
|||
|
|
@ -1,3 +1,4 @@
|
|||
mod content;
|
||||
mod contracts;
|
||||
mod idunn_deployment_brake;
|
||||
mod idunn_lifecycle_brake;
|
||||
|
|
@ -19,6 +20,7 @@ mod selection;
|
|||
mod shard_catalog;
|
||||
mod transport;
|
||||
|
||||
pub use content::*;
|
||||
pub use contracts::*;
|
||||
pub use idunn_deployment_brake::*;
|
||||
pub use idunn_lifecycle_brake::*;
|
||||
|
|
|
|||
806
packages/cultnet-rs/tests/content.rs
Normal file
806
packages/cultnet-rs/tests/content.rs
Normal file
|
|
@ -0,0 +1,806 @@
|
|||
//! The content plane (`src/content.rs`, the two chunk messages in `src/contracts.rs`), pinned against
|
||||
//! the C# reference. `contracts/cultmesh/content-vectors.cs-written.json` is the reference's own
|
||||
//! bytes (written by `CultMeshContentVectorTests`, including the answers `CultMeshLegacyRudpContentServer`
|
||||
//! gives); `content-vectors.rs-written.json` is this binary's mirror, regenerated with
|
||||
//! `CULTNET_WRITE_VECTORS=1`, and judged by the C# side.
|
||||
|
||||
use std::collections::HashMap;
|
||||
use std::path::{Path, PathBuf};
|
||||
|
||||
use anyhow::Result;
|
||||
use base64::Engine;
|
||||
use cultnet_rs::{
|
||||
CultMeshCdnArtifactManifest, CultNetMessage, CultNetWireContract, answer_content_chunk_request,
|
||||
decode_cultnet_message_from_slice, encode_cultnet_message_for_wire, encode_cultnet_message_to_vec,
|
||||
fetch_content, normalize_hash, pack_content, validate_manifest,
|
||||
};
|
||||
use serde::{Deserialize, Serialize};
|
||||
|
||||
const CHUNK: usize = 262_144;
|
||||
const BODY_LEN: usize = 1_315_551;
|
||||
const CREATED: &str = "2026-09-22T00:00:00.0000000+00:00";
|
||||
const SCHEMA_V0: CultNetWireContract = CultNetWireContract::CultNetSchemaV0;
|
||||
|
||||
fn body() -> Vec<u8> {
|
||||
(0..BODY_LEN).map(|i| (i % 251) as u8).collect()
|
||||
}
|
||||
|
||||
fn pack(bytes: &[u8]) -> (CultMeshCdnArtifactManifest, Vec<cultnet_rs::CultMeshCdnChunk>) {
|
||||
pack_content(
|
||||
"eureka/content-vector",
|
||||
"asset",
|
||||
"1",
|
||||
"application/x-cultnet-vector",
|
||||
CREATED,
|
||||
bytes,
|
||||
CHUNK,
|
||||
)
|
||||
.expect("packs")
|
||||
}
|
||||
|
||||
fn store(chunks: &[cultnet_rs::CultMeshCdnChunk]) -> HashMap<String, Vec<u8>> {
|
||||
chunks
|
||||
.iter()
|
||||
.map(|chunk| (chunk.chunk_hash.clone(), chunk.payload.clone()))
|
||||
.collect()
|
||||
}
|
||||
|
||||
fn lookup_in<'a>(store: &'a HashMap<String, Vec<u8>>) -> impl Fn(&str) -> Option<&'a [u8]> {
|
||||
move |hash| store.get(hash).map(Vec::as_slice)
|
||||
}
|
||||
|
||||
fn wire(message: &CultNetMessage) -> Vec<u8> {
|
||||
encode_cultnet_message_to_vec(message, SCHEMA_V0).expect("encodes")
|
||||
}
|
||||
|
||||
fn unwire(bytes: &[u8]) -> Result<CultNetMessage> {
|
||||
decode_cultnet_message_from_slice(bytes, SCHEMA_V0)
|
||||
}
|
||||
|
||||
fn manifest_bytes(manifest: &CultMeshCdnArtifactManifest) -> Vec<u8> {
|
||||
rmp_serde::to_vec_named(manifest).expect("encodes")
|
||||
}
|
||||
|
||||
fn decode_manifest(bytes: &[u8]) -> CultMeshCdnArtifactManifest {
|
||||
rmp_serde::from_slice(bytes).expect("decodes")
|
||||
}
|
||||
|
||||
/// The manifest's bytes with its metadata map replaced by `pairs`, written in exactly that order
|
||||
/// (and with duplicates, if given): what a peer that is not this crate can put on the wire.
|
||||
fn manifest_with_metadata(manifest: &CultMeshCdnArtifactManifest, pairs: &[(&str, &str)]) -> Vec<u8> {
|
||||
let encoded = manifest_bytes(manifest);
|
||||
let mut value = rmpv::decode::read_value(&mut encoded.as_slice()).expect("a msgpack value");
|
||||
let rmpv::Value::Array(fields) = &mut value else {
|
||||
panic!("the manifest is a positional array");
|
||||
};
|
||||
fields[9] = rmpv::Value::Map(pairs.iter().map(|(k, v)| (rmpv::Value::from(*k), rmpv::Value::from(*v))).collect());
|
||||
let mut out = Vec::new();
|
||||
rmpv::encode::write_value(&mut out, &value).expect("writes");
|
||||
out
|
||||
}
|
||||
|
||||
fn request(id: &str, hash: &str, key: &str, size: i32) -> CultNetMessage {
|
||||
CultNetMessage::ContentChunkRequest {
|
||||
message_id: id.to_string(),
|
||||
chunk_hash: hash.to_string(),
|
||||
record_key: key.to_string(),
|
||||
expected_size_bytes: size,
|
||||
}
|
||||
}
|
||||
|
||||
fn response_of(message: &CultNetMessage) -> (&str, bool, &str, &[u8], &str) {
|
||||
match message {
|
||||
CultNetMessage::ContentChunkResponse {
|
||||
message_id,
|
||||
found,
|
||||
chunk_hash,
|
||||
payload,
|
||||
error,
|
||||
..
|
||||
} => (message_id, *found, chunk_hash, payload, error),
|
||||
other => panic!("not a content chunk response: {other:?}"),
|
||||
}
|
||||
}
|
||||
|
||||
/// A transport closure that answers from `chunks` through the wire, counting calls.
|
||||
fn serving<'a>(
|
||||
chunks: &'a HashMap<String, Vec<u8>>,
|
||||
calls: &'a std::cell::Cell<usize>,
|
||||
) -> impl FnMut(CultNetMessage) -> Result<CultNetMessage> + 'a {
|
||||
move |message| {
|
||||
calls.set(calls.get() + 1);
|
||||
let request = unwire(&wire(&message))?;
|
||||
unwire(&wire(&answer_content_chunk_request(&request, lookup_in(chunks))))
|
||||
}
|
||||
}
|
||||
|
||||
fn flip_last_digit(hash: &str) -> String {
|
||||
let last = if hash.ends_with('0') { '1' } else { '0' };
|
||||
format!("{}{last}", &hash[..hash.len() - 1])
|
||||
}
|
||||
|
||||
// ------------------------------------------------------------------------------------------
|
||||
// Vector files
|
||||
// ------------------------------------------------------------------------------------------
|
||||
|
||||
#[derive(Serialize, Deserialize)]
|
||||
struct VectorFile {
|
||||
vectors: Vec<VectorEntry>,
|
||||
}
|
||||
|
||||
#[derive(Serialize, Deserialize)]
|
||||
struct VectorEntry {
|
||||
label: String,
|
||||
kind: String,
|
||||
#[serde(rename = "messagePackBase64")]
|
||||
message_pack_base64: String,
|
||||
}
|
||||
|
||||
struct Vector {
|
||||
label: String,
|
||||
kind: &'static str,
|
||||
bytes: Vec<u8>,
|
||||
}
|
||||
|
||||
fn vector_path(name: &str) -> PathBuf {
|
||||
Path::new(env!("CARGO_MANIFEST_DIR"))
|
||||
.join("..")
|
||||
.join("..")
|
||||
.join("contracts")
|
||||
.join("cultmesh")
|
||||
.join(name)
|
||||
}
|
||||
|
||||
fn read_vectors(name: &str) -> Vec<(String, String, Vec<u8>)> {
|
||||
let path = vector_path(name);
|
||||
let text = std::fs::read_to_string(&path).unwrap_or_else(|_| {
|
||||
panic!("{} is missing - write it first (CULTNET_WRITE_VECTORS=1)", path.display())
|
||||
});
|
||||
let file: VectorFile = serde_json::from_str(&text).expect("vector file parses");
|
||||
assert!(!file.vectors.is_empty(), "the vector file must carry at least one vector");
|
||||
file.vectors
|
||||
.into_iter()
|
||||
.map(|v| {
|
||||
let bytes = base64::engine::general_purpose::STANDARD
|
||||
.decode(&v.message_pack_base64)
|
||||
.expect("base64");
|
||||
(v.label, v.kind, bytes)
|
||||
})
|
||||
.collect()
|
||||
}
|
||||
|
||||
/// The vectors this runtime writes: the same labelled set the C# writer produces, built from Rust
|
||||
/// values and answered by Rust's `answer_content_chunk_request`.
|
||||
fn local_vectors() -> Vec<Vector> {
|
||||
let (manifest, chunks) = pack(&body());
|
||||
let store = store(&chunks);
|
||||
let last = chunks.last().expect("chunks");
|
||||
let last_size = last.payload.len() as i32;
|
||||
let key = format!("mesh:cdn:chunk:{}", last.chunk_hash);
|
||||
let mut vectors = Vec::new();
|
||||
let mut push_message = |label: String, kind: &'static str, message: &CultNetMessage| {
|
||||
vectors.push(Vector { label, kind, bytes: wire(message) });
|
||||
};
|
||||
let answers = [
|
||||
("answer_found", request("vector-found", &format!("SHA256:{}", last.chunk_hash), &key, last_size)),
|
||||
("answer_not_found", request("vector-missing", &"0".repeat(64), "", 100)),
|
||||
(
|
||||
"answer_record_key_disagrees",
|
||||
request("vector-key", &last.chunk_hash, "mesh:cdn:chunk:other", last_size),
|
||||
),
|
||||
("answer_size_mismatch", request("vector-size", &last.chunk_hash, &key, last_size - 1)),
|
||||
("answer_blank_message_id", request("", &last.chunk_hash, &key, last_size)),
|
||||
("answer_whitespace_message_id", request(" ", &last.chunk_hash, &key, last_size)),
|
||||
("answer_blank_hash", request("vector-blank-hash", "", "", 100)),
|
||||
("answer_whitespace_hash", request("vector-space-hash", " ", "", 100)),
|
||||
("answer_prefix_only_hash", request("vector-prefix-hash", "sha256: ", "", 100)),
|
||||
("answer_negative_size", request("vector-negative", &last.chunk_hash, &key, -1)),
|
||||
(
|
||||
"answer_record_key_case",
|
||||
request("vector-key-case", &last.chunk_hash, &key.to_uppercase(), last_size),
|
||||
),
|
||||
("answer_blank_record_key", request("vector-key-blank", &last.chunk_hash, " ", last_size)),
|
||||
(
|
||||
"answer_double_prefix",
|
||||
request("vector-double", &format!("sha256:sha256:{}", last.chunk_hash), "", last_size),
|
||||
),
|
||||
];
|
||||
for (name, request) in &answers {
|
||||
push_message(format!("{name}.request"), "request", request);
|
||||
let answer = answer_content_chunk_request(request, lookup_in(&store));
|
||||
push_message(format!("{name}.response"), "response", &answer);
|
||||
}
|
||||
push_message(
|
||||
"response_hash_last_digit".to_string(),
|
||||
"response",
|
||||
&CultNetMessage::ContentChunkResponse {
|
||||
message_id: "vector-digit".to_string(),
|
||||
found: true,
|
||||
chunk_hash: flip_last_digit(&last.chunk_hash),
|
||||
size_bytes: last_size,
|
||||
payload: last.payload.clone(),
|
||||
error: String::new(),
|
||||
},
|
||||
);
|
||||
let mut push_manifest = |label: &str, manifest: &CultMeshCdnArtifactManifest| {
|
||||
vectors.push(Vector {
|
||||
label: label.to_string(),
|
||||
kind: "manifest",
|
||||
bytes: manifest_bytes(manifest),
|
||||
});
|
||||
};
|
||||
push_manifest("manifest", &manifest);
|
||||
let mut shuffled = manifest.clone();
|
||||
shuffled.chunks = [3, 0, 5, 1, 4, 2].iter().map(|&i| manifest.chunks[i].clone()).collect();
|
||||
push_manifest("manifest_out_of_order", &shuffled);
|
||||
let tagged = decode_manifest(&manifest_with_metadata(&manifest, &[("zeta", "1"), ("alpha", "2"), ("mid", "3")]));
|
||||
push_manifest("manifest_metadata_order", &tagged);
|
||||
push_manifest("manifest_empty_body", &pack(&[]).0);
|
||||
vectors
|
||||
}
|
||||
|
||||
fn to_json(vectors: &[Vector]) -> String {
|
||||
let file = VectorFile {
|
||||
vectors: vectors
|
||||
.iter()
|
||||
.map(|v| VectorEntry {
|
||||
label: v.label.clone(),
|
||||
kind: v.kind.to_string(),
|
||||
message_pack_base64: base64::engine::general_purpose::STANDARD.encode(&v.bytes),
|
||||
})
|
||||
.collect(),
|
||||
};
|
||||
serde_json::to_string_pretty(&file).expect("serializes")
|
||||
}
|
||||
|
||||
/// The committed rs-written file is what this binary encodes now. Under `CULTNET_WRITE_VECTORS=1`
|
||||
/// it is rewritten instead, for the C# test `RustVectorsDecodeInTheReference` to judge.
|
||||
#[test]
|
||||
fn rust_written_vectors_are_current() {
|
||||
let fresh = local_vectors();
|
||||
let path = vector_path("content-vectors.rs-written.json");
|
||||
if std::env::var("CULTNET_WRITE_VECTORS").as_deref() == Ok("1") {
|
||||
std::fs::write(&path, to_json(&fresh)).expect("writes the vector file");
|
||||
return;
|
||||
}
|
||||
let committed = read_vectors("content-vectors.rs-written.json");
|
||||
assert_eq!(committed.len(), fresh.len());
|
||||
for ((label, kind, bytes), fresh) in committed.iter().zip(&fresh) {
|
||||
assert_eq!((label.as_str(), kind.as_str()), (fresh.label.as_str(), fresh.kind));
|
||||
assert_eq!(bytes, &fresh.bytes, "vector '{label}' drifted from this binary's encode");
|
||||
}
|
||||
}
|
||||
|
||||
/// Byte identity, both ways, against the reference's own bytes: every vector the reference wrote
|
||||
/// decodes here and this runtime's independently built value encodes to exactly those bytes. The
|
||||
/// manifest vector also pins `pack_content` (same body and options, same manifest, byte for byte).
|
||||
#[test]
|
||||
fn reference_vectors_encode_byte_identically() {
|
||||
let local = local_vectors();
|
||||
// The nil-field vectors are bytes only the reference writes; `nil_fields_are_answered_as_blanks` judges them.
|
||||
let reference: Vec<_> = read_vectors("content-vectors.cs-written.json")
|
||||
.into_iter()
|
||||
.filter(|(label, _, _)| !label.starts_with("nil_"))
|
||||
.collect();
|
||||
assert_eq!(
|
||||
reference.iter().map(|(l, _, _)| l.as_str()).collect::<Vec<_>>(),
|
||||
local.iter().map(|v| v.label.as_str()).collect::<Vec<_>>(),
|
||||
"both runtimes write the same labelled vectors"
|
||||
);
|
||||
for ((label, kind, reference_bytes), mine) in reference.iter().zip(&local) {
|
||||
assert_eq!(reference_bytes, &mine.bytes, "vector '{label}' is not byte identical");
|
||||
match kind.as_str() {
|
||||
"request" | "response" => {
|
||||
let decoded = unwire(reference_bytes).expect("the reference's bytes decode");
|
||||
assert_eq!(&wire(&decoded), reference_bytes, "vector '{label}' does not re-encode identically");
|
||||
}
|
||||
"manifest" => {
|
||||
let decoded: CultMeshCdnArtifactManifest =
|
||||
rmp_serde::from_slice(reference_bytes).expect("the reference's manifest decodes");
|
||||
assert_eq!(&manifest_bytes(&decoded), reference_bytes, "manifest '{label}' does not re-encode identically");
|
||||
}
|
||||
other => panic!("unknown vector kind {other}"),
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// F1's failure mode: a chunk response carries `bin`, which the JSON-value path cannot carry.
|
||||
#[test]
|
||||
fn a_chunk_response_carries_bin_through_the_raw_path() {
|
||||
let payload: Vec<u8> = (0..=255u8).collect();
|
||||
let message = CultNetMessage::ContentChunkResponse {
|
||||
message_id: "m".to_string(),
|
||||
found: true,
|
||||
chunk_hash: "ab".to_string(),
|
||||
size_bytes: 256,
|
||||
payload: payload.clone(),
|
||||
error: String::new(),
|
||||
};
|
||||
let wire_value = encode_cultnet_message_for_wire(&message, SCHEMA_V0).expect("encodes");
|
||||
let entries = wire_value.as_map().expect("a map");
|
||||
let (_, value) = entries.iter().find(|(k, _)| k.as_str() == Some("payload")).expect("payload key");
|
||||
assert!(matches!(value, rmpv::Value::Binary(bytes) if *bytes == payload), "payload must be bin");
|
||||
assert_eq!(unwire(&wire(&message)).expect("decodes"), message);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn normalize_hash_matches_the_reference() {
|
||||
for (input, expected) in [
|
||||
("SHA256:ABCdef", "abcdef"),
|
||||
("sha256:abc", "abc"),
|
||||
("sha256: ABC ", "abc"),
|
||||
(" ABC ", "abc"),
|
||||
(" sha256:abc", "sha256:abc"),
|
||||
("sha256:", ""),
|
||||
("plain", "plain"),
|
||||
] {
|
||||
assert_eq!(normalize_hash(input).expect("normalizes"), expected, "input {input:?}");
|
||||
}
|
||||
for blank in ["", " "] {
|
||||
assert!(normalize_hash(blank).is_err(), "{blank:?} must be refused");
|
||||
}
|
||||
// The fixture's uppercase-prefix request names the same chunk as its bare hash.
|
||||
let reference = read_vectors("content-vectors.cs-written.json");
|
||||
let (_, _, bytes) = reference.iter().find(|(l, _, _)| l == "answer_found.request").expect("vector");
|
||||
let CultNetMessage::ContentChunkRequest { chunk_hash, .. } = unwire(bytes).expect("decodes") else {
|
||||
panic!("not a request");
|
||||
};
|
||||
assert!(chunk_hash.starts_with("SHA256:"));
|
||||
let (_, chunks) = pack(&body());
|
||||
assert_eq!(normalize_hash(&chunk_hash).expect("normalizes"), chunks.last().unwrap().chunk_hash);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_manifest_out_of_offset_order_is_accepted_as_the_reference_accepts_it() {
|
||||
let reference = read_vectors("content-vectors.cs-written.json");
|
||||
let (_, _, bytes) = reference.iter().find(|(l, _, _)| l == "manifest_out_of_order").expect("vector");
|
||||
let manifest: CultMeshCdnArtifactManifest = rmp_serde::from_slice(bytes).expect("decodes");
|
||||
assert_ne!(manifest.chunks[0].offset, 0, "the fixture's chunk list is shuffled");
|
||||
validate_manifest(&manifest).expect("the reference accepts it");
|
||||
let (_, chunks) = pack(&body());
|
||||
let store = store(&chunks);
|
||||
let calls = std::cell::Cell::new(0);
|
||||
let fetched = fetch_content(&manifest, BODY_LEN as u64, serving(&store, &calls)).expect("fetches");
|
||||
assert_eq!(fetched, body());
|
||||
assert_eq!(calls.get(), 6);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_hostile_manifest_is_refused_before_any_request() {
|
||||
let (good, chunks) = pack(&body());
|
||||
let store = store(&chunks);
|
||||
let mut hostile = Vec::new();
|
||||
let mut negative = good.clone();
|
||||
negative.size_bytes = -1;
|
||||
hostile.push(negative);
|
||||
let mut gap = good.clone();
|
||||
gap.chunks[2].offset += 1;
|
||||
hostile.push(gap);
|
||||
let mut overlap = good.clone();
|
||||
overlap.chunks[3].offset -= 1;
|
||||
hostile.push(overlap);
|
||||
let mut short = good.clone();
|
||||
short.size_bytes -= 1;
|
||||
hostile.push(short);
|
||||
let mut negative_chunk = good.clone();
|
||||
negative_chunk.chunks[5].size_bytes = -4831;
|
||||
hostile.push(negative_chunk);
|
||||
for manifest in hostile {
|
||||
let calls = std::cell::Cell::new(0);
|
||||
assert!(fetch_content(&manifest, u64::MAX, serving(&store, &calls)).is_err());
|
||||
assert_eq!(calls.get(), 0, "a corrupt manifest must not make the client ask");
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_manifest_over_the_cap_is_refused_before_any_request() {
|
||||
let (manifest, chunks) = pack(&body());
|
||||
let store = store(&chunks);
|
||||
let size = BODY_LEN as u64;
|
||||
|
||||
let calls = std::cell::Cell::new(0);
|
||||
let fetched = fetch_content(&manifest, size, serving(&store, &calls)).expect("exactly the cap is accepted");
|
||||
assert_eq!(fetched.len(), BODY_LEN);
|
||||
assert_eq!(calls.get(), 6);
|
||||
|
||||
// One byte over, and sizes where doubling the cap would admit the body.
|
||||
for cap in [size - 1, size / 2 + 1, size / 2, 0] {
|
||||
let calls = std::cell::Cell::new(0);
|
||||
assert!(fetch_content(&manifest, cap, serving(&store, &calls)).is_err(), "cap {cap} must refuse");
|
||||
assert_eq!(calls.get(), 0, "cap {cap} must refuse before any request");
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_chunk_whose_hash_differs_in_the_last_digit_is_refused() {
|
||||
let reference = read_vectors("content-vectors.cs-written.json");
|
||||
let (_, _, bytes) = reference.iter().find(|(l, _, _)| l == "response_hash_last_digit").expect("vector");
|
||||
let CultNetMessage::ContentChunkResponse { chunk_hash: claimed, payload, .. } = unwire(bytes).expect("decodes") else {
|
||||
panic!("not a response");
|
||||
};
|
||||
// A one-chunk manifest for exactly that payload: its bytes are right, only the response's claim is off.
|
||||
let (manifest, chunks) = pack(&payload);
|
||||
let honest = chunks[0].chunk_hash.clone();
|
||||
assert_ne!(claimed, honest);
|
||||
assert_eq!(claimed[..claimed.len() - 1], honest[..honest.len() - 1], "they differ in the last digit only");
|
||||
let error = fetch_content(&manifest, u64::MAX, |message| {
|
||||
let CultNetMessage::ContentChunkRequest { message_id, .. } = message else {
|
||||
panic!("not a request");
|
||||
};
|
||||
let CultNetMessage::ContentChunkResponse { found, size_bytes, payload, error, .. } =
|
||||
unwire(bytes).expect("decodes")
|
||||
else {
|
||||
panic!("not a response");
|
||||
};
|
||||
Ok(CultNetMessage::ContentChunkResponse {
|
||||
message_id,
|
||||
found,
|
||||
chunk_hash: claimed.clone(),
|
||||
size_bytes,
|
||||
payload,
|
||||
error,
|
||||
})
|
||||
})
|
||||
.expect_err("a hash off by one digit is a different hash");
|
||||
assert!(error.to_string().contains("does not match its payload"), "{error}");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_body_whose_chunks_verify_but_whole_hash_does_not_is_refused() {
|
||||
let (mut manifest, chunks) = pack(&body());
|
||||
manifest.content_hash = pack(b"another body").0.content_hash;
|
||||
let store = store(&chunks);
|
||||
let calls = std::cell::Cell::new(0);
|
||||
let error = fetch_content(&manifest, u64::MAX, serving(&store, &calls)).expect_err("whole body must verify");
|
||||
assert_eq!(calls.get(), 6, "every chunk verified; only the whole body is wrong");
|
||||
assert!(error.to_string().contains("content hash"), "{error}");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_response_for_another_message_id_is_refused() {
|
||||
let (manifest, chunks) = pack(&body());
|
||||
let store = store(&chunks);
|
||||
let error = fetch_content(&manifest, u64::MAX, |message| {
|
||||
let mut answer = answer_content_chunk_request(&message, lookup_in(&store));
|
||||
if let CultNetMessage::ContentChunkResponse { message_id, .. } = &mut answer {
|
||||
*message_id = "someone-else".to_string();
|
||||
}
|
||||
Ok(answer)
|
||||
})
|
||||
.expect_err("an answer to another request is not this answer");
|
||||
assert!(error.to_string().contains("someone-else"), "{error}");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn an_empty_body_packs_one_zero_length_chunk_and_fetches() {
|
||||
let (manifest, chunks) = pack(&[]);
|
||||
assert_eq!((manifest.chunks.len(), chunks.len(), manifest.size_bytes), (1, 1, 0));
|
||||
let store = store(&chunks);
|
||||
let calls = std::cell::Cell::new(0);
|
||||
assert_eq!(fetch_content(&manifest, 0, serving(&store, &calls)).expect("fetches"), Vec::<u8>::new());
|
||||
assert_eq!(calls.get(), 1);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn answer_refuses_a_record_key_that_disagrees_with_its_hash() {
|
||||
let (_, chunks) = pack(&body());
|
||||
let store = store(&chunks);
|
||||
let last = chunks.last().unwrap();
|
||||
let asked = std::cell::Cell::new(false);
|
||||
let answer = answer_content_chunk_request(
|
||||
&request("m", &last.chunk_hash, "mesh:cdn:chunk:other", last.payload.len() as i32),
|
||||
|hash| {
|
||||
asked.set(true);
|
||||
lookup_in(&store)(hash)
|
||||
},
|
||||
);
|
||||
let (id, found, _, payload, error) = response_of(&answer);
|
||||
assert_eq!((id, found, payload.len()), ("m", false, 0));
|
||||
assert_eq!(error, "InvalidDataException: Content chunk record key disagrees with its content hash.");
|
||||
assert!(!asked.get(), "the key check precedes the lookup, as in HandleAsync");
|
||||
}
|
||||
|
||||
/// Every failure is an answer (`found: false`, empty payload, the reference's spelling) and equals,
|
||||
/// byte for byte, what `CultMeshLegacyRudpContentServer` answered to the same request bytes.
|
||||
#[test]
|
||||
fn answer_serves_found_false_with_the_reference_error_spelling() {
|
||||
let (_, chunks) = pack(&body());
|
||||
let store = store(&chunks);
|
||||
let reference = read_vectors("content-vectors.cs-written.json");
|
||||
let mut judged = 0;
|
||||
for (label, _, request_bytes) in reference.iter().filter(|(l, _, _)| l.ends_with(".request")) {
|
||||
let name = label.trim_end_matches(".request");
|
||||
let request = unwire(request_bytes).expect("decodes");
|
||||
let answer = answer_content_chunk_request(&request, lookup_in(&store));
|
||||
let (_, _, expected_bytes) = reference
|
||||
.iter()
|
||||
.find(|(l, _, _)| *l == format!("{name}.response"))
|
||||
.expect("paired response");
|
||||
assert_eq!(&wire(&answer), expected_bytes, "{name}: answer differs from the reference's");
|
||||
let (_, found, _, payload, error) = response_of(&answer);
|
||||
if ["answer_found", "answer_blank_record_key", "answer_double_prefix"].contains(&name) {
|
||||
assert!(found && error.is_empty() && !payload.is_empty());
|
||||
} else {
|
||||
assert!(!found && payload.is_empty(), "{name}");
|
||||
assert!(error.contains("Exception: "), "{name}: {error}");
|
||||
}
|
||||
judged += 1;
|
||||
}
|
||||
assert_eq!(judged, 16);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn gamecult_networking_contract_refuses_content_messages() {
|
||||
let legacy = CultNetWireContract::GameCultNetworkingV0;
|
||||
let message = request("m", "abc", "", 1);
|
||||
assert!(encode_cultnet_message_for_wire(&message, legacy).is_err());
|
||||
assert!(decode_cultnet_message_from_slice(&wire(&message), legacy).is_err());
|
||||
}
|
||||
|
||||
// ------------------------------------------------------------------------------------------
|
||||
// BP-1 fixes
|
||||
// ------------------------------------------------------------------------------------------
|
||||
|
||||
fn chunk_ref(hash: &str, offset: i64, size: i32) -> cultnet_rs::CultMeshCdnChunkRef {
|
||||
cultnet_rs::CultMeshCdnChunkRef {
|
||||
chunk_hash: hash.to_string(),
|
||||
offset,
|
||||
size_bytes: size,
|
||||
record_key: String::new(),
|
||||
}
|
||||
}
|
||||
|
||||
/// A manifest with the given chunk list and stated size, everything else from a real pack.
|
||||
fn manifest_of(size: i64, chunks: Vec<cultnet_rs::CultMeshCdnChunkRef>) -> CultMeshCdnArtifactManifest {
|
||||
let mut manifest = pack(&[]).0;
|
||||
manifest.size_bytes = size;
|
||||
manifest.chunks = chunks;
|
||||
manifest
|
||||
}
|
||||
|
||||
// F1: a zero-size chunk is legal only as an empty body's single chunk.
|
||||
#[test]
|
||||
fn a_zero_size_chunk_flood_is_refused_before_any_request() {
|
||||
let (empty, empty_chunks) = pack(&[]);
|
||||
let empty_store = store(&empty_chunks);
|
||||
let flood = manifest_of(0, (0..100_000).map(|_| chunk_ref(&empty.content_hash, 0, 0)).collect());
|
||||
validate_manifest(&flood).expect("the shared shape rule accepts it, as the reference does");
|
||||
let calls = std::cell::Cell::new(0);
|
||||
assert!(fetch_content(&flood, u64::MAX, serving(&empty_store, &calls)).is_err());
|
||||
assert_eq!(calls.get(), 0, "100,000 empty chunks must not become 100,000 requests");
|
||||
|
||||
// A zero-size chunk beside real ones is refused too, so skipping it is never the client's job.
|
||||
let (good, chunks) = pack(&body());
|
||||
let body_store = store(&chunks);
|
||||
let mut zero_inside = good.clone();
|
||||
let boundary = zero_inside.chunks[2].offset;
|
||||
zero_inside.chunks.insert(2, chunk_ref(&empty.content_hash, boundary, 0));
|
||||
validate_manifest(&zero_inside).expect("shape-valid");
|
||||
let calls = std::cell::Cell::new(0);
|
||||
assert!(fetch_content(&zero_inside, u64::MAX, serving(&body_store, &calls)).is_err());
|
||||
assert_eq!(calls.get(), 0);
|
||||
|
||||
// An empty body still fetches, through its one zero-length chunk.
|
||||
let calls = std::cell::Cell::new(0);
|
||||
assert_eq!(fetch_content(&empty, 0, serving(&empty_store, &calls)).expect("fetches"), Vec::<u8>::new());
|
||||
assert_eq!(calls.get(), 1);
|
||||
}
|
||||
|
||||
// F2, F5: every bad request is answered, in the reference's validation order and spelling. The
|
||||
// byte-identity against the reference server's own answers is `answer_serves_found_false_...`.
|
||||
#[test]
|
||||
fn a_bad_request_is_answered_never_dropped() {
|
||||
let (_, chunks) = pack(&body());
|
||||
let store = store(&chunks);
|
||||
let last = chunks.last().unwrap();
|
||||
let size = last.payload.len() as i32;
|
||||
let size_mismatch = "InvalidDataException: CDN artifact chunk payload metadata does not match its manifest reference.";
|
||||
for (label, bad, spelling) in [
|
||||
(
|
||||
"blank id",
|
||||
request("", &last.chunk_hash, "", size),
|
||||
"InvalidDataException: Content chunk request requires a message identity.",
|
||||
),
|
||||
("blank hash", request("m", "", "", size), "ArgumentException: Hash must be non-empty. (Parameter 'ChunkHash')"),
|
||||
(
|
||||
"prefix-only hash",
|
||||
request("m", "sha256: ", "", size),
|
||||
"ArgumentException: Hash must be non-empty. (Parameter 'chunkHash')",
|
||||
),
|
||||
("negative size", request("m", &last.chunk_hash, "", -1), size_mismatch),
|
||||
] {
|
||||
let answer = answer_content_chunk_request(&bad, lookup_in(&store));
|
||||
let (_, found, _, payload, error) = response_of(&answer);
|
||||
assert!(!found && payload.is_empty(), "{label}");
|
||||
assert_eq!(error, spelling, "{label}");
|
||||
// And both travel: neither the request nor its answer is stopped at decode or encode.
|
||||
assert_eq!(unwire(&wire(&bad)).expect("the request decodes"), bad, "{label}");
|
||||
assert_eq!(unwire(&wire(&answer)).expect("the answer encodes and decodes"), answer, "{label}");
|
||||
}
|
||||
}
|
||||
|
||||
// A caller that leaves a string null writes msgpack nil. The reference reads null, treats it as blank
|
||||
// and answers; Rust decodes nil as blank so the same request gets the same answer, byte for byte.
|
||||
#[test]
|
||||
fn nil_fields_are_answered_as_blanks() {
|
||||
let (_, chunks) = pack(&body());
|
||||
let store = store(&chunks);
|
||||
let reference = read_vectors("content-vectors.cs-written.json");
|
||||
for (name, spelling) in [
|
||||
("nil_message_id", "InvalidDataException: Content chunk request requires a message identity."),
|
||||
("nil_hash", "ArgumentException: Hash must be non-empty. (Parameter 'ChunkHash')"),
|
||||
("nil_record_key", "FileNotFoundException: Content chunk is not available."),
|
||||
] {
|
||||
let find = |suffix: &str| {
|
||||
let label = format!("{name}.{suffix}");
|
||||
reference.iter().find(|(l, _, _)| *l == label).expect("vector").2.clone()
|
||||
};
|
||||
let request_bytes = find("request");
|
||||
assert!(request_bytes.contains(&0xc0), "{name}: the reference wrote nil");
|
||||
let answer = answer_content_chunk_request(&unwire(&request_bytes).expect("nil decodes"), lookup_in(&store));
|
||||
assert_eq!(wire(&answer), find("response"), "{name}: answer differs from the reference's");
|
||||
assert_eq!(response_of(&answer).4, spelling, "{name}");
|
||||
}
|
||||
}
|
||||
|
||||
// F3: metadata keeps the order it was read in and refuses a duplicate key.
|
||||
#[test]
|
||||
fn manifest_metadata_keeps_wire_order_and_refuses_a_duplicate_key() {
|
||||
let reference = read_vectors("content-vectors.cs-written.json");
|
||||
let (_, _, bytes) = reference.iter().find(|(l, _, _)| l == "manifest_metadata_order").expect("vector");
|
||||
let decoded = decode_manifest(bytes);
|
||||
assert_eq!(&manifest_bytes(&decoded), bytes, "zeta, alpha, mid re-encode as zeta, alpha, mid");
|
||||
|
||||
let base = pack(&body()).0;
|
||||
let duplicated = manifest_with_metadata(&base, &[("k", "1"), ("other", "2"), ("k", "3")]);
|
||||
assert!(rmp_serde::from_slice::<CultMeshCdnArtifactManifest>(&duplicated).is_err());
|
||||
let unique = manifest_with_metadata(&base, &[("k", "1"), ("other", "2")]);
|
||||
assert_eq!(manifest_bytes(&decode_manifest(&unique)), unique);
|
||||
|
||||
// Metadata that is not a map is refused, and says what was expected.
|
||||
let mut value = rmpv::decode::read_value(&mut manifest_bytes(&base).as_slice()).expect("a msgpack value");
|
||||
let rmpv::Value::Array(fields) = &mut value else {
|
||||
panic!("the manifest is a positional array");
|
||||
};
|
||||
fields[9] = rmpv::Value::from(5);
|
||||
let mut not_a_map = Vec::new();
|
||||
rmpv::encode::write_value(&mut not_a_map, &value).expect("writes");
|
||||
let error = rmp_serde::from_slice::<CultMeshCdnArtifactManifest>(¬_a_map).expect_err("not a map");
|
||||
assert!(error.to_string().contains("a map of strings"), "{error}");
|
||||
}
|
||||
|
||||
// F4: hashes are settled before the first request.
|
||||
#[test]
|
||||
fn a_blank_hash_is_refused_before_any_request() {
|
||||
let (good, chunks) = pack(&body());
|
||||
let store = store(&chunks);
|
||||
let mut blank_content = good.clone();
|
||||
blank_content.content_hash = " ".to_string();
|
||||
let mut prefix_content = good.clone();
|
||||
prefix_content.content_hash = "sha256: ".to_string();
|
||||
let mut blank_chunk = good.clone();
|
||||
blank_chunk.chunks[3].chunk_hash = " ".to_string();
|
||||
let mut prefix_chunk = good.clone();
|
||||
prefix_chunk.chunks[3].chunk_hash = "SHA256: ".to_string();
|
||||
for (label, manifest) in [
|
||||
("blank content hash", blank_content),
|
||||
("prefix-only content hash", prefix_content),
|
||||
("blank chunk hash at 3", blank_chunk),
|
||||
("prefix-only chunk hash at 3", prefix_chunk),
|
||||
] {
|
||||
let calls = std::cell::Cell::new(0);
|
||||
assert!(fetch_content(&manifest, u64::MAX, serving(&store, &calls)).is_err(), "{label}");
|
||||
assert_eq!(calls.get(), 0, "{label}: refused before any request");
|
||||
}
|
||||
}
|
||||
|
||||
// F6: `pack_content` refuses a chunk size the reference's int cannot hold, without panicking.
|
||||
#[test]
|
||||
fn pack_content_refuses_an_unusable_chunk_size() {
|
||||
for size in [0usize, i32::MAX as usize + 1, usize::MAX] {
|
||||
let refused = std::panic::catch_unwind(|| pack_content("a", "", "", "", "", b"abc", size));
|
||||
assert!(matches!(refused, Ok(Err(_))), "chunk size {size} must be refused cleanly");
|
||||
}
|
||||
let (manifest, _) =
|
||||
pack_content("a", "", "", "", "", b"abc", i32::MAX as usize).expect("i32::MAX is a valid chunk size");
|
||||
assert_eq!(manifest.chunks.len(), 1);
|
||||
}
|
||||
|
||||
// F6: `PackArtifact` defaults a blank kind and mime type and otherwise uses the value untouched.
|
||||
#[test]
|
||||
fn pack_defaults_only_a_blank_kind_and_mime_type_and_never_trims() {
|
||||
let packed = |kind: &str, mime: &str| pack_content("a", kind, "v", mime, CREATED, b"abc", 2).expect("packs").0;
|
||||
for blank in ["", " ", "\t \n"] {
|
||||
let manifest = packed(blank, blank);
|
||||
assert_eq!(
|
||||
(manifest.kind.as_str(), manifest.mime_type.as_str()),
|
||||
("asset", "application/octet-stream"),
|
||||
"{blank:?}"
|
||||
);
|
||||
}
|
||||
let manifest = packed(" build ", " text/plain ");
|
||||
assert_eq!((manifest.kind.as_str(), manifest.mime_type.as_str()), (" build ", " text/plain "));
|
||||
}
|
||||
|
||||
/// The honest answer to `request`, taken apart so a test can lie in one field.
|
||||
fn honest(request: &CultNetMessage, store: &HashMap<String, Vec<u8>>) -> (String, bool, String, i32, Vec<u8>, String) {
|
||||
match answer_content_chunk_request(request, lookup_in(store)) {
|
||||
CultNetMessage::ContentChunkResponse { message_id, found, chunk_hash, size_bytes, payload, error } => {
|
||||
(message_id, found, chunk_hash, size_bytes, payload, error)
|
||||
}
|
||||
other => panic!("{other:?}"),
|
||||
}
|
||||
}
|
||||
|
||||
// F6: the two halves of the per-chunk check, each on its own.
|
||||
#[test]
|
||||
fn a_chunk_whose_length_or_claim_disagrees_with_the_manifest_is_refused() {
|
||||
let (manifest, chunks) = pack(&body());
|
||||
let store = store(&chunks);
|
||||
// Each lie maps (honest size, honest payload) to (claimed size, payload served).
|
||||
type Lie = fn(i32, Vec<u8>) -> (i32, Vec<u8>);
|
||||
let lies: [(&str, Lie); 4] = [
|
||||
("a payload of the claimed length that is not the manifest's length", |size, mut p| {
|
||||
p.truncate(p.len() - 1);
|
||||
(size - 1, p)
|
||||
}),
|
||||
("a payload whose length is not its claimed size, the claim being the manifest's", |size, mut p| {
|
||||
p.truncate(p.len() - 1);
|
||||
(size, p)
|
||||
}),
|
||||
("the right payload under a wrong claimed size", |size, p| (size - 1, p)),
|
||||
("a longer payload of its claimed length", |size, mut p| {
|
||||
p.push(0);
|
||||
(size + 1, p)
|
||||
}),
|
||||
];
|
||||
for (label, lie) in lies {
|
||||
let error = fetch_content(&manifest, u64::MAX, |message| {
|
||||
let (message_id, found, chunk_hash, honest_size, payload, error) = honest(&message, &store);
|
||||
let (size_bytes, payload) = lie(honest_size, payload);
|
||||
Ok(CultNetMessage::ContentChunkResponse { message_id, found, chunk_hash, size_bytes, payload, error })
|
||||
})
|
||||
.expect_err(label);
|
||||
assert!(error.to_string().contains("payload metadata does not match"), "{label}: {error}");
|
||||
}
|
||||
}
|
||||
|
||||
// F6: `[5@0, 0@0]` is not contiguous under the reference's stable sort by offset alone.
|
||||
#[test]
|
||||
fn equal_offsets_keep_their_manifest_order() {
|
||||
let hash = "0".repeat(64);
|
||||
let five_then_zero = manifest_of(5, vec![chunk_ref(&hash, 0, 5), chunk_ref(&hash, 0, 0)]);
|
||||
assert!(validate_manifest(&five_then_zero).is_err(), "the stable sort keeps 5@0 first, so 0@0 lands at offset 5");
|
||||
let zero_then_five = manifest_of(5, vec![chunk_ref(&hash, 0, 0), chunk_ref(&hash, 0, 5)]);
|
||||
validate_manifest(&zero_then_five).expect("0@0 first leaves 5@0 at offset 0");
|
||||
}
|
||||
|
||||
// F6: what goes on the wire is the normalized hash and the canonical record key.
|
||||
#[test]
|
||||
fn the_client_sends_the_normalized_hash_and_canonical_record_key() {
|
||||
let (mut manifest, chunks) = pack(&body());
|
||||
let store = store(&chunks);
|
||||
let honest_hashes: Vec<String> = manifest.chunks.iter().map(|c| c.chunk_hash.clone()).collect();
|
||||
manifest.content_hash = format!("SHA256:{}", manifest.content_hash.to_uppercase());
|
||||
for (index, chunk) in manifest.chunks.iter_mut().enumerate() {
|
||||
chunk.chunk_hash = format!("sha256:{}", chunk.chunk_hash.to_uppercase());
|
||||
// Alternate chunks name their key; the rest leave it blank for the client to derive.
|
||||
chunk.record_key =
|
||||
if index % 2 == 0 { format!("mesh:cdn:chunk:{}", honest_hashes[index]) } else { " ".to_string() };
|
||||
}
|
||||
let mut sent = Vec::new();
|
||||
let fetched = fetch_content(&manifest, u64::MAX, |message| {
|
||||
sent.push(message.clone());
|
||||
Ok(answer_content_chunk_request(&message, lookup_in(&store)))
|
||||
})
|
||||
.expect("fetches");
|
||||
assert_eq!(fetched, body());
|
||||
assert_eq!(sent.len(), honest_hashes.len());
|
||||
for (message, hash) in sent.iter().zip(&honest_hashes) {
|
||||
let CultNetMessage::ContentChunkRequest { chunk_hash, record_key, .. } = message else {
|
||||
panic!("not a request");
|
||||
};
|
||||
assert_eq!(chunk_hash, hash, "the normalized hash is what is sent");
|
||||
assert_eq!(record_key, &format!("mesh:cdn:chunk:{hash}"), "and the canonical key");
|
||||
}
|
||||
}
|
||||
|
|
@ -15,6 +15,11 @@
|
|||
"require": "./dist/contracts.js",
|
||||
"default": "./dist/contracts.js"
|
||||
},
|
||||
"./idunn-runtime": {
|
||||
"types": "./dist/idunn-runtime-authority.d.ts",
|
||||
"require": "./dist/idunn-runtime-authority.js",
|
||||
"default": "./dist/idunn-runtime-authority.js"
|
||||
},
|
||||
"./authority": {
|
||||
"types": "./dist/cultmesh-authority.d.ts",
|
||||
"require": "./dist/cultmesh-authority.js",
|
||||
|
|
@ -53,7 +58,7 @@
|
|||
},
|
||||
"homepage": "https://github.com/GameCult/CultLib/tree/main/packages/cultnet-ts#readme",
|
||||
"engines": {
|
||||
"node": ">=18"
|
||||
"node": ">=20"
|
||||
},
|
||||
"dependencies": {
|
||||
"@msgpack/msgpack": "^3.1.3",
|
||||
|
|
|
|||
|
|
@ -1,4 +1,4 @@
|
|||
import Ajv2020, { type ValidateFunction } from "ajv/dist/2020";
|
||||
import Ajv2020, { type ValidateFunction } from "ajv/dist/2020.js";
|
||||
|
||||
import documentRecordSchema from "../contracts/cultnet/cultnet.document-record.schema.json";
|
||||
import helloSchema from "../contracts/cultnet/cultnet.hello.schema.json";
|
||||
|
|
|
|||
244
packages/cultnet-ts/src/idunn-odin-presence-publisher.ts
Normal file
244
packages/cultnet-ts/src/idunn-odin-presence-publisher.ts
Normal file
|
|
@ -0,0 +1,244 @@
|
|||
import dgram from "node:dgram";
|
||||
import { decode, encode } from "@msgpack/msgpack";
|
||||
|
||||
import { encodeCultNetMessageForWire, parseCultNetMessage } from "./contracts";
|
||||
import type { IdunnRuntimeSigner } from "./idunn-runtime-authority";
|
||||
import { CultNetRudpSession, decodeRudpPacket, encodeRudpPacket } from "./rudp";
|
||||
import type { CultNetRudpPacket } from "./rudp";
|
||||
|
||||
const ODIN_CAPABILITY = "odin.verse-rendezvous";
|
||||
const MAX_LEASE_WAIT_ROUNDS = 720;
|
||||
|
||||
export type IdunnRuntimePresencePublisher = {
|
||||
readonly runtimeId: string;
|
||||
readonly runtimeInstanceId: string;
|
||||
readonly requiresWriteLease: boolean;
|
||||
/** Publishes the signer's presence in the health the signer reports. */
|
||||
publish(detail: string): Promise<string>;
|
||||
/**
|
||||
* Publishes warming presence until Idunn's lease names one. Call it before
|
||||
* `reportHealth('active')`: once the signer reports a non-warming health,
|
||||
* `publish` inside this loop throws (it needs the lease) instead of polling.
|
||||
*/
|
||||
waitForWriteLease(options?: { pollIntervalMs?: number; signal?: AbortSignal }): Promise<string>;
|
||||
assertWriteLease(): Promise<string>;
|
||||
};
|
||||
|
||||
export type IdunnRuntimePresencePublisherOptions = {
|
||||
signer: IdunnRuntimeSigner;
|
||||
endpoint: string;
|
||||
};
|
||||
|
||||
/**
|
||||
* Publishes the signer's presence to Odin over RUDP, for services that are
|
||||
* CultMesh-aware and declare `odin.verse-rendezvous` in Expected. The route
|
||||
* proof never passes through here: `signer.answerRouteObservation` answers
|
||||
* Idunn's challenge locally and needs no Odin. Capability shortfalls are not
|
||||
* judged here either; the correlation owner records a typed disagreement.
|
||||
*/
|
||||
export function createIdunnRuntimePresencePublisher(
|
||||
options: IdunnRuntimePresencePublisherOptions,
|
||||
): IdunnRuntimePresencePublisher {
|
||||
const { signer } = options;
|
||||
const endpoint = parseRudpEndpoint(options.endpoint);
|
||||
const odinDependency = signer.authority.expected.dependencies.find((dependency) => dependency.kind === "shared-infrastructure"
|
||||
&& dependency.capability === ODIN_CAPABILITY);
|
||||
if (!odinDependency || normalizeRudpEndpoint(odinDependency.providerEndpoint ?? "") !== normalizeRudpEndpoint(options.endpoint)) {
|
||||
throw new Error("Configured Odin endpoint does not match Idunn Expected dependency authority.");
|
||||
}
|
||||
const connectionId = 0x0d1d0002;
|
||||
let messageSequence = 0;
|
||||
|
||||
const publish = async (detail: string) => {
|
||||
const signed = signer.sign(detail);
|
||||
messageSequence += 1;
|
||||
await publishDocument(endpoint, connectionId, {
|
||||
schemaVersion: "cultnet.document_put_raw.v0",
|
||||
messageId: `runtime-presence:${signer.authority.expected.target}:${signer.runtimeInstanceId}:${messageSequence}`,
|
||||
document: signed.document,
|
||||
});
|
||||
return signed.canonicalSha256;
|
||||
};
|
||||
|
||||
return {
|
||||
runtimeId: signer.runtimeId,
|
||||
runtimeInstanceId: signer.runtimeInstanceId,
|
||||
requiresWriteLease: signer.requiresWriteLease,
|
||||
publish,
|
||||
async waitForWriteLease({ pollIntervalMs = 5000, signal } = {}) {
|
||||
if (!signer.requiresWriteLease) return "";
|
||||
let warmingSequence = 0;
|
||||
while (!signal?.aborted) {
|
||||
await publish("waiting-for-process-write-lease");
|
||||
warmingSequence += 1;
|
||||
try {
|
||||
return signer.assertWriteLease();
|
||||
} catch (error) {
|
||||
if (warmingSequence > MAX_LEASE_WAIT_ROUNDS) throw new Error("Timed out waiting for Idunn process write lease.", { cause: error });
|
||||
}
|
||||
await abortableDelay(pollIntervalMs, signal);
|
||||
}
|
||||
throw signal?.reason ?? new Error("Aborted while waiting for Idunn process write lease.");
|
||||
},
|
||||
async assertWriteLease() {
|
||||
return signer.assertWriteLease();
|
||||
},
|
||||
};
|
||||
}
|
||||
|
||||
async function publishDocument(
|
||||
endpoint: { host: string; port: number },
|
||||
connectionId: number,
|
||||
message: Record<string, unknown>,
|
||||
): Promise<void> {
|
||||
const socket = dgram.createSocket(endpoint.host.includes(":") ? "udp6" : "udp4");
|
||||
await new Promise<void>((resolve, reject) => {
|
||||
socket.once("error", reject);
|
||||
socket.bind(0, endpoint.host.includes(":") ? "::" : "0.0.0.0", () => {
|
||||
socket.off("error", reject);
|
||||
resolve();
|
||||
});
|
||||
});
|
||||
const receiver = receivePackets(socket);
|
||||
const session = new CultNetRudpSession({ connectionId, initialSequence: 1, resendDelayMs: 100 });
|
||||
try {
|
||||
await sendPacket(socket, endpoint, session.createConnect(Date.now(), new Uint8Array()));
|
||||
await receiveUntil(receiver, session, endpoint, (packet) => packet.packetType === "accept", 5000);
|
||||
const wirePayload = encode(encodeCultNetMessageForWire(message as never, "cultnet.schema.v0"));
|
||||
const packets = session.sendMany("schema", wirePayload, { reliable: true, ordered: true, nowMs: Date.now() });
|
||||
for (const packet of packets) await sendPacket(socket, endpoint, packet);
|
||||
await receiveUntil(
|
||||
receiver,
|
||||
session,
|
||||
endpoint,
|
||||
() => session.outstandingReliablePacketCount === 0,
|
||||
2000,
|
||||
(frame) => {
|
||||
if (frame.channelId !== "schema") return;
|
||||
const response = parseCultNetMessage(decode(frame.payload));
|
||||
if (response.schemaVersion === "cultnet.error.v0") {
|
||||
throw new Error(`Odin rejected runtime presence: ${response.error}`);
|
||||
}
|
||||
},
|
||||
);
|
||||
} finally {
|
||||
receiver.close();
|
||||
socket.close();
|
||||
}
|
||||
}
|
||||
|
||||
type PacketReceiver = {
|
||||
socket: dgram.Socket;
|
||||
next(timeoutMs: number): Promise<CultNetRudpPacket>;
|
||||
close(): void;
|
||||
};
|
||||
|
||||
function receivePackets(socket: dgram.Socket): PacketReceiver {
|
||||
const packets: CultNetRudpPacket[] = [];
|
||||
const waiters: Array<{ resolve: (packet: CultNetRudpPacket) => void; reject: (error: Error) => void; timer: NodeJS.Timeout }> = [];
|
||||
const errors: Error[] = [];
|
||||
const drain = () => {
|
||||
while (waiters.length && (packets.length || errors.length)) {
|
||||
const waiter = waiters.shift()!;
|
||||
clearTimeout(waiter.timer);
|
||||
if (errors.length) waiter.reject(errors.shift()!);
|
||||
else waiter.resolve(packets.shift()!);
|
||||
}
|
||||
};
|
||||
const onMessage = (wire: Buffer) => {
|
||||
try { packets.push(decodeRudpPacket(wire)); } catch (error) { errors.push(error as Error); }
|
||||
drain();
|
||||
};
|
||||
const onError = (error: Error) => { errors.push(error); drain(); };
|
||||
socket.on("message", onMessage);
|
||||
socket.on("error", onError);
|
||||
return {
|
||||
socket,
|
||||
next(timeoutMs) {
|
||||
if (packets.length) return Promise.resolve(packets.shift()!);
|
||||
if (errors.length) return Promise.reject(errors.shift()!);
|
||||
return new Promise((resolve, reject) => {
|
||||
const waiter = {
|
||||
resolve,
|
||||
reject,
|
||||
timer: setTimeout(() => {
|
||||
const index = waiters.indexOf(waiter);
|
||||
if (index >= 0) waiters.splice(index, 1);
|
||||
const error = new Error("Timed out waiting for CultNet RUDP packet.") as NodeJS.ErrnoException;
|
||||
error.code = "ETIMEDOUT";
|
||||
reject(error);
|
||||
}, Math.max(1, timeoutMs)),
|
||||
};
|
||||
waiters.push(waiter);
|
||||
});
|
||||
},
|
||||
close() {
|
||||
socket.off("message", onMessage);
|
||||
socket.off("error", onError);
|
||||
for (const waiter of waiters.splice(0)) {
|
||||
clearTimeout(waiter.timer);
|
||||
waiter.reject(new Error("CultNet RUDP publisher closed."));
|
||||
}
|
||||
},
|
||||
};
|
||||
}
|
||||
|
||||
async function receiveUntil(
|
||||
receiver: PacketReceiver,
|
||||
session: CultNetRudpSession,
|
||||
endpoint: { host: string; port: number },
|
||||
predicate: (packet: CultNetRudpPacket) => boolean,
|
||||
timeoutMs: number,
|
||||
onDelivered?: (frame: { channelId: string; payload: Uint8Array; sequence: number }) => void,
|
||||
): Promise<void> {
|
||||
const deadline = Date.now() + timeoutMs;
|
||||
while (Date.now() < deadline) {
|
||||
try {
|
||||
const packet = await receiver.next(Math.min(100, deadline - Date.now()));
|
||||
const received = session.receive(packet, Date.now());
|
||||
if (received.reply) throw new Error("Runtime presence received an unexpected reply-required packet.");
|
||||
for (const frame of received.delivered) onDelivered?.(frame);
|
||||
if (predicate(packet)) return;
|
||||
} catch (error) {
|
||||
if ((error as NodeJS.ErrnoException)?.code !== "ETIMEDOUT") throw error;
|
||||
}
|
||||
for (const packet of session.dueResends(Date.now())) await sendPacket(receiver.socket, endpoint, packet);
|
||||
}
|
||||
throw new Error(`Timed out waiting for CultNet RUDP response after ${timeoutMs} ms.`);
|
||||
}
|
||||
|
||||
async function sendPacket(socket: dgram.Socket, endpoint: { host: string; port: number }, packet: CultNetRudpPacket): Promise<void> {
|
||||
const wire = encodeRudpPacket(packet);
|
||||
await new Promise<void>((resolve, reject) => {
|
||||
socket.send(wire, endpoint.port, endpoint.host, (error) => error ? reject(error) : resolve());
|
||||
});
|
||||
}
|
||||
|
||||
function parseRudpEndpoint(value: string): { host: string; port: number } {
|
||||
const text = value.replace(/^rudp:\/\//i, "");
|
||||
const match = text.match(/^\[([^\]]+)\]:(\d+)$/) ?? text.match(/^([^:]+):(\d+)$/);
|
||||
if (!match) throw new Error(`Invalid Odin RUDP endpoint: ${value}`);
|
||||
const port = Number(match[2]);
|
||||
if (!Number.isInteger(port) || port < 1 || port > 65535) throw new Error(`Invalid Odin RUDP port: ${match[2]}`);
|
||||
return { host: match[1]!, port };
|
||||
}
|
||||
|
||||
function normalizeRudpEndpoint(value: string): string {
|
||||
const normalized = value.trim().toLowerCase().replace(/^rudp:\/\//, "");
|
||||
const parsed = parseRudpEndpoint(normalized);
|
||||
return `${parsed.host.toLowerCase()}:${parsed.port}`;
|
||||
}
|
||||
|
||||
function abortableDelay(milliseconds: number, signal?: AbortSignal): Promise<void> {
|
||||
return new Promise((resolve, reject) => {
|
||||
const timer = setTimeout(() => {
|
||||
signal?.removeEventListener("abort", onAbort);
|
||||
resolve();
|
||||
}, milliseconds);
|
||||
const onAbort = () => {
|
||||
clearTimeout(timer);
|
||||
reject(signal?.reason ?? new Error("Aborted."));
|
||||
};
|
||||
signal?.addEventListener("abort", onAbort, { once: true });
|
||||
});
|
||||
}
|
||||
643
packages/cultnet-ts/src/idunn-runtime-authority.ts
Normal file
643
packages/cultnet-ts/src/idunn-runtime-authority.ts
Normal file
|
|
@ -0,0 +1,643 @@
|
|||
import crypto from "node:crypto";
|
||||
import fs from "node:fs";
|
||||
import path from "node:path";
|
||||
import { decode, encode } from "@msgpack/msgpack";
|
||||
|
||||
import {
|
||||
GAMECULT_RUNTIME_PRESENCE_HEALTH_SCHEMA,
|
||||
GAMECULT_RUNTIME_PRESENCE_IDENTITY_NAME,
|
||||
RUNTIME_PRESENCE_DETAIL_MAX_BYTES,
|
||||
IDUNN_RUNTIME_ACTIVATION_CREDENTIAL_NAME,
|
||||
runtimePresenceActivationSigningMessage,
|
||||
runtimePresenceProofPayload,
|
||||
runtimePresenceProviderSigningMessage,
|
||||
encodeRuntimePresenceHealth,
|
||||
type RuntimePresenceHealth,
|
||||
} from "./runtime-presence-health";
|
||||
import { truncateUtf8Bytes } from "./utf8-bound";
|
||||
import type { CultNetRawDocumentRecord, CultNetSnapshotRequestMessage } from "./contracts";
|
||||
|
||||
export const IDUNN_EXPECTED_INCARNATION_SCHEMA = "idunn.expected_incarnation.v2";
|
||||
export const IDUNN_RUNTIME_ACTIVATION_SCHEMA = "idunn.runtime_activation.v2";
|
||||
export const IDUNN_PROCESS_WRITE_LEASE_SCHEMA = "idunn.process_write_lease.v1";
|
||||
export const IDUNN_PROCESS_WRITE_LEASE_ENVIRONMENT = "GAMECULT_IDUNN_PROCESS_WRITE_LEASE";
|
||||
export const IDUNN_RUNTIME_BUNDLE_ENVIRONMENT = "GAMECULT_IDUNN_RUNTIME_BUNDLE";
|
||||
export const IDUNN_RUNTIME_CANDIDATE_BIND_ENVIRONMENT = "GAMECULT_IDUNN_CANDIDATE_BIND";
|
||||
|
||||
const PROVIDER_ID_DOMAIN = Buffer.from("gamecult.provider-health.identity.v1\0", "utf8");
|
||||
const PROVIDER_PROTECTOR_CONTEXT = "gamecult-provider-health-identity-v1";
|
||||
const ACTIVATION_ID_DOMAIN = Buffer.from("idunn.runtime-activation.id.v1\0", "utf8");
|
||||
const CULTCACHE_STORE_FORMAT = "cultcache.store.v1";
|
||||
const ED25519_PKCS8_PREFIX = Buffer.from("302e020100300506032b657004220420", "hex");
|
||||
// Limit: more than this many warmings signed between Idunn's observation and
|
||||
// assertWriteLease would push the leased one out and refuse a valid lease.
|
||||
const MAX_RECENT_WARMING_PROOFS = 64;
|
||||
const authoritiesWithSigner = new WeakSet<object>();
|
||||
const authorityKeys = new WeakMap<object, { providerPrivateKey: crypto.KeyObject; activationPrivateKey: crypto.KeyObject }>();
|
||||
|
||||
type ExpectedIncarnation = {
|
||||
schemaVersion: string;
|
||||
target: string;
|
||||
planId: string;
|
||||
incarnationId: string;
|
||||
sealedReleaseId: string;
|
||||
sourceRepository: string;
|
||||
sourceRevision: string;
|
||||
recipeSha256: string;
|
||||
runtimeId: string;
|
||||
expectedSignerIdentityId: string;
|
||||
healthContract: string;
|
||||
artifactSha256: string;
|
||||
stateSchemaGeneration: string | null;
|
||||
stateContractSha256: string | null;
|
||||
writeLeaseRequired: boolean;
|
||||
route: { routeId: string; transport: string; stableEndpoint: string; candidateEndpoint: string } | null;
|
||||
capabilities: Array<{ capability: string; schema: string; compatibility: string; minimumCapacity: number }>;
|
||||
dependencies: Array<{ kind: string; capability: string; schema: string; compatibility: string; providerEndpoint: string | null }>;
|
||||
canonicalSha256: string;
|
||||
};
|
||||
|
||||
type RuntimeActivation = {
|
||||
schemaVersion: string;
|
||||
expectedProjectionSha256: string;
|
||||
runtimeId: string;
|
||||
runtimeInstanceId: string;
|
||||
activationSignerIdentityId: string;
|
||||
activationSignerPublicKeyHex: string;
|
||||
canonicalSha256: string;
|
||||
};
|
||||
|
||||
type DeepReadonly<T> = T extends readonly (infer U)[]
|
||||
? readonly DeepReadonly<U>[]
|
||||
: T extends object ? { readonly [K in keyof T]: DeepReadonly<T[K]> } : T;
|
||||
|
||||
/**
|
||||
* What Idunn admitted for this launch. Deeply frozen at load: bind, health
|
||||
* contract, Expected, Activation and identities are read-only for the life of
|
||||
* the process, so no caller can steer what the signer signs.
|
||||
*/
|
||||
export type IdunnRuntimeAuthority = DeepReadonly<{
|
||||
expected: ExpectedIncarnation;
|
||||
activation: RuntimeActivation;
|
||||
providerSignerIdentityId: string;
|
||||
activationSignerIdentityId: string;
|
||||
boundEndpoint: string;
|
||||
processWriteLeasePath?: string;
|
||||
}>;
|
||||
|
||||
export type SignedRuntimePresence = {
|
||||
document: CultNetRawDocumentRecord;
|
||||
canonicalSha256: string;
|
||||
};
|
||||
|
||||
/**
|
||||
* Signs this launch's runtime presence and answers Idunn's route challenge. It
|
||||
* owns no network: Odin publication, if a service wants it, is a separate
|
||||
* consumer of `sign`. The signer is the single owner of the reported health:
|
||||
* it starts `warming`, the app moves it with `reportHealth`, and every
|
||||
* presence it signs, however it is carried, states that health.
|
||||
*/
|
||||
export type IdunnRuntimeSigner = {
|
||||
readonly authority: IdunnRuntimeAuthority;
|
||||
readonly runtimeId: string;
|
||||
readonly runtimeInstanceId: string;
|
||||
readonly requiresWriteLease: boolean;
|
||||
/** Records the app's health. Until the first call the signer reports `warming`. */
|
||||
reportHealth(state: RuntimePresenceHealth["state"]): void;
|
||||
/**
|
||||
* Signs one presence document in the reported health. Every call takes the
|
||||
* next publisher sequence; every warming presence signed becomes a valid
|
||||
* write-lease target.
|
||||
*/
|
||||
sign(detail: string): SignedRuntimePresence;
|
||||
/**
|
||||
* Answers an Idunn route challenge from local authority alone: signs a fresh
|
||||
* presence in the reported health, with no network.
|
||||
*/
|
||||
answerRouteObservation(request: CultNetSnapshotRequestMessage): CultNetRawDocumentRecord;
|
||||
/** Reads Idunn's write lease and checks it names this incarnation and a warming presence this signer signed. */
|
||||
assertWriteLease(): string;
|
||||
};
|
||||
|
||||
export type IdunnRuntimeSignerOptions = {
|
||||
authority: IdunnRuntimeAuthority;
|
||||
capabilities: RuntimePresenceHealth["capabilities"];
|
||||
};
|
||||
|
||||
/**
|
||||
* Loads the root-provisioned Idunn bundle and parent-only signing descriptors.
|
||||
* The expected record and activation witness are accepted only when their
|
||||
* exact positional contracts and mutual incarnation binding agree. Nothing
|
||||
* here reads Odin: whether a target talks to Odin is decided by the
|
||||
* publisher a service chooses to create.
|
||||
*/
|
||||
export function loadIdunnRuntimeAuthorityFromEnvironment(
|
||||
target: string,
|
||||
healthContract: string,
|
||||
): IdunnRuntimeAuthority {
|
||||
const bundle = requiredEnvironment(IDUNN_RUNTIME_BUNDLE_ENVIRONMENT);
|
||||
const expected = readAuthorityRecord(path.join(bundle, "expected.cc"), "idunn.expected_incarnation", IDUNN_EXPECTED_INCARNATION_SCHEMA);
|
||||
const activation = readAuthorityRecord(path.join(bundle, "activation.cc"), "idunn.runtime_activation", IDUNN_RUNTIME_ACTIVATION_SCHEMA);
|
||||
const expectedValue = decodeExpected(expected.payload);
|
||||
const activationValue = decodeActivation(activation.payload);
|
||||
if (expectedValue.target !== target || expectedValue.healthContract !== healthContract) {
|
||||
throw new Error("Idunn Expected target or health contract does not match this runtime.");
|
||||
}
|
||||
if (activationValue.expectedProjectionSha256 !== expectedValue.canonicalSha256
|
||||
|| activationValue.runtimeId !== expectedValue.runtimeId) {
|
||||
throw new Error("Idunn Activation does not bind this exact Expected incarnation.");
|
||||
}
|
||||
|
||||
const descriptors = inheritedDescriptorMap();
|
||||
const providerCredential = descriptors.get(GAMECULT_RUNTIME_PRESENCE_IDENTITY_NAME);
|
||||
const activationCredential = descriptors.get(IDUNN_RUNTIME_ACTIVATION_CREDENTIAL_NAME);
|
||||
if (providerCredential === undefined || activationCredential === undefined) {
|
||||
throw new Error("Idunn runtime-presence signing descriptors are missing.");
|
||||
}
|
||||
|
||||
const providerPrivateKey = openProviderHealthIdentity(readDescriptor(providerCredential));
|
||||
const activationSeed = readDescriptor(activationCredential);
|
||||
if (activationSeed.length !== 32) throw new Error("Idunn activation credential must be exactly 32 bytes.");
|
||||
const activationPrivateKey = privateKeyFromSeed(activationSeed);
|
||||
activationSeed.fill(0);
|
||||
const activationPublicKey = rawEd25519PublicKey(crypto.createPublicKey(activationPrivateKey));
|
||||
const activationSignerIdentityId = sha256Hex(Buffer.concat([ACTIVATION_ID_DOMAIN, activationPublicKey]));
|
||||
if (activationSignerIdentityId !== activationValue.activationSignerIdentityId
|
||||
|| activationPublicKey.toString("hex") !== activationValue.activationSignerPublicKeyHex) {
|
||||
throw new Error("Idunn activation credential does not match the root-provisioned Activation witness.");
|
||||
}
|
||||
|
||||
if (expectedValue.writeLeaseRequired !== (process.env[IDUNN_PROCESS_WRITE_LEASE_ENVIRONMENT] !== undefined)) {
|
||||
throw new Error("Idunn process write-lease environment does not match Expected.");
|
||||
}
|
||||
const boundEndpoint = requiredEnvironment(IDUNN_RUNTIME_CANDIDATE_BIND_ENVIRONMENT);
|
||||
if (!expectedValue.route || expectedValue.route.candidateEndpoint !== boundEndpoint) {
|
||||
throw new Error("Idunn candidate bind differs from the Expected route.");
|
||||
}
|
||||
if (expectedValue.expectedSignerIdentityId !== providerSignerIdentityId(providerPrivateKey)) {
|
||||
throw new Error("Provider identity does not match Idunn Expected.");
|
||||
}
|
||||
|
||||
const authority: IdunnRuntimeAuthority = deepFreeze({
|
||||
expected: expectedValue,
|
||||
activation: activationValue,
|
||||
providerSignerIdentityId: expectedValue.expectedSignerIdentityId,
|
||||
activationSignerIdentityId,
|
||||
boundEndpoint,
|
||||
...(process.env[IDUNN_PROCESS_WRITE_LEASE_ENVIRONMENT]
|
||||
? { processWriteLeasePath: process.env[IDUNN_PROCESS_WRITE_LEASE_ENVIRONMENT] }
|
||||
: {}),
|
||||
});
|
||||
authorityKeys.set(authority, { providerPrivateKey, activationPrivateKey });
|
||||
return authority;
|
||||
}
|
||||
|
||||
|
||||
/**
|
||||
* Signs the fixed Idunn v2 positional runtime-presence contract with the
|
||||
* provider identity and this launch's Idunn-issued activation key.
|
||||
*/
|
||||
function signIdunnRuntimePresence(
|
||||
authority: IdunnRuntimeAuthority,
|
||||
fields: Omit<RuntimePresenceHealth, "target" | "expectedProjectionSha256" | "planId" | "incarnationId" | "sealedReleaseId" | "activationWitnessSha256" | "stateSchemaGeneration" | "stateContractSha256" | "runtimeId" | "runtimeInstanceId" | "boundEndpoint" | "healthContract" | "signerIdentityId" | "activationSignerIdentityId">,
|
||||
): { presence: RuntimePresenceHealth; payload: Uint8Array; canonicalSha256: string } {
|
||||
const presence: RuntimePresenceHealth = {
|
||||
...fields,
|
||||
target: authority.expected.target,
|
||||
expectedProjectionSha256: authority.expected.canonicalSha256,
|
||||
planId: authority.expected.planId,
|
||||
incarnationId: authority.expected.incarnationId,
|
||||
sealedReleaseId: authority.expected.sealedReleaseId,
|
||||
activationWitnessSha256: authority.activation.canonicalSha256,
|
||||
stateSchemaGeneration: authority.expected.stateSchemaGeneration,
|
||||
stateContractSha256: authority.expected.stateContractSha256,
|
||||
runtimeId: authority.expected.runtimeId,
|
||||
runtimeInstanceId: authority.activation.runtimeInstanceId,
|
||||
boundEndpoint: authority.boundEndpoint,
|
||||
healthContract: authority.expected.healthContract,
|
||||
signerIdentityId: authority.providerSignerIdentityId,
|
||||
activationSignerIdentityId: authority.activationSignerIdentityId,
|
||||
};
|
||||
const keys = authorityKeys.get(authority);
|
||||
if (!keys) throw new Error("Idunn runtime authority was not opened by the CultNet credential reader.");
|
||||
const proofPayload = runtimePresenceProofPayload(presence);
|
||||
const providerSignature = crypto.sign(null, runtimePresenceProviderSigningMessage(proofPayload), keys.providerPrivateKey);
|
||||
const activationSignature = crypto.sign(null, runtimePresenceActivationSigningMessage(proofPayload), keys.activationPrivateKey);
|
||||
const payload = encodeRuntimePresenceHealth(presence, providerSignature, activationSignature);
|
||||
return {
|
||||
presence,
|
||||
payload,
|
||||
canonicalSha256: prefixedSha256(Buffer.from(payload)),
|
||||
};
|
||||
}
|
||||
|
||||
/**
|
||||
* One signer per loaded authority: the publisher sequence and the warming proofs
|
||||
* are the signer's, and a second signer would restart the sequence under the
|
||||
* same runtimeInstanceId.
|
||||
*/
|
||||
export function createIdunnRuntimeSigner(options: IdunnRuntimeSignerOptions): IdunnRuntimeSigner {
|
||||
const { authority } = options;
|
||||
if (authoritiesWithSigner.has(authority)) throw new Error("This Idunn runtime authority already has a signer.");
|
||||
authoritiesWithSigner.add(authority);
|
||||
const expected = authority.expected;
|
||||
let sequence = 0;
|
||||
let health: RuntimePresenceHealth["state"] = "warming";
|
||||
const recentWarmingProofs: string[] = [];
|
||||
|
||||
const assertWriteLease = () => {
|
||||
if (!expected.writeLeaseRequired) return "";
|
||||
const leasePath = authority.processWriteLeasePath;
|
||||
if (!leasePath) throw new Error("Idunn process write lease is required but no lease path is configured.");
|
||||
const record = readAuthorityRecord(leasePath, "idunn.process_write_lease", IDUNN_PROCESS_WRITE_LEASE_SCHEMA);
|
||||
const lease = decodeArray(record.payload, 14, "Idunn process write lease");
|
||||
assertLeaseMatches(lease, authority, recentWarmingProofs);
|
||||
return prefixedSha256(Buffer.from(encode(lease)));
|
||||
};
|
||||
|
||||
const sign = (detail: string): SignedRuntimePresence => {
|
||||
const state = health;
|
||||
const writeLeaseSha256 = state === "warming" || !expected.writeLeaseRequired ? null : assertWriteLease();
|
||||
sequence += 1;
|
||||
const signed = signIdunnRuntimePresence(authority, {
|
||||
capabilities: options.capabilities,
|
||||
state,
|
||||
detail: truncateUtf8Bytes(detail, RUNTIME_PRESENCE_DETAIL_MAX_BYTES),
|
||||
writeLeaseSha256,
|
||||
publisherSequence: sequence,
|
||||
observedAtUnixMillis: Date.now(),
|
||||
});
|
||||
if (state === "warming") {
|
||||
recentWarmingProofs.push(signed.canonicalSha256);
|
||||
if (recentWarmingProofs.length > MAX_RECENT_WARMING_PROOFS) recentWarmingProofs.shift();
|
||||
}
|
||||
return {
|
||||
canonicalSha256: signed.canonicalSha256,
|
||||
document: {
|
||||
schemaId: GAMECULT_RUNTIME_PRESENCE_HEALTH_SCHEMA,
|
||||
recordKey: expected.target,
|
||||
storedAt: new Date().toISOString(),
|
||||
payloadEncoding: "messagepack",
|
||||
payload: new Uint8Array(signed.payload),
|
||||
sourceRuntimeId: expected.runtimeId,
|
||||
sourceRole: "runtime-presence-health-publisher",
|
||||
tags: ["cultnet.transport.rudp.v0", "runtime-presence"],
|
||||
},
|
||||
};
|
||||
};
|
||||
|
||||
return {
|
||||
authority,
|
||||
runtimeId: expected.runtimeId,
|
||||
runtimeInstanceId: authority.activation.runtimeInstanceId,
|
||||
requiresWriteLease: expected.writeLeaseRequired,
|
||||
reportHealth(state) {
|
||||
health = state;
|
||||
},
|
||||
sign,
|
||||
answerRouteObservation(request) {
|
||||
if (!request.messageId || request.messageId.trim() !== request.messageId) throw new Error("Idunn route observation requires a message id.");
|
||||
if ((request.schemaIds && !request.schemaIds.includes(GAMECULT_RUNTIME_PRESENCE_HEALTH_SCHEMA))
|
||||
|| (request.recordKeys && !request.recordKeys.includes(expected.target))
|
||||
|| request.shardId !== undefined
|
||||
|| request.shardEpoch !== undefined) {
|
||||
throw new Error("Idunn route observation does not request this runtime presence document.");
|
||||
}
|
||||
return sign(`route-observation:${request.messageId}`).document;
|
||||
},
|
||||
assertWriteLease,
|
||||
};
|
||||
}
|
||||
|
||||
function deepFreeze<T>(value: T): T {
|
||||
if (value !== null && typeof value === "object" && !Object.isFrozen(value)) {
|
||||
for (const child of Object.values(value)) deepFreeze(child);
|
||||
Object.freeze(value);
|
||||
}
|
||||
return value;
|
||||
}
|
||||
|
||||
function readAuthorityRecord(filePath: string, type: string, schemaId: string): { payload: Uint8Array } {
|
||||
const decoded = decode(fs.readFileSync(filePath));
|
||||
if (!Array.isArray(decoded) || decoded[0] !== CULTCACHE_STORE_FORMAT || !Array.isArray(decoded[1]) || !Array.isArray(decoded[2])) {
|
||||
throw new Error(`Idunn authority file ${filePath} is not a CultCache v1 store.`);
|
||||
}
|
||||
if (decoded[2].length !== 1) throw new Error(`Idunn authority file ${filePath} must contain exactly one record.`);
|
||||
const matchingRecords = (decoded[2] as unknown[]).filter((raw) => {
|
||||
const row = array(raw, 4, "CultCache record");
|
||||
return row[1] === schemaId;
|
||||
});
|
||||
if (matchingRecords.length !== 1) throw new Error(`Idunn authority file must contain exactly one ${schemaId} record.`);
|
||||
const row = array(matchingRecords[0], 4, "CultCache record");
|
||||
const catalog = (decoded[1] as unknown[]).find((raw) => {
|
||||
const entry = Array.isArray(raw) ? raw : [];
|
||||
return entry[0] === schemaId;
|
||||
});
|
||||
const catalogEntry = array(catalog, 7, "CultCache schema catalog entry");
|
||||
if (catalogEntry[1] !== type) throw new Error(`Idunn authority record has unexpected CultCache type ${String(catalogEntry[1])}.`);
|
||||
if (!(row[3] instanceof Uint8Array)) throw new Error("Idunn authority payload is not MessagePack bytes.");
|
||||
return { payload: row[3] };
|
||||
}
|
||||
|
||||
function decodeExpected(payload: Uint8Array): ExpectedIncarnation {
|
||||
const values = decodeArray(payload, 18, "Idunn Expected");
|
||||
if (values[0] !== IDUNN_EXPECTED_INCARNATION_SCHEMA) throw new Error("Idunn Expected schema is unsupported.");
|
||||
const canonicalBytes = Buffer.from(encode(values));
|
||||
if (!canonicalBytes.equals(Buffer.from(payload))) throw new Error("Idunn Expected is not canonical MessagePack.");
|
||||
const stateSchemaGeneration = nullableString(values[12], "Expected state generation");
|
||||
const stateContractSha256 = nullableString(values[13], "Expected state contract");
|
||||
if ((stateSchemaGeneration === null) !== (stateContractSha256 === null)) throw new Error("Idunn Expected state lineage is partial.");
|
||||
if (typeof values[14] !== "boolean") throw new Error("Idunn Expected write-lease flag is not boolean.");
|
||||
const route = decodeRoute(values[15]);
|
||||
const writeLeaseRequired = values[14];
|
||||
if (writeLeaseRequired && stateSchemaGeneration === null) throw new Error("Stateless Idunn Expected cannot require a write lease.");
|
||||
const target = string(values[1], "Expected target");
|
||||
const planId = string(values[2], "Expected plan id");
|
||||
const incarnationId = string(values[3], "Expected incarnation id");
|
||||
const sealedReleaseId = string(values[4], "Expected sealed release");
|
||||
const sourceRepository = string(values[5], "Expected source repository");
|
||||
const sourceRevision = string(values[6], "Expected source revision");
|
||||
const recipeSha256 = string(values[7], "Expected recipe hash");
|
||||
const runtimeId = string(values[8], "Expected runtime id");
|
||||
const expectedSignerIdentityId = string(values[9], "Expected signer identity");
|
||||
const healthContract = string(values[10], "Expected health contract");
|
||||
const artifactSha256 = string(values[11], "Expected artifact hash");
|
||||
for (const [name, hash] of [["plan", planId], ["release", sealedReleaseId], ["recipe", recipeSha256], ["artifact", artifactSha256]] as const) {
|
||||
if (!/^sha256-[0-9a-f]{64}$/u.test(hash)) throw new Error(`Expected ${name} hash is malformed.`);
|
||||
}
|
||||
if (!/^[0-9a-f]{40}$/u.test(sourceRevision)) throw new Error("Expected source revision is malformed.");
|
||||
if (route) validateRoute(route);
|
||||
return {
|
||||
schemaVersion: string(values[0], "Expected schema"),
|
||||
target,
|
||||
planId,
|
||||
incarnationId,
|
||||
sealedReleaseId,
|
||||
sourceRepository,
|
||||
sourceRevision,
|
||||
recipeSha256,
|
||||
runtimeId,
|
||||
expectedSignerIdentityId,
|
||||
healthContract,
|
||||
artifactSha256,
|
||||
stateSchemaGeneration,
|
||||
stateContractSha256,
|
||||
writeLeaseRequired,
|
||||
route,
|
||||
capabilities: decodeExpectedCapabilities(values[16]),
|
||||
dependencies: decodeExpectedDependencies(values[17]),
|
||||
canonicalSha256: prefixedSha256(canonicalBytes),
|
||||
};
|
||||
}
|
||||
|
||||
function decodeActivation(payload: Uint8Array): RuntimeActivation {
|
||||
const values = decodeArray(payload, 10, "Idunn Activation");
|
||||
if (values[0] !== IDUNN_RUNTIME_ACTIVATION_SCHEMA) throw new Error("Idunn Activation schema is unsupported.");
|
||||
const canonicalBytes = Buffer.from(encode(values));
|
||||
if (!canonicalBytes.equals(Buffer.from(payload))) throw new Error("Idunn Activation is not canonical MessagePack.");
|
||||
const publicKey = bytes(values[5], "Activation signer public key");
|
||||
if (publicKey.length !== 32) throw new Error("Activation signer public key is not Ed25519.");
|
||||
const activationSignerIdentityId = string(values[4], "Activation signer identity");
|
||||
if (number(values[6], "Activation issue time") <= 0
|
||||
|| !/^[0-9a-f]{64}$/u.test(string(values[7], "Idunn signer identity"))
|
||||
|| values[8] !== "ed25519"
|
||||
|| bytes(values[9], "Activation signature").length !== 64) {
|
||||
throw new Error("Idunn Activation signature contract is malformed.");
|
||||
}
|
||||
if (sha256Hex(Buffer.concat([ACTIVATION_ID_DOMAIN, publicKey])) !== activationSignerIdentityId) {
|
||||
throw new Error("Activation signer identity does not match its public key.");
|
||||
}
|
||||
return {
|
||||
schemaVersion: string(values[0], "Activation schema"),
|
||||
expectedProjectionSha256: string(values[1], "Activation Expected hash"),
|
||||
runtimeId: string(values[2], "Activation runtime id"),
|
||||
runtimeInstanceId: string(values[3], "Activation instance id"),
|
||||
activationSignerIdentityId,
|
||||
activationSignerPublicKeyHex: Buffer.from(publicKey).toString("hex"),
|
||||
canonicalSha256: prefixedSha256(canonicalBytes),
|
||||
};
|
||||
}
|
||||
|
||||
function decodeExpectedCapabilities(value: unknown): ExpectedIncarnation["capabilities"] {
|
||||
return arrayOf(value, "Expected capabilities").map((raw) => {
|
||||
const item = array(raw, 4, "Expected capability");
|
||||
return {
|
||||
capability: string(item[0], "Capability id"),
|
||||
schema: string(item[1], "Capability schema"),
|
||||
compatibility: string(item[2], "Capability compatibility"),
|
||||
minimumCapacity: number(item[3], "Capability capacity"),
|
||||
};
|
||||
});
|
||||
}
|
||||
|
||||
function decodeExpectedDependencies(value: unknown): ExpectedIncarnation["dependencies"] {
|
||||
return arrayOf(value, "Expected dependencies").map((raw) => {
|
||||
const item = array(raw, 10, "Expected dependency");
|
||||
return {
|
||||
kind: string(item[0], "Dependency kind"),
|
||||
capability: string(item[1], "Dependency capability"),
|
||||
schema: string(item[2], "Dependency schema"),
|
||||
compatibility: string(item[3], "Dependency compatibility"),
|
||||
providerEndpoint: nullableString(item[9], "Dependency provider endpoint"),
|
||||
};
|
||||
});
|
||||
}
|
||||
|
||||
// The Rust owner (IdunnExpectedRoute::validate) accepts http, tcp and rudp
|
||||
// routes; a runtime is not entitled to a narrower admission than Idunn's.
|
||||
const ROUTE_SCHEMES: Record<string, { stable: string[]; candidate: string[] }> = {
|
||||
http: { stable: ["http://", "https://"], candidate: ["http://"] },
|
||||
tcp: { stable: ["tcp://"], candidate: ["tcp://"] },
|
||||
rudp: { stable: ["rudp://"], candidate: ["rudp://"] },
|
||||
};
|
||||
|
||||
function validateRoute(route: NonNullable<ExpectedIncarnation["route"]>): void {
|
||||
const schemes = ROUTE_SCHEMES[route.transport];
|
||||
if (!schemes) throw new Error("Idunn Expected route transport is unsupported.");
|
||||
if (!schemes.stable.some((scheme) => route.stableEndpoint.startsWith(scheme))
|
||||
|| !schemes.candidate.some((scheme) => route.candidateEndpoint.startsWith(scheme))) {
|
||||
throw new Error(`Idunn Expected ${route.transport} route endpoints use an unsupported scheme.`);
|
||||
}
|
||||
if (route.stableEndpoint === route.candidateEndpoint) throw new Error("Idunn Expected stable and candidate route endpoints are identical.");
|
||||
}
|
||||
|
||||
function decodeRoute(value: unknown): ExpectedIncarnation["route"] {
|
||||
if (value === null) return null;
|
||||
const route = array(value, 4, "Expected route");
|
||||
return {
|
||||
routeId: string(route[0], "Route id"),
|
||||
transport: string(route[1], "Route transport"),
|
||||
stableEndpoint: string(route[2], "Stable route endpoint"),
|
||||
candidateEndpoint: string(route[3], "Candidate route endpoint"),
|
||||
};
|
||||
}
|
||||
|
||||
function openProviderHealthIdentity(credentialBytes: Buffer): crypto.KeyObject {
|
||||
const fields = decodeArray(readProviderHealthIdentityCredential(credentialBytes), 10, "provider-health identity");
|
||||
const [schema, identityId, publicKeyValue, protectedSeedValue, protectorKind, binding, version, assurance, createdAt, enrollmentNonceValue] = fields;
|
||||
if (schema !== "gamecult.provider_health_identity.private.v1" || version !== "v1") throw new Error("Provider-health identity schema is unsupported.");
|
||||
string(createdAt, "Provider-health identity creation time");
|
||||
const enrollmentNonce = providerIdentityByteVector(enrollmentNonceValue, "Provider-health enrollment nonce");
|
||||
if (enrollmentNonce.length !== 32) throw new Error("Provider-health enrollment nonce has an invalid length.");
|
||||
const publicKey = Buffer.from(providerIdentityByteVector(publicKeyValue, "Provider-health public key"));
|
||||
const protectedSeed = Buffer.from(providerIdentityByteVector(protectedSeedValue, "Provider-health protected seed"));
|
||||
const machineId = readMachineId();
|
||||
if (!machineId) throw new Error("Linux machine-id is unavailable for provider-health identity.");
|
||||
const expectedBinding = `${PROVIDER_PROTECTOR_CONTEXT}:machine-id-sha256:${sha256Hex(Buffer.from(machineId))}`;
|
||||
if (protectorKind !== "linux_file_mode_machine_id_binding" || binding !== expectedBinding || assurance !== "os_installation_file_bound_cloneable_baseline") {
|
||||
throw new Error("Provider-health identity protector does not match this Linux installation.");
|
||||
}
|
||||
if (publicKey.length !== 32 || protectedSeed.length !== 32) throw new Error("Provider-health identity key material has an invalid length.");
|
||||
const mask = crypto.createHash("sha256").update(Buffer.concat([
|
||||
Buffer.from("gamecult-linux-service-seed-v1\0", "utf8"),
|
||||
Buffer.from(PROVIDER_PROTECTOR_CONTEXT, "utf8"),
|
||||
Buffer.from(expectedBinding, "utf8"),
|
||||
])).digest();
|
||||
const seed = Buffer.from(protectedSeed.map((value, index) => value ^ mask[index]!));
|
||||
const key = privateKeyFromSeed(seed);
|
||||
seed.fill(0);
|
||||
const derivedPublicKey = rawEd25519PublicKey(crypto.createPublicKey(key));
|
||||
const derivedId = sha256Hex(Buffer.concat([PROVIDER_ID_DOMAIN, derivedPublicKey]));
|
||||
if (!derivedPublicKey.equals(publicKey) || identityId !== derivedId) throw new Error("Provider-health private key differs from its enrolled identity.");
|
||||
return key;
|
||||
}
|
||||
|
||||
// Same sources, same order as the Rust identity protector.
|
||||
function readMachineId(): string {
|
||||
try {
|
||||
return fs.readFileSync("/etc/machine-id", "utf8").trim();
|
||||
} catch {
|
||||
return fs.readFileSync("/var/lib/dbus/machine-id", "utf8").trim();
|
||||
}
|
||||
}
|
||||
|
||||
function readProviderHealthIdentityCredential(bytes: Buffer): Uint8Array {
|
||||
const decoded = decode(bytes);
|
||||
if (!Array.isArray(decoded) || decoded.length !== 1) {
|
||||
throw new Error("Provider-health identity credential must contain exactly one envelope.");
|
||||
}
|
||||
const envelope = array(decoded[0], 5, "Provider-health identity envelope");
|
||||
if (envelope[0] !== "gamecult-provider-health-identity"
|
||||
|| envelope[1] !== "gamecult.provider_health_identity.private.v1"
|
||||
|| envelope[4] !== "gamecult.provider_health_identity.private.v1") {
|
||||
throw new Error("Provider-health identity credential belongs to a different profile or schema.");
|
||||
}
|
||||
string(envelope[3], "Provider-health identity stored-at time");
|
||||
return bytesValue(envelope[2], "Provider-health identity payload");
|
||||
}
|
||||
|
||||
function providerIdentityByteVector(value: unknown, label: string): Uint8Array {
|
||||
if (!Array.isArray(value) || value.some((byte) => typeof byte !== "number" || !Number.isInteger(byte) || byte < 0 || byte > 255)) {
|
||||
throw new Error(`${label} is not a byte vector.`);
|
||||
}
|
||||
return Uint8Array.from(value as number[]);
|
||||
}
|
||||
|
||||
function inheritedDescriptorMap(): Map<string, number> {
|
||||
if (!systemdListenPidMatches(process.env.LISTEN_PID, process.pid)) throw new Error("Inherited Idunn descriptors do not belong to this process.");
|
||||
const count = Number(process.env.LISTEN_FDS);
|
||||
const names = process.env.LISTEN_FDNAMES?.split(":") ?? [];
|
||||
if (!Number.isInteger(count) || count < 1 || names.length !== count) throw new Error("Inherited Idunn descriptor list is malformed.");
|
||||
return new Map(names.map((name, index) => [name, index + 3]));
|
||||
}
|
||||
|
||||
export function systemdListenPidMatches(listenPid: string | undefined, processPid: number): boolean {
|
||||
if (listenPid === String(processPid)) return true;
|
||||
// systemd sets LISTEN_PID in the host PID namespace. With PrivatePIDs=yes,
|
||||
// the service's main process is namespace PID 1 and cannot read that host
|
||||
// PID through its private /proc mount. A descendant has a PID greater than
|
||||
// 1 and must not reuse the inherited descriptor set.
|
||||
return processPid === 1 && /^\d+$/u.test(listenPid ?? "") && Number(listenPid) > 1;
|
||||
}
|
||||
|
||||
function readDescriptor(descriptor: number): Buffer {
|
||||
return fs.readFileSync(descriptor);
|
||||
}
|
||||
|
||||
function privateKeyFromSeed(seed: Uint8Array): crypto.KeyObject {
|
||||
return crypto.createPrivateKey({ key: Buffer.concat([ED25519_PKCS8_PREFIX, Buffer.from(seed)]), format: "der", type: "pkcs8" });
|
||||
}
|
||||
|
||||
function rawEd25519PublicKey(publicKey: crypto.KeyObject): Buffer {
|
||||
const der = publicKey.export({ type: "spki", format: "der" }) as Buffer;
|
||||
return Buffer.from(der.subarray(der.length - 32));
|
||||
}
|
||||
|
||||
function providerSignerIdentityId(privateKey: crypto.KeyObject): string {
|
||||
return sha256Hex(Buffer.concat([PROVIDER_ID_DOMAIN, rawEd25519PublicKey(crypto.createPublicKey(privateKey))]));
|
||||
}
|
||||
|
||||
function assertLeaseMatches(values: unknown[], authority: IdunnRuntimeAuthority, recentWarmingProofs: string[]): void {
|
||||
const expected = authority.expected;
|
||||
const activation = authority.activation;
|
||||
const matches = values[0] === IDUNN_PROCESS_WRITE_LEASE_SCHEMA
|
||||
&& values[1] === expected.target
|
||||
&& values[2] === expected.canonicalSha256
|
||||
&& values[3] === expected.planId
|
||||
&& values[4] === expected.incarnationId
|
||||
&& values[5] === expected.sealedReleaseId
|
||||
&& values[6] === activation.canonicalSha256
|
||||
&& values[7] === expected.stateSchemaGeneration
|
||||
&& values[8] === expected.stateContractSha256
|
||||
&& values[9] === expected.runtimeId
|
||||
&& values[10] === activation.runtimeInstanceId
|
||||
&& typeof values[11] === "string"
|
||||
&& recentWarmingProofs.includes(values[11])
|
||||
&& Number.isSafeInteger(values[12]) && Number(values[12]) > 0
|
||||
&& Number.isSafeInteger(values[13]) && Number(values[13]) > 0;
|
||||
if (!matches) throw new Error("Idunn process write lease does not match the current Expected incarnation.");
|
||||
}
|
||||
|
||||
function requiredEnvironment(name: string): string {
|
||||
const value = process.env[name]?.trim();
|
||||
if (!value) throw new Error(`${name} is required for Idunn runtime presence.`);
|
||||
return value;
|
||||
}
|
||||
|
||||
|
||||
function array(value: unknown, length: number, label: string): unknown[] {
|
||||
if (!Array.isArray(value) || value.length !== length) throw new Error(`${label} is not a ${length}-field positional contract.`);
|
||||
return value;
|
||||
}
|
||||
|
||||
function decodeArray(payload: Uint8Array, length: number, label: string): unknown[] {
|
||||
return array(decode(payload), length, label);
|
||||
}
|
||||
|
||||
function arrayOf(value: unknown, label: string): unknown[] {
|
||||
if (!Array.isArray(value)) throw new Error(`${label} is not an array.`);
|
||||
return value;
|
||||
}
|
||||
|
||||
function string(value: unknown, label: string): string {
|
||||
if (typeof value !== "string" || !value.trim() || value.trim() !== value || /[\u0000-\u001f\u007f]/u.test(value)) {
|
||||
throw new Error(`${label} is not a valid authority string.`);
|
||||
}
|
||||
return value;
|
||||
}
|
||||
|
||||
function nullableString(value: unknown, label: string): string | null {
|
||||
return value === null ? null : string(value, label);
|
||||
}
|
||||
|
||||
function number(value: unknown, label: string): number {
|
||||
if (typeof value !== "number" || !Number.isSafeInteger(value) || value < 0) throw new Error(`${label} is not a non-negative integer.`);
|
||||
return value;
|
||||
}
|
||||
|
||||
function bytes(value: unknown, label: string): Uint8Array {
|
||||
if (!(value instanceof Uint8Array)) throw new Error(`${label} is not bytes.`);
|
||||
return value;
|
||||
}
|
||||
|
||||
function bytesValue(value: unknown, label: string): Buffer {
|
||||
return Buffer.from(bytes(value, label));
|
||||
}
|
||||
|
||||
function prefixedSha256(bytes: Uint8Array): string {
|
||||
return `sha256-${sha256Hex(bytes)}`;
|
||||
}
|
||||
|
||||
function sha256Hex(bytes: Uint8Array): string {
|
||||
return crypto.createHash("sha256").update(bytes).digest("hex");
|
||||
}
|
||||
|
|
@ -197,3 +197,23 @@ export {
|
|||
type RuntimePresenceHealth,
|
||||
type RuntimePresenceState,
|
||||
} from "./runtime-presence-health";
|
||||
|
||||
export {
|
||||
IDUNN_EXPECTED_INCARNATION_SCHEMA,
|
||||
IDUNN_PROCESS_WRITE_LEASE_ENVIRONMENT,
|
||||
IDUNN_PROCESS_WRITE_LEASE_SCHEMA,
|
||||
IDUNN_RUNTIME_BUNDLE_ENVIRONMENT,
|
||||
IDUNN_RUNTIME_CANDIDATE_BIND_ENVIRONMENT,
|
||||
IDUNN_RUNTIME_ACTIVATION_SCHEMA,
|
||||
createIdunnRuntimeSigner,
|
||||
loadIdunnRuntimeAuthorityFromEnvironment,
|
||||
type IdunnRuntimeAuthority,
|
||||
type IdunnRuntimeSigner,
|
||||
type IdunnRuntimeSignerOptions,
|
||||
type SignedRuntimePresence,
|
||||
} from "./idunn-runtime-authority";
|
||||
export {
|
||||
createIdunnRuntimePresencePublisher,
|
||||
type IdunnRuntimePresencePublisher,
|
||||
type IdunnRuntimePresencePublisherOptions,
|
||||
} from "./idunn-odin-presence-publisher";
|
||||
|
|
|
|||
|
|
@ -1,4 +1,4 @@
|
|||
import Ajv2020, { type ErrorObject, type ValidateFunction } from "ajv/dist/2020";
|
||||
import Ajv2020, { type ErrorObject, type ValidateFunction } from "ajv/dist/2020.js";
|
||||
import type { CultCacheSchema } from "@gamecult/cultcache-ts";
|
||||
|
||||
export interface JsonSchemaContract<TValue> extends CultCacheSchema<TValue> {
|
||||
|
|
|
|||
|
|
@ -20,6 +20,8 @@
|
|||
|
||||
import { encode } from "@msgpack/msgpack";
|
||||
|
||||
import { truncateUtf8Bytes } from "./utf8-bound";
|
||||
|
||||
export const GAMECULT_RUNTIME_PRESENCE_HEALTH_SCHEMA = "gamecult.runtime_presence_health.v2";
|
||||
|
||||
/** Purpose for the stable provider-health signature over the proof payload. */
|
||||
|
|
@ -171,6 +173,9 @@ function presenceTuple(
|
|||
return fields;
|
||||
}
|
||||
|
||||
/** The Rust owner (`cultnet-rs`) bounds presence detail by UTF-8 bytes, not UTF-16 units. */
|
||||
export const RUNTIME_PRESENCE_DETAIL_MAX_BYTES = 512;
|
||||
|
||||
/**
|
||||
* Reject statements the contract forbids, before they are signed.
|
||||
*
|
||||
|
|
@ -185,7 +190,7 @@ export function validateRuntimePresence(presence: RuntimePresenceHealth): void {
|
|||
if (presence.observedAtUnixMillis <= 0 || !Number.isSafeInteger(presence.observedAtUnixMillis)) {
|
||||
throw new Error("runtime presence observation time must be a positive integer");
|
||||
}
|
||||
if (presence.detail.length > 512 || /\p{Cc}/u.test(presence.detail)) {
|
||||
if (truncateUtf8Bytes(presence.detail, RUNTIME_PRESENCE_DETAIL_MAX_BYTES) !== presence.detail || /\p{Cc}/u.test(presence.detail)) {
|
||||
throw new Error("runtime presence detail is too long or carries control characters");
|
||||
}
|
||||
if (presence.state === "warming" && presence.writeLeaseSha256 !== null) {
|
||||
|
|
|
|||
|
|
@ -19,6 +19,10 @@ import { encode } from "@msgpack/msgpack";
|
|||
import { CultNetRudpSession, decodeRudpPacket, encodeRudpPacket } from "./rudp";
|
||||
import type { CultNetRudpPacket } from "./rudp";
|
||||
import { encodeCultNetMessageForWire } from "./contracts";
|
||||
import { truncateUtf8Bytes } from "./utf8-bound";
|
||||
|
||||
/** The Rust owner (`cultnet-rs`) bounds daemon health detail by UTF-8 bytes. */
|
||||
export const DAEMON_HEALTH_DETAIL_MAX_BYTES = 512;
|
||||
|
||||
export const CULTNET_RUDP_PROTOCOL_ID = "cultnet.transport.rudp.v0";
|
||||
|
||||
|
|
@ -120,15 +124,7 @@ export async function publishSignedDaemonHealth(
|
|||
|
||||
const observedAt = health.observedAt || new Date().toISOString();
|
||||
const signed = publisher.privateKey ? signedDaemonHealthPayload(publisher, health, observedAt) : null;
|
||||
const payload = signed?.payload || encode([
|
||||
publisher.daemonId,
|
||||
health.state,
|
||||
String(health.detail || "").slice(0, 512),
|
||||
observedAt,
|
||||
publisher.healthContract,
|
||||
"daemon-published",
|
||||
CULTNET_RUDP_PROTOCOL_ID,
|
||||
]);
|
||||
const payload = signed?.payload || unsignedDaemonHealthPayload(publisher, health, observedAt);
|
||||
|
||||
const message = {
|
||||
schemaVersion: "cultnet.document_put_raw.v0",
|
||||
|
|
@ -165,6 +161,22 @@ export async function publishSignedDaemonHealth(
|
|||
}
|
||||
}
|
||||
|
||||
export function unsignedDaemonHealthPayload(
|
||||
publisher: SignedDaemonHealthPublisher,
|
||||
health: DaemonHealth,
|
||||
observedAt: string,
|
||||
): Uint8Array {
|
||||
return encode([
|
||||
publisher.daemonId,
|
||||
health.state,
|
||||
truncateUtf8Bytes(String(health.detail || ""), DAEMON_HEALTH_DETAIL_MAX_BYTES),
|
||||
observedAt,
|
||||
publisher.healthContract,
|
||||
"daemon-published",
|
||||
CULTNET_RUDP_PROTOCOL_ID,
|
||||
]);
|
||||
}
|
||||
|
||||
export function signedDaemonHealthPayload(
|
||||
publisher: SignedDaemonHealthPublisher,
|
||||
health: DaemonHealth,
|
||||
|
|
@ -185,7 +197,7 @@ export function signedDaemonHealthPayload(
|
|||
publisher.healthContract,
|
||||
publisher.sourceRuntimeId,
|
||||
health.state,
|
||||
String(health.detail || "").slice(0, 512),
|
||||
truncateUtf8Bytes(String(health.detail || ""), DAEMON_HEALTH_DETAIL_MAX_BYTES),
|
||||
publisher.signerIdentityId,
|
||||
publisher.publisherIncarnationId,
|
||||
publisher.publisherSequence,
|
||||
|
|
|
|||
20
packages/cultnet-ts/src/utf8-bound.ts
Normal file
20
packages/cultnet-ts/src/utf8-bound.ts
Normal file
|
|
@ -0,0 +1,20 @@
|
|||
/**
|
||||
* Longest prefix of `value` whose UTF-8 encoding fits in `maxBytes`, cut on a
|
||||
* code point boundary. Rust owners (`cultnet-rs`) bound strings by UTF-8 bytes,
|
||||
* not UTF-16 units, so every TypeScript publisher bounds through this one path.
|
||||
*
|
||||
* Lone surrogates are replaced with U+FFFD first: they have no UTF-8 encoding,
|
||||
* and a msgpack writer would otherwise emit invalid bytes that Rust refuses.
|
||||
* A value is therefore in bounds exactly when this returns it unchanged.
|
||||
*/
|
||||
export function truncateUtf8Bytes(value: string, maxBytes: number): string {
|
||||
const wellFormed = (value as string & { toWellFormed(): string }).toWellFormed();
|
||||
let bytes = 0;
|
||||
let end = 0;
|
||||
for (const char of wellFormed) {
|
||||
bytes += Buffer.byteLength(char, "utf8");
|
||||
if (bytes > maxBytes) break;
|
||||
end += char.length;
|
||||
}
|
||||
return wellFormed.slice(0, end);
|
||||
}
|
||||
1
packages/cultnet-ts/test/fixtures/idunn-runtime/.gitattributes
vendored
Normal file
1
packages/cultnet-ts/test/fixtures/idunn-runtime/.gitattributes
vendored
Normal file
|
|
@ -0,0 +1 @@
|
|||
* -text
|
||||
42
packages/cultnet-ts/test/fixtures/idunn-runtime/README.md
vendored
Normal file
42
packages/cultnet-ts/test/fixtures/idunn-runtime/README.md
vendored
Normal file
|
|
@ -0,0 +1,42 @@
|
|||
# Idunn runtime fixtures
|
||||
|
||||
Written by the Rust owner, not by the TypeScript tests. Regenerate with
|
||||
`packages/cultnet-rs/examples/idunn_runtime_fixture.rs` (CultLib `9ba6ac4`; it uses
|
||||
cultnet-rs only, and Idunn's `IdunnRuntimeActivationLaunch` is that same crate's).
|
||||
It needs Linux and a machine-id equal to the `machine-id` file here, because the
|
||||
provider identity is bound to it. On Yggdrasil:
|
||||
|
||||
DOCKER_ARGS='--cap-add SYS_ADMIN --security-opt apparmor=unconfined' bash ygg-verify.sh <CultLib> HEAD rust 'cd packages/cultnet-rs && cp <fixed-machine-id> /tmp/mid && mount --bind /tmp/mid /etc/machine-id && cargo run -q --example idunn_runtime_fixture /tmp/out'
|
||||
|
||||
then copy `/tmp/out` over this directory. `--cap-add SYS_ADMIN` exists only so the bind mount can present the committed `machine-id`, which keeps Yggdrasil's real machine-id out of the repo. Every `presence-*.bin` was accepted by
|
||||
`authenticate_runtime_presence_claim` and correlated by
|
||||
`correlate_runtime_presence_claim` before being written; the
|
||||
`below-minimum` vector correlates to exactly `expected-capability-000-capacity`.
|
||||
Ed25519 is deterministic, so the TypeScript signer must reproduce them byte for byte.
|
||||
|
||||
`service-stateful` is the lease-bound shape (`streampixels-service`, state lineage set,
|
||||
`write_lease_required: true`). Rust issues `lease.cc`, which names the digest of its
|
||||
`presence-warming.bin`; `presence-active.bin` and `presence-degraded.bin` are sequence 2 and
|
||||
carry that lease's digest. `lease-other-warming.cc` names a different warming digest and
|
||||
`lease-other-target.cc` names another target; the TypeScript lease check must refuse both.
|
||||
|
||||
## Generating a consumer's own set
|
||||
|
||||
The generator takes its specification as input, so a consumer needs no patch to CultLib. The
|
||||
specification is command-line flags; `@<file>` splices in a response file (one `--flag value`
|
||||
per line, `#` comments). CultLib's own sets are `fixture.args` here:
|
||||
|
||||
cargo run -q --example idunn_runtime_fixture /tmp/out @<path>/fixture.args
|
||||
|
||||
The consumer keeps its own `.args` file in its repository and runs the same command with the
|
||||
same machine-id bind mount as above. Global flags: `--source-repository`, `--detail`. Each
|
||||
`--set <dir>` opens a set written to `<out>/<dir>`, and the flags after it configure it:
|
||||
`--target`, `--transport`, `--stable`, `--candidate` (required); `--capability` (default
|
||||
`<target>.api`), `--schema` (default `<capability>.v1`), `--health-contract` (default
|
||||
`<target>.runtime-health`), `--minimum-capacity` (default 1), `--stateful` with
|
||||
`--state-schema-generation` and `--lease-other-target`, and repeatable
|
||||
`--dependency kind=..,capability=..,schema=..,provider=..,endpoint=..` (optional `compatibility`,
|
||||
`capacity`, `startup`, `authority`, `projection`). The full grammar is the header of the example.
|
||||
|
||||
Every generation enrolls fresh keys, so regenerated bytes differ from the committed ones. The
|
||||
committed set stays; `fixture.args` regenerates the same file list, sizes and structure.
|
||||
35
packages/cultnet-ts/test/fixtures/idunn-runtime/fixture.args
vendored
Normal file
35
packages/cultnet-ts/test/fixtures/idunn-runtime/fixture.args
vendored
Normal file
|
|
@ -0,0 +1,35 @@
|
|||
# CultLib's own fixture sets, in the generator's response-file form:
|
||||
# idunn_runtime_fixture <out-dir> @fixture.args
|
||||
--source-repository github.com/GameCult/StreamPixels
|
||||
--detail route-observation:route-challenge-1
|
||||
|
||||
--set web
|
||||
--target streampixels-web
|
||||
--transport http
|
||||
--stable http://127.0.0.1:8830
|
||||
--candidate http://127.0.0.1:18830
|
||||
|
||||
--set service
|
||||
--target streampixels-service
|
||||
--transport tcp
|
||||
--stable tcp://127.0.0.1:8831
|
||||
--candidate tcp://127.0.0.1:18831
|
||||
--minimum-capacity 2
|
||||
--dependency kind=shared-infrastructure,capability=odin.verse-rendezvous,schema=odin.verse-topology.v1,provider=odin,endpoint=rudp://127.0.0.1:47871
|
||||
|
||||
--set service-stateful
|
||||
--target streampixels-service
|
||||
--transport tcp
|
||||
--stable tcp://127.0.0.1:8833
|
||||
--candidate tcp://127.0.0.1:18833
|
||||
--minimum-capacity 2
|
||||
--stateful
|
||||
--state-schema-generation streampixels-state-v1
|
||||
--lease-other-target streampixels-web
|
||||
--dependency kind=shared-infrastructure,capability=odin.verse-rendezvous,schema=odin.verse-topology.v1,provider=odin,endpoint=rudp://127.0.0.1:47871
|
||||
|
||||
--set rudp-route
|
||||
--target streampixels-rudp
|
||||
--transport rudp
|
||||
--stable rudp://127.0.0.1:8832
|
||||
--candidate rudp://127.0.0.1:18832
|
||||
1
packages/cultnet-ts/test/fixtures/idunn-runtime/machine-id
vendored
Normal file
1
packages/cultnet-ts/test/fixtures/idunn-runtime/machine-id
vendored
Normal file
|
|
@ -0,0 +1 @@
|
|||
c1c1c1c1c1c1c1c1c1c1c1c1c1c1c1c1
|
||||
1
packages/cultnet-ts/test/fixtures/idunn-runtime/rudp-route/activation-key.seed
vendored
Normal file
1
packages/cultnet-ts/test/fixtures/idunn-runtime/rudp-route/activation-key.seed
vendored
Normal file
|
|
@ -0,0 +1 @@
|
|||
<EFBFBD>_<EFBFBD>#<23>/<2F>"Q0\<5C>iC<69>]\ʝ<><CA9D><EFBFBD><EFBFBD>;<3B>Y<EFBFBD><14><>k
|
||||
BIN
packages/cultnet-ts/test/fixtures/idunn-runtime/rudp-route/activation.cc
vendored
Normal file
BIN
packages/cultnet-ts/test/fixtures/idunn-runtime/rudp-route/activation.cc
vendored
Normal file
Binary file not shown.
BIN
packages/cultnet-ts/test/fixtures/idunn-runtime/rudp-route/expected.cc
vendored
Normal file
BIN
packages/cultnet-ts/test/fixtures/idunn-runtime/rudp-route/expected.cc
vendored
Normal file
Binary file not shown.
BIN
packages/cultnet-ts/test/fixtures/idunn-runtime/rudp-route/presence-active.bin
vendored
Normal file
BIN
packages/cultnet-ts/test/fixtures/idunn-runtime/rudp-route/presence-active.bin
vendored
Normal file
Binary file not shown.
BIN
packages/cultnet-ts/test/fixtures/idunn-runtime/rudp-route/presence-warming.bin
vendored
Normal file
BIN
packages/cultnet-ts/test/fixtures/idunn-runtime/rudp-route/presence-warming.bin
vendored
Normal file
Binary file not shown.
BIN
packages/cultnet-ts/test/fixtures/idunn-runtime/rudp-route/provider-identity.credential
vendored
Normal file
BIN
packages/cultnet-ts/test/fixtures/idunn-runtime/rudp-route/provider-identity.credential
vendored
Normal file
Binary file not shown.
1
packages/cultnet-ts/test/fixtures/idunn-runtime/service-stateful/activation-key.seed
vendored
Normal file
1
packages/cultnet-ts/test/fixtures/idunn-runtime/service-stateful/activation-key.seed
vendored
Normal file
|
|
@ -0,0 +1 @@
|
|||
Kýaźz´-2‰ËˇV>)ë»xěşÚĎ®˘T
=/‰*
|
||||
BIN
packages/cultnet-ts/test/fixtures/idunn-runtime/service-stateful/activation.cc
vendored
Normal file
BIN
packages/cultnet-ts/test/fixtures/idunn-runtime/service-stateful/activation.cc
vendored
Normal file
Binary file not shown.
BIN
packages/cultnet-ts/test/fixtures/idunn-runtime/service-stateful/expected.cc
vendored
Normal file
BIN
packages/cultnet-ts/test/fixtures/idunn-runtime/service-stateful/expected.cc
vendored
Normal file
Binary file not shown.
BIN
packages/cultnet-ts/test/fixtures/idunn-runtime/service-stateful/lease-other-target.cc
vendored
Normal file
BIN
packages/cultnet-ts/test/fixtures/idunn-runtime/service-stateful/lease-other-target.cc
vendored
Normal file
Binary file not shown.
BIN
packages/cultnet-ts/test/fixtures/idunn-runtime/service-stateful/lease-other-warming.cc
vendored
Normal file
BIN
packages/cultnet-ts/test/fixtures/idunn-runtime/service-stateful/lease-other-warming.cc
vendored
Normal file
Binary file not shown.
BIN
packages/cultnet-ts/test/fixtures/idunn-runtime/service-stateful/lease.cc
vendored
Normal file
BIN
packages/cultnet-ts/test/fixtures/idunn-runtime/service-stateful/lease.cc
vendored
Normal file
Binary file not shown.
BIN
packages/cultnet-ts/test/fixtures/idunn-runtime/service-stateful/presence-active.bin
vendored
Normal file
BIN
packages/cultnet-ts/test/fixtures/idunn-runtime/service-stateful/presence-active.bin
vendored
Normal file
Binary file not shown.
BIN
packages/cultnet-ts/test/fixtures/idunn-runtime/service-stateful/presence-degraded.bin
vendored
Normal file
BIN
packages/cultnet-ts/test/fixtures/idunn-runtime/service-stateful/presence-degraded.bin
vendored
Normal file
Binary file not shown.
BIN
packages/cultnet-ts/test/fixtures/idunn-runtime/service-stateful/presence-warming.bin
vendored
Normal file
BIN
packages/cultnet-ts/test/fixtures/idunn-runtime/service-stateful/presence-warming.bin
vendored
Normal file
Binary file not shown.
BIN
packages/cultnet-ts/test/fixtures/idunn-runtime/service-stateful/provider-identity.credential
vendored
Normal file
BIN
packages/cultnet-ts/test/fixtures/idunn-runtime/service-stateful/provider-identity.credential
vendored
Normal file
Binary file not shown.
1
packages/cultnet-ts/test/fixtures/idunn-runtime/service/activation-key.seed
vendored
Normal file
1
packages/cultnet-ts/test/fixtures/idunn-runtime/service/activation-key.seed
vendored
Normal file
|
|
@ -0,0 +1 @@
|
|||
<EFBFBD><EFBFBD><EFBFBD>Bf<EFBFBD><EFBFBD>=?<3F><><EFBFBD>Z<EFBFBD>j<EFBFBD><6A><EFBFBD>&<26><15><>3<EFBFBD><33>ܟf<DC9F>mJ
|
||||
BIN
packages/cultnet-ts/test/fixtures/idunn-runtime/service/activation.cc
vendored
Normal file
BIN
packages/cultnet-ts/test/fixtures/idunn-runtime/service/activation.cc
vendored
Normal file
Binary file not shown.
BIN
packages/cultnet-ts/test/fixtures/idunn-runtime/service/expected.cc
vendored
Normal file
BIN
packages/cultnet-ts/test/fixtures/idunn-runtime/service/expected.cc
vendored
Normal file
Binary file not shown.
BIN
packages/cultnet-ts/test/fixtures/idunn-runtime/service/presence-active-below-minimum.bin
vendored
Normal file
BIN
packages/cultnet-ts/test/fixtures/idunn-runtime/service/presence-active-below-minimum.bin
vendored
Normal file
Binary file not shown.
BIN
packages/cultnet-ts/test/fixtures/idunn-runtime/service/presence-active.bin
vendored
Normal file
BIN
packages/cultnet-ts/test/fixtures/idunn-runtime/service/presence-active.bin
vendored
Normal file
Binary file not shown.
BIN
packages/cultnet-ts/test/fixtures/idunn-runtime/service/presence-warming.bin
vendored
Normal file
BIN
packages/cultnet-ts/test/fixtures/idunn-runtime/service/presence-warming.bin
vendored
Normal file
Binary file not shown.
BIN
packages/cultnet-ts/test/fixtures/idunn-runtime/service/provider-identity.credential
vendored
Normal file
BIN
packages/cultnet-ts/test/fixtures/idunn-runtime/service/provider-identity.credential
vendored
Normal file
Binary file not shown.
1
packages/cultnet-ts/test/fixtures/idunn-runtime/web/activation-key.seed
vendored
Normal file
1
packages/cultnet-ts/test/fixtures/idunn-runtime/web/activation-key.seed
vendored
Normal file
|
|
@ -0,0 +1 @@
|
|||
¯ÂOd×f¯l*oµ‘ÀFªv‰n<E280B0>hLûÑpšS´p
|
||||
BIN
packages/cultnet-ts/test/fixtures/idunn-runtime/web/activation.cc
vendored
Normal file
BIN
packages/cultnet-ts/test/fixtures/idunn-runtime/web/activation.cc
vendored
Normal file
Binary file not shown.
BIN
packages/cultnet-ts/test/fixtures/idunn-runtime/web/expected.cc
vendored
Normal file
BIN
packages/cultnet-ts/test/fixtures/idunn-runtime/web/expected.cc
vendored
Normal file
Binary file not shown.
BIN
packages/cultnet-ts/test/fixtures/idunn-runtime/web/presence-active.bin
vendored
Normal file
BIN
packages/cultnet-ts/test/fixtures/idunn-runtime/web/presence-active.bin
vendored
Normal file
Binary file not shown.
BIN
packages/cultnet-ts/test/fixtures/idunn-runtime/web/presence-warming.bin
vendored
Normal file
BIN
packages/cultnet-ts/test/fixtures/idunn-runtime/web/presence-warming.bin
vendored
Normal file
Binary file not shown.
BIN
packages/cultnet-ts/test/fixtures/idunn-runtime/web/provider-identity.credential
vendored
Normal file
BIN
packages/cultnet-ts/test/fixtures/idunn-runtime/web/provider-identity.credential
vendored
Normal file
Binary file not shown.
391
packages/cultnet-ts/test/idunn-runtime-authority.test.ts
Normal file
391
packages/cultnet-ts/test/idunn-runtime-authority.test.ts
Normal file
|
|
@ -0,0 +1,391 @@
|
|||
import { test, type TestContext } from "node:test";
|
||||
import assert from "node:assert/strict";
|
||||
import { spawnSync } from "node:child_process";
|
||||
import dgram from "node:dgram";
|
||||
import fs from "node:fs";
|
||||
import path from "node:path";
|
||||
import { decode, encode } from "@msgpack/msgpack";
|
||||
|
||||
import {
|
||||
createIdunnRuntimePresencePublisher,
|
||||
createIdunnRuntimeSigner,
|
||||
loadIdunnRuntimeAuthorityFromEnvironment,
|
||||
type IdunnRuntimeAuthority,
|
||||
} from "../src";
|
||||
import { systemdListenPidMatches } from "../src/idunn-runtime-authority";
|
||||
import type { CultNetSnapshotRequestMessage } from "../src/contracts";
|
||||
import { CultNetRudpSession, decodeRudpPacket, encodeRudpPacket } from "../src/rudp";
|
||||
import { RUNTIME_PRESENCE_SLOT } from "../src/runtime-presence-health";
|
||||
|
||||
// Every input below was written by the Rust owner; see fixtures/idunn-runtime/README.md.
|
||||
// The only values this file pins are the ones the generator also pins.
|
||||
const FIXTURES = path.join(__dirname, "..", "..", "test", "fixtures", "idunn-runtime");
|
||||
const OBSERVED_AT = 1_790_000_000_000;
|
||||
const CHALLENGE: CultNetSnapshotRequestMessage = {
|
||||
schemaVersion: "cultnet.snapshot_request.v0",
|
||||
messageId: "route-challenge-1",
|
||||
};
|
||||
|
||||
type FixtureSet = "web" | "service" | "rudp-route" | "service-stateful";
|
||||
|
||||
function fixtureFile(set: FixtureSet, name: string): Buffer {
|
||||
return fs.readFileSync(path.join(FIXTURES, set, name));
|
||||
}
|
||||
|
||||
/** The Expected fields the tests need, read from the Rust-written file rather than re-spelled. */
|
||||
function expectedFacts(set: FixtureSet) {
|
||||
const store = decode(fixtureFile(set, "expected.cc")) as unknown[][][];
|
||||
const values = decode(store[2]![0]![3] as Uint8Array) as unknown[];
|
||||
const route = values[15] as string[];
|
||||
const capabilities = (values[16] as Array<[string, string, string, number]>).map(([capability, schema, compatibility, minimum]) => ({
|
||||
capability, schema, compatibility, capacity: minimum,
|
||||
}));
|
||||
const dependencies = values[17] as unknown[][];
|
||||
return {
|
||||
target: values[1] as string,
|
||||
healthContract: values[10] as string,
|
||||
candidate: route[3]!,
|
||||
capabilities,
|
||||
odinEndpoint: dependencies.map((dependency) => dependency[9] as string)[0],
|
||||
};
|
||||
}
|
||||
|
||||
/** Points the process at one Rust-written bundle and its inherited descriptors, as Idunn's systemd unit would. */
|
||||
function openAuthority(
|
||||
context: TestContext,
|
||||
set: FixtureSet,
|
||||
options: { machineId?: "etc" | "dbus"; lease?: string } = {},
|
||||
): IdunnRuntimeAuthority {
|
||||
const facts = expectedFacts(set);
|
||||
const originalEnvironment = { ...process.env };
|
||||
context.after(() => {
|
||||
for (const key of Object.keys(process.env)) if (!(key in originalEnvironment)) delete process.env[key];
|
||||
Object.assign(process.env, originalEnvironment);
|
||||
});
|
||||
process.env.GAMECULT_IDUNN_RUNTIME_BUNDLE = path.join(FIXTURES, set);
|
||||
process.env.GAMECULT_IDUNN_CANDIDATE_BIND = facts.candidate;
|
||||
if (options.lease) process.env.GAMECULT_IDUNN_PROCESS_WRITE_LEASE = path.join(FIXTURES, set, options.lease);
|
||||
else delete process.env.GAMECULT_IDUNN_PROCESS_WRITE_LEASE;
|
||||
process.env.LISTEN_PID = String(process.pid);
|
||||
process.env.LISTEN_FDS = "2";
|
||||
process.env.LISTEN_FDNAMES = "gamecult-idunn-runtime-activation-key:gamecult-runtime-presence-identity";
|
||||
const machineId = fs.readFileSync(path.join(FIXTURES, "machine-id"), "utf8");
|
||||
const realReadFileSync = fs.readFileSync.bind(fs);
|
||||
context.mock.method(fs, "readFileSync", (filePath: fs.PathOrFileDescriptor, ...args: unknown[]) => {
|
||||
if (filePath === 3) return fixtureFile(set, "activation-key.seed");
|
||||
if (filePath === 4) return fixtureFile(set, "provider-identity.credential");
|
||||
if (filePath === "/etc/machine-id") {
|
||||
if (options.machineId === "dbus") throw Object.assign(new Error("ENOENT"), { code: "ENOENT" });
|
||||
return machineId;
|
||||
}
|
||||
if (filePath === "/var/lib/dbus/machine-id") return machineId;
|
||||
return realReadFileSync(filePath as never, ...args as never[]);
|
||||
});
|
||||
return loadIdunnRuntimeAuthorityFromEnvironment(facts.target, facts.healthContract);
|
||||
}
|
||||
|
||||
function signerFor(context: TestContext, set: FixtureSet, capacityDelta = 0, lease?: string) {
|
||||
const authority = openAuthority(context, set, { lease });
|
||||
const capabilities = expectedFacts(set).capabilities.map((capability) => ({ ...capability, capacity: capability.capacity + capacityDelta }));
|
||||
return createIdunnRuntimeSigner({ authority, capabilities });
|
||||
}
|
||||
|
||||
function freezeClock(context: TestContext): void {
|
||||
context.mock.method(Date, "now", () => OBSERVED_AT);
|
||||
}
|
||||
|
||||
test("matches systemd's host PID for the private PID namespace init only", () => {
|
||||
assert.equal(systemdListenPidMatches(String(process.pid), process.pid), true);
|
||||
assert.equal(systemdListenPidMatches("1725346", 1), true);
|
||||
assert.equal(systemdListenPidMatches("1725346", 2), false);
|
||||
assert.equal(systemdListenPidMatches("not-a-pid", 1), false);
|
||||
assert.equal(systemdListenPidMatches(undefined, 1), false);
|
||||
});
|
||||
|
||||
for (const set of ["web", "service", "rudp-route"] as const) {
|
||||
test(`opens the Rust-written ${set} bundle with no Odin endpoint, whatever route transport Rust admits`, (context) => {
|
||||
const authority = openAuthority(context, set);
|
||||
assert.equal(authority.expected.target, expectedFacts(set).target);
|
||||
assert.equal(authority.boundEndpoint, expectedFacts(set).candidate);
|
||||
});
|
||||
}
|
||||
|
||||
test("a target that declares no Odin dependency opens and answers Idunn's challenge without one", (context) => {
|
||||
assert.equal(expectedFacts("web").odinEndpoint, undefined);
|
||||
const signer = signerFor(context, "web");
|
||||
assert.ok(signer.answerRouteObservation(CHALLENGE).payload.byteLength > 0);
|
||||
});
|
||||
|
||||
test("finds the machine-id at the dbus path when /etc/machine-id is absent, as the Rust protector does", (context) => {
|
||||
assert.ok(openAuthority(context, "web", { machineId: "dbus" }));
|
||||
});
|
||||
|
||||
test("rejects a credential file holding more than one envelope", (context) => {
|
||||
openAuthority(context, "web");
|
||||
const credential = decode(fixtureFile("web", "provider-identity.credential")) as unknown[][];
|
||||
const doubled = Buffer.from(encode([...credential, ...credential]));
|
||||
const realReadFileSync = fs.readFileSync;
|
||||
context.mock.method(fs, "readFileSync", (filePath: fs.PathOrFileDescriptor, ...args: unknown[]) =>
|
||||
filePath === 4 ? doubled : (realReadFileSync as (...all: unknown[]) => unknown)(filePath, ...args));
|
||||
assert.throws(
|
||||
() => loadIdunnRuntimeAuthorityFromEnvironment(expectedFacts("web").target, expectedFacts("web").healthContract),
|
||||
/exactly one envelope/,
|
||||
);
|
||||
});
|
||||
|
||||
function presenceSlot(document: { payload: Uint8Array }, slot: number): unknown {
|
||||
return (decode(document.payload) as unknown[])[slot];
|
||||
}
|
||||
|
||||
// Every committed vector is asserted, dead ones included. Stateless sets sign at sequence 1.
|
||||
for (const set of ["web", "service", "rudp-route"] as const) {
|
||||
test(`${set}: a fresh signer answers warming, and after reportHealth('active') answers active, byte for byte as the Rust-verified vectors`, (context) => {
|
||||
freezeClock(context);
|
||||
assert.deepEqual(Buffer.from(signerFor(context, set).answerRouteObservation(CHALLENGE).payload), fixtureFile(set, "presence-warming.bin"));
|
||||
const active = signerFor(context, set);
|
||||
active.reportHealth("active");
|
||||
assert.deepEqual(Buffer.from(active.answerRouteObservation(CHALLENGE).payload), fixtureFile(set, "presence-active.bin"));
|
||||
});
|
||||
}
|
||||
|
||||
test("a shortfall signs the vector Rust correlates to the typed capacity disagreement", (context) => {
|
||||
freezeClock(context);
|
||||
const signer = signerFor(context, "service", -1);
|
||||
signer.reportHealth("active");
|
||||
assert.deepEqual(Buffer.from(signer.answerRouteObservation(CHALLENGE).payload), fixtureFile("service", "presence-active-below-minimum.bin"));
|
||||
});
|
||||
|
||||
test("the signer owns the reported health: a fresh signer is warming, reportHealth moves it, the sequence keeps counting", (context) => {
|
||||
freezeClock(context);
|
||||
const signer = signerFor(context, "web");
|
||||
const first = signer.answerRouteObservation(CHALLENGE);
|
||||
assert.equal(presenceSlot(first, RUNTIME_PRESENCE_SLOT.state), "warming");
|
||||
assert.equal(presenceSlot(signer.sign("detail").document, RUNTIME_PRESENCE_SLOT.state), "warming");
|
||||
signer.reportHealth("active");
|
||||
const third = signer.answerRouteObservation(CHALLENGE);
|
||||
assert.equal(presenceSlot(third, RUNTIME_PRESENCE_SLOT.state), "active");
|
||||
assert.equal(presenceSlot(third, RUNTIME_PRESENCE_SLOT.publisherSequence), 3);
|
||||
});
|
||||
|
||||
test("answers locally: synchronously, with no socket opened", (context) => {
|
||||
const sockets = context.mock.method(dgram, "createSocket");
|
||||
const signer = signerFor(context, "web");
|
||||
const answer = signer.answerRouteObservation(CHALLENGE);
|
||||
assert.equal(typeof (answer as unknown as { then?: unknown }).then, "undefined");
|
||||
assert.equal(sockets.mock.callCount(), 0);
|
||||
});
|
||||
|
||||
test("refuses a challenge that does not ask for this runtime's presence", (context) => {
|
||||
const signer = signerFor(context, "web");
|
||||
const cases: CultNetSnapshotRequestMessage[] = [
|
||||
{ ...CHALLENGE, messageId: "" },
|
||||
{ ...CHALLENGE, messageId: " padded" },
|
||||
{ ...CHALLENGE, recordKeys: ["another-target"] },
|
||||
{ ...CHALLENGE, schemaIds: ["another.schema"] },
|
||||
{ ...CHALLENGE, shardId: "shard-1" },
|
||||
];
|
||||
for (const request of cases) assert.throws(() => signer.answerRouteObservation(request), /route observation/);
|
||||
});
|
||||
|
||||
async function startOdinPeer(context: TestContext, endpoint: string) {
|
||||
const peer = dgram.createSocket("udp4");
|
||||
const port = Number(endpoint.slice(endpoint.lastIndexOf(":") + 1));
|
||||
await new Promise<void>((resolve, reject) => {
|
||||
peer.once("error", reject);
|
||||
peer.bind(port, "127.0.0.1", resolve);
|
||||
});
|
||||
context.after(() => peer.close());
|
||||
const state = {
|
||||
reject: false,
|
||||
received: [] as Array<{ schemaVersion?: string; document: { payload: Uint8Array } }>,
|
||||
responseAck: undefined as number | undefined,
|
||||
failure: undefined as Error | undefined,
|
||||
};
|
||||
let serverSession: CultNetRudpSession | undefined;
|
||||
peer.on("message", (wire, remote) => {
|
||||
try {
|
||||
const packet = decodeRudpPacket(wire);
|
||||
if (packet.packetType === "connect") {
|
||||
serverSession = new CultNetRudpSession({ connectionId: packet.connectionId, initialSequence: 100 });
|
||||
peer.send(encodeRudpPacket(serverSession.acceptConnect(packet, Date.now())), remote.port, remote.address);
|
||||
return;
|
||||
}
|
||||
if (!serverSession) throw new Error("Publisher sent data before establishing RUDP.");
|
||||
const frame = serverSession.receive(packet, Date.now()).delivered.find((candidate) => candidate.channelId === "schema");
|
||||
if (!frame) return;
|
||||
state.received.push(decode(frame.payload) as never);
|
||||
const [response] = serverSession.sendMany("schema", encode(state.reject
|
||||
? { schemaVersion: "cultnet.error.v0", error: "test admission denied", routingHint: null, code: null, details: null }
|
||||
: { schemaVersion: "cultnet.snapshot_response.v0", messageId: "ack", documents: [] }), {
|
||||
reliable: true,
|
||||
ordered: true,
|
||||
nowMs: Date.now(),
|
||||
});
|
||||
assert.ok(response);
|
||||
state.responseAck = response.ack;
|
||||
peer.send(encodeRudpPacket(response), remote.port, remote.address);
|
||||
} catch (error) {
|
||||
state.failure = error as Error;
|
||||
}
|
||||
});
|
||||
return state;
|
||||
}
|
||||
|
||||
test("the Odin publisher publishes the signer's document to the endpoint Expected names and surfaces Odin's rejection", async (context) => {
|
||||
const endpoint = expectedFacts("service").odinEndpoint!;
|
||||
const peer = await startOdinPeer(context, endpoint);
|
||||
const signer = signerFor(context, "service");
|
||||
const publisher = createIdunnRuntimePresencePublisher({ signer, endpoint });
|
||||
|
||||
await publisher.publish("accepted presence");
|
||||
assert.equal(peer.received[0]?.schemaVersion, "cultnet.document_put_raw.v0");
|
||||
const published = decode(peer.received[0]!.document.payload) as unknown[];
|
||||
assert.equal(published[RUNTIME_PRESENCE_SLOT.state], "warming");
|
||||
assert.equal(published[RUNTIME_PRESENCE_SLOT.publisherSequence], 1);
|
||||
assert.equal(peer.responseAck, 2, "the response data packet must acknowledge the publisher's reliable schema packet");
|
||||
|
||||
peer.reject = true;
|
||||
signer.reportHealth("active");
|
||||
await assert.rejects(publisher.publish("denied presence"), /Odin rejected runtime presence: test admission denied/);
|
||||
assert.equal(peer.failure, undefined, peer.failure?.message);
|
||||
});
|
||||
|
||||
test("the Odin publisher leaves a capability shortfall to the Rust correlation instead of refusing to publish", async (context) => {
|
||||
const endpoint = expectedFacts("service").odinEndpoint!;
|
||||
const peer = await startOdinPeer(context, endpoint);
|
||||
const signer = signerFor(context, "service", -1);
|
||||
signer.reportHealth("active");
|
||||
const publisher = createIdunnRuntimePresencePublisher({ signer, endpoint });
|
||||
await publisher.publish("below minimum");
|
||||
const capabilities = (decode(peer.received[0]!.document.payload) as unknown[])[RUNTIME_PRESENCE_SLOT.capabilities] as unknown[][];
|
||||
assert.equal(capabilities[0]![3], expectedFacts("service").capabilities[0]!.capacity - 1);
|
||||
});
|
||||
|
||||
test("the Odin publisher takes only the endpoint Expected names", (context) => {
|
||||
assert.throws(
|
||||
() => createIdunnRuntimePresencePublisher({ signer: signerFor(context, "service"), endpoint: "rudp://127.0.0.1:1" }),
|
||||
/does not match Idunn Expected dependency authority/,
|
||||
);
|
||||
assert.throws(
|
||||
() => createIdunnRuntimePresencePublisher({ signer: signerFor(context, "web"), endpoint: expectedFacts("service").odinEndpoint! }),
|
||||
/does not match Idunn Expected dependency authority/,
|
||||
);
|
||||
});
|
||||
|
||||
test("the route answer and the Odin publish report the same state, because the signer owns it", async (context) => {
|
||||
const endpoint = expectedFacts("service").odinEndpoint!;
|
||||
const peer = await startOdinPeer(context, endpoint);
|
||||
const signer = signerFor(context, "service");
|
||||
const publisher = createIdunnRuntimePresencePublisher({ signer, endpoint });
|
||||
|
||||
await publisher.publish("first");
|
||||
assert.equal(presenceSlot(peer.received[0]!.document, RUNTIME_PRESENCE_SLOT.state), "warming");
|
||||
assert.equal(presenceSlot(signer.answerRouteObservation(CHALLENGE), RUNTIME_PRESENCE_SLOT.state), "warming");
|
||||
|
||||
signer.reportHealth("active");
|
||||
await publisher.publish("second");
|
||||
assert.equal(presenceSlot(peer.received[1]!.document, RUNTIME_PRESENCE_SLOT.state), "active");
|
||||
assert.equal(presenceSlot(signer.answerRouteObservation(CHALLENGE), RUNTIME_PRESENCE_SLOT.state), "active");
|
||||
// One sequence across both carriers.
|
||||
assert.deepEqual(
|
||||
[1, 2].map((index) => presenceSlot(peer.received[index - 1]!.document, RUNTIME_PRESENCE_SLOT.publisherSequence)),
|
||||
[1, 3],
|
||||
);
|
||||
});
|
||||
|
||||
// The lease-bound set: Rust issued lease.cc naming presence-warming.bin's digest, and presence-active.bin
|
||||
// and presence-degraded.bin carry that lease's digest.
|
||||
const STATEFUL = "service-stateful" as const;
|
||||
|
||||
function statefulSigner(context: TestContext, lease = "lease.cc") {
|
||||
return signerFor(context, STATEFUL, 0, lease);
|
||||
}
|
||||
|
||||
test("stateful: warming, active and degraded match the Rust-verified vectors byte for byte, active and degraded bound to Rust's lease", (context) => {
|
||||
freezeClock(context);
|
||||
const signer = statefulSigner(context);
|
||||
assert.deepEqual(Buffer.from(signer.answerRouteObservation(CHALLENGE).payload), fixtureFile(STATEFUL, "presence-warming.bin"));
|
||||
signer.reportHealth("active");
|
||||
const active = signer.answerRouteObservation(CHALLENGE);
|
||||
assert.deepEqual(Buffer.from(active.payload), fixtureFile(STATEFUL, "presence-active.bin"));
|
||||
assert.match(String(presenceSlot(active, RUNTIME_PRESENCE_SLOT.writeLeaseSha256)), /^sha256-[0-9a-f]{64}$/);
|
||||
|
||||
const degraded = statefulSigner(context);
|
||||
degraded.answerRouteObservation(CHALLENGE);
|
||||
degraded.reportHealth("degraded");
|
||||
assert.deepEqual(Buffer.from(degraded.answerRouteObservation(CHALLENGE).payload), fixtureFile(STATEFUL, "presence-degraded.bin"));
|
||||
});
|
||||
|
||||
test("a warming answered on the route becomes a lease target: Rust's lease naming it is accepted", (context) => {
|
||||
freezeClock(context);
|
||||
const signer = statefulSigner(context);
|
||||
assert.throws(() => signer.assertWriteLease(), /does not match the current Expected incarnation/, "no warming signed yet");
|
||||
signer.answerRouteObservation(CHALLENGE);
|
||||
assert.equal(signer.assertWriteLease(), presenceSlot({ payload: fixtureFile(STATEFUL, "presence-active.bin") }, RUNTIME_PRESENCE_SLOT.writeLeaseSha256));
|
||||
});
|
||||
|
||||
for (const [lease, reason] of [["lease-other-warming.cc", "names another warming digest"], ["lease-other-target.cc", "names another target"]] as const) {
|
||||
test(`a lease that ${reason} is refused, and the signer cannot sign active under it`, (context) => {
|
||||
freezeClock(context);
|
||||
const signer = statefulSigner(context, lease);
|
||||
signer.answerRouteObservation(CHALLENGE);
|
||||
assert.throws(() => signer.assertWriteLease(), /does not match the current Expected incarnation/);
|
||||
signer.reportHealth("active");
|
||||
assert.throws(() => signer.answerRouteObservation(CHALLENGE), /does not match the current Expected incarnation/);
|
||||
});
|
||||
}
|
||||
|
||||
test("one signer per loaded authority", (context) => {
|
||||
const authority = openAuthority(context, "web");
|
||||
const capabilities = expectedFacts("web").capabilities;
|
||||
createIdunnRuntimeSigner({ authority, capabilities });
|
||||
assert.throws(() => createIdunnRuntimeSigner({ authority, capabilities }), /already has a signer/);
|
||||
});
|
||||
|
||||
test("the loaded authority is frozen: the bind, contract, Expected, Activation and identities cannot change, and the signer signs the loaded endpoint", (context) => {
|
||||
freezeClock(context);
|
||||
const authority = openAuthority(context, "web");
|
||||
const loaded = expectedFacts("web");
|
||||
const open = authority as unknown as { [key: string]: any };
|
||||
const mutations: Array<[string, () => void]> = [
|
||||
["boundEndpoint", () => { open.boundEndpoint = "http://127.0.0.1:1"; }],
|
||||
["providerSignerIdentityId", () => { open.providerSignerIdentityId = "forged"; }],
|
||||
["activationSignerIdentityId", () => { open.activationSignerIdentityId = "forged"; }],
|
||||
["expected.healthContract", () => { open.expected.healthContract = "forged"; }],
|
||||
["expected.target", () => { open.expected.target = "forged"; }],
|
||||
["expected.canonicalSha256", () => { open.expected.canonicalSha256 = "forged"; }],
|
||||
["expected.route.candidateEndpoint", () => { open.expected.route.candidateEndpoint = "http://127.0.0.1:1"; }],
|
||||
["expected.capabilities[0].minimumCapacity", () => { open.expected.capabilities[0].minimumCapacity = 0; }],
|
||||
["expected.capabilities.push", () => { open.expected.capabilities.push({}); }],
|
||||
["activation.runtimeInstanceId", () => { open.activation.runtimeInstanceId = "forged"; }],
|
||||
["activation.canonicalSha256", () => { open.activation.canonicalSha256 = "forged"; }],
|
||||
];
|
||||
for (const [name, mutate] of mutations) assert.throws(mutate, TypeError, name);
|
||||
const signer = createIdunnRuntimeSigner({ authority, capabilities: loaded.capabilities });
|
||||
assert.equal(presenceSlot(signer.answerRouteObservation(CHALLENGE), RUNTIME_PRESENCE_SLOT.boundEndpoint), loaded.candidate);
|
||||
});
|
||||
|
||||
// A web app must be able to import the signer without pulling the Odin publisher and dgram.
|
||||
function loadUnderDgramStub(modulePath: string): string {
|
||||
const script = [
|
||||
'const Module = require("node:module");',
|
||||
"const load = Module._load;",
|
||||
'Module._load = function (request, ...rest) { if (request === "dgram" || request === "node:dgram") throw new Error("dgram was loaded"); return load.call(this, request, ...rest); };',
|
||||
"try { require(process.argv[1]); process.stdout.write(\"loaded\"); } catch (error) { process.stdout.write(\"failed: \" + error.message); }",
|
||||
].join("\n");
|
||||
const run = spawnSync(process.execPath, ["-e", script, modulePath], { encoding: "utf8" });
|
||||
assert.equal(run.status, 0, run.stderr);
|
||||
return run.stdout;
|
||||
}
|
||||
|
||||
test("the idunn-runtime subpath loads the signer and loader without loading dgram; the package root does load it", () => {
|
||||
const subpath = require.resolve("cultnet-ts/idunn-runtime");
|
||||
assert.equal(loadUnderDgramStub(subpath), "loaded");
|
||||
assert.equal(loadUnderDgramStub(require.resolve("cultnet-ts")), "failed: dgram was loaded");
|
||||
const exported = require(subpath) as Record<string, unknown>;
|
||||
assert.equal(typeof exported.createIdunnRuntimeSigner, "function");
|
||||
assert.equal(typeof exported.loadIdunnRuntimeAuthorityFromEnvironment, "function");
|
||||
assert.equal(exported.createIdunnRuntimePresencePublisher, undefined);
|
||||
assert.equal(exported.signIdunnRuntimePresence, undefined);
|
||||
assert.equal((require("cultnet-ts") as Record<string, unknown>).signIdunnRuntimePresence, undefined);
|
||||
});
|
||||
|
|
@ -21,6 +21,7 @@ import {
|
|||
validateRuntimePresence,
|
||||
type RuntimePresenceHealth,
|
||||
} from "../src/runtime-presence-health";
|
||||
import { truncateUtf8Bytes } from "../src/utf8-bound";
|
||||
|
||||
// Read from the source tree, not a copy beside the compiled test: the vectors
|
||||
// are generated output and must have exactly one home.
|
||||
|
|
@ -121,3 +122,44 @@ test("statements the contract forbids are refused before they are signed", () =>
|
|||
const partialLineage = { ...referencePresence(), stateContractSha256: null };
|
||||
assert.throws(() => validateRuntimePresence(partialLineage), /state lineage is partial/);
|
||||
});
|
||||
|
||||
const utf8Bytes = (text: string) => Buffer.byteLength(text, "utf8");
|
||||
const isValidUtf8 = (text: string) => !Buffer.from(text, "utf8").toString("utf8").includes("\uFFFD") && !text.includes("\uFFFD");
|
||||
|
||||
test("presence detail is truncated to 512 UTF-8 bytes, not UTF-16 units", () => {
|
||||
const truncated = truncateUtf8Bytes("é".repeat(300), 512);
|
||||
assert.ok(utf8Bytes(truncated) <= 512);
|
||||
assert.equal(truncated, "é".repeat(256));
|
||||
assert.ok(isValidUtf8(truncated));
|
||||
});
|
||||
|
||||
test("presence detail drops a 4-byte character straddling the boundary whole", () => {
|
||||
const truncated = truncateUtf8Bytes("a".repeat(510) + "😀", 512);
|
||||
assert.equal(truncated, "a".repeat(510));
|
||||
assert.ok(isValidUtf8(truncated));
|
||||
assert.equal(truncateUtf8Bytes("a".repeat(508) + "😀", 512), "a".repeat(508) + "😀");
|
||||
});
|
||||
|
||||
test("presence detail of exactly 512 ASCII bytes passes unchanged and 513 is cut", () => {
|
||||
const exact = "a".repeat(512);
|
||||
assert.equal(truncateUtf8Bytes(exact, 512), exact);
|
||||
assert.doesNotThrow(() => validateRuntimePresence({ ...referencePresence(), detail: exact }));
|
||||
assert.equal(truncateUtf8Bytes(exact + "a", 512), exact);
|
||||
assert.throws(() => validateRuntimePresence({ ...referencePresence(), detail: exact + "a" }), /too long/);
|
||||
});
|
||||
|
||||
test("validation refuses a detail that is short in UTF-16 units but over 512 UTF-8 bytes", () => {
|
||||
assert.throws(() => validateRuntimePresence({ ...referencePresence(), detail: "é".repeat(300) }), /too long/);
|
||||
});
|
||||
|
||||
test("a lone high surrogate at the end becomes U+FFFD and the result is valid UTF-8", () => {
|
||||
const truncated = truncateUtf8Bytes("abc\uD83D", 512);
|
||||
assert.equal(truncated, "abc\uFFFD");
|
||||
assert.equal(Buffer.from(truncated, "utf8").toString("utf8"), truncated);
|
||||
});
|
||||
|
||||
test("a lone low surrogate in the middle becomes U+FFFD and the result is valid UTF-8", () => {
|
||||
const truncated = truncateUtf8Bytes("ab\uDE00cd", 512);
|
||||
assert.equal(truncated, "ab\uFFFDcd");
|
||||
assert.equal(Buffer.from(truncated, "utf8").toString("utf8"), truncated);
|
||||
});
|
||||
|
|
|
|||
48
packages/cultnet-ts/test/signed-daemon-health.test.ts
Normal file
48
packages/cultnet-ts/test/signed-daemon-health.test.ts
Normal file
|
|
@ -0,0 +1,48 @@
|
|||
import test from "node:test";
|
||||
import assert from "node:assert/strict";
|
||||
import crypto from "node:crypto";
|
||||
import { decode } from "@msgpack/msgpack";
|
||||
|
||||
import {
|
||||
signedDaemonHealthPayload,
|
||||
unsignedDaemonHealthPayload,
|
||||
type SignedDaemonHealthPublisher,
|
||||
} from "../src/signed-daemon-health";
|
||||
|
||||
function publisher(): SignedDaemonHealthPublisher {
|
||||
return {
|
||||
daemonId: "heimdall",
|
||||
endpoint: { host: "127.0.0.1", port: 1 },
|
||||
healthContract: "contract",
|
||||
publisherIncarnationId: "incarnation",
|
||||
publisherSequence: 0,
|
||||
sourceRuntimeId: "runtime",
|
||||
contract: {
|
||||
connectionId: 1,
|
||||
signedSchemaId: "signed.schema",
|
||||
unsignedSchemaId: "unsigned.schema",
|
||||
} as SignedDaemonHealthPublisher["contract"],
|
||||
privateKey: crypto.generateKeyPairSync("ed25519").privateKey,
|
||||
signerIdentityId: "signer",
|
||||
};
|
||||
}
|
||||
|
||||
const observedAt = "2026-01-01T00:00:00.000Z";
|
||||
const detail = "é".repeat(300);
|
||||
|
||||
function assertBounded(text: unknown) {
|
||||
assert.equal(typeof text, "string");
|
||||
const bytes = Buffer.from(text as string, "utf8");
|
||||
assert.ok(bytes.length <= 512, `detail is ${bytes.length} bytes`);
|
||||
assert.equal(bytes.toString("utf8"), text);
|
||||
}
|
||||
|
||||
test("unsigned daemon health detail is bounded by UTF-8 bytes", () => {
|
||||
const fields = decode(unsignedDaemonHealthPayload(publisher(), { state: "ok", detail }, observedAt)) as unknown[];
|
||||
assertBounded(fields[2]);
|
||||
});
|
||||
|
||||
test("signed daemon health detail is bounded by UTF-8 bytes", () => {
|
||||
const { statement } = signedDaemonHealthPayload(publisher(), { state: "ok", detail }, observedAt);
|
||||
assertBounded(statement[5]);
|
||||
});
|
||||
|
|
@ -19,13 +19,19 @@ namespace GameCult.Caching.MessagePack
|
|||
|
||||
public static class CultCacheMessagePack
|
||||
{
|
||||
// The inspection model over this codec. Values serialize without the document guard but with their owning document's
|
||||
// options, resolvers included, so dictionary keys compare by the bytes the store writes; clones deserialize as
|
||||
// registered documents.
|
||||
public static CultInspectorModel CreateInspectorModel(CultDocumentRegistry registry) => new CultInspectorModel(
|
||||
registry,
|
||||
// The store's encoding as one port. Values serialize without the document guard but with their owning document's
|
||||
// options, resolvers included, so dictionary keys compare by the bytes the store writes; a document type
|
||||
// deserializes as a registered document, a member type as itself.
|
||||
public static CultCodec CreateCodec(CultDocumentRegistry registry) => new CultCodec(
|
||||
(value, type, document) => global::MessagePack.MessagePackSerializer.Serialize(type, value, CultDocumentMessagePackSerialization.OptionsFor(document.Assembly)),
|
||||
(type, bytes) => CultDocumentMessagePackSerialization.DeserializeUntyped(type, bytes, registry));
|
||||
(type, document, bytes) => type == document
|
||||
? CultDocumentMessagePackSerialization.DeserializeUntyped(type, bytes, registry)
|
||||
: global::MessagePack.MessagePackSerializer.Deserialize(type, bytes, CultDocumentMessagePackSerialization.OptionsFor(document.Assembly)),
|
||||
CultDocumentMessagePackSerialization.OverlaySlots);
|
||||
|
||||
// The inspection model over that codec.
|
||||
public static CultInspectorModel CreateInspectorModel(CultDocumentRegistry registry) =>
|
||||
new CultInspectorModel(registry, CreateCodec(registry));
|
||||
|
||||
// Opening hydrates. A consumer that wants a fresh store removes the records it does not keep, upserts, and
|
||||
// flushes; the atomic replace does the rest.
|
||||
|
|
@ -37,7 +43,8 @@ namespace GameCult.Caching.MessagePack
|
|||
}
|
||||
|
||||
options ??= new CultCacheOpenOptions();
|
||||
var cache = new CultCache(options.Registry)
|
||||
var registry = options.Registry ?? CultDocumentRegistry.Shared;
|
||||
var cache = new CultCache(registry, CreateCodec(registry))
|
||||
{
|
||||
FlushAttachedStoresOnDispose = options.FlushOnDispose
|
||||
};
|
||||
|
|
|
|||
|
|
@ -1,6 +1,7 @@
|
|||
using System;
|
||||
using System.Buffers;
|
||||
using System.Collections.Concurrent;
|
||||
using System.Collections.Generic;
|
||||
using System.Linq;
|
||||
using System.Reflection;
|
||||
using GameCult.Caching;
|
||||
|
|
@ -31,6 +32,7 @@ public sealed class CultDocumentResolver : IFormatterResolver
|
|||
public static class CultDocumentMessagePackSerialization
|
||||
{
|
||||
private const int PersistedRecordFieldCount = 4;
|
||||
private const int VariantRecordFieldCount = 5;
|
||||
private const int SchemaCatalogEntryFieldCount = 7;
|
||||
private const int SchemaCatalogMemberFieldCount = 8;
|
||||
private const int StoreSnapshotFieldCount = 3;
|
||||
|
|
@ -94,6 +96,49 @@ public static class CultDocumentMessagePackSerialization
|
|||
?? throw new InvalidOperationException($"MessagePack returned null for Cult document type {type.FullName}.");
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Replaces slots of a serialized document payload (a MessagePack array indexed by slot) with already-encoded member
|
||||
/// values, leaving every other slot byte for byte as it was. A slot past the end extends the array with nil.
|
||||
/// </summary>
|
||||
public static byte[] OverlaySlots(byte[] payload, IReadOnlyList<KeyValuePair<int, byte[]>> slots)
|
||||
{
|
||||
var reader = new MessagePackReader(payload);
|
||||
if (reader.NextMessagePackType != MessagePackType.Array)
|
||||
{
|
||||
throw new InvalidOperationException("A document payload is a MessagePack array; this one is not, so its slots cannot be overridden.");
|
||||
}
|
||||
|
||||
var count = reader.ReadArrayHeader();
|
||||
var elements = new List<byte[]>(count);
|
||||
for (var index = 0; index < count; index++)
|
||||
{
|
||||
var start = reader.Position;
|
||||
reader.Skip();
|
||||
elements.Add(reader.Sequence.Slice(start, reader.Position).ToArray());
|
||||
}
|
||||
|
||||
foreach (var (slot, value) in slots)
|
||||
{
|
||||
while (elements.Count <= slot)
|
||||
{
|
||||
elements.Add(new byte[] { 0xc0 });
|
||||
}
|
||||
|
||||
elements[slot] = value;
|
||||
}
|
||||
|
||||
var buffer = new ArrayBufferWriter<byte>();
|
||||
var writer = new MessagePackWriter(buffer);
|
||||
writer.WriteArrayHeader(elements.Count);
|
||||
foreach (var element in elements)
|
||||
{
|
||||
writer.WriteRaw(element);
|
||||
}
|
||||
|
||||
writer.Flush();
|
||||
return buffer.WrittenSpan.ToArray();
|
||||
}
|
||||
|
||||
public static byte[] SerializePersistedRecord(CultPersistedRecord record)
|
||||
{
|
||||
var buffer = new global::System.Buffers.ArrayBufferWriter<byte>();
|
||||
|
|
@ -139,7 +184,8 @@ public static class CultDocumentMessagePackSerialization
|
|||
|
||||
if (fieldCount > 0)
|
||||
{
|
||||
snapshot.FormatVersion = reader.ReadString() ?? "cultcache.store.v1";
|
||||
snapshot.FormatVersion = reader.ReadString()
|
||||
?? throw new NotSupportedException("Store snapshot declares no format version; this runtime reads " + CultPersistedStoreSnapshot.FormatV1 + " and " + CultPersistedStoreSnapshot.FormatV2 + ".");
|
||||
}
|
||||
|
||||
if (fieldCount > 1)
|
||||
|
|
@ -170,16 +216,113 @@ public static class CultDocumentMessagePackSerialization
|
|||
return snapshot;
|
||||
}
|
||||
|
||||
/// <summary>Refuses a single-file snapshot this runtime cannot read, naming the format or record it found.</summary>
|
||||
public static void RequireSingleFileFormat(CultPersistedStoreSnapshot snapshot)
|
||||
{
|
||||
var version = snapshot.FormatVersion;
|
||||
if (!string.Equals(version, CultPersistedStoreSnapshot.FormatV1, StringComparison.Ordinal) &&
|
||||
!string.Equals(version, CultPersistedStoreSnapshot.FormatV2, StringComparison.Ordinal))
|
||||
{
|
||||
throw new NotSupportedException(
|
||||
$"Store format {version} is not readable; this runtime reads {CultPersistedStoreSnapshot.FormatV1} and {CultPersistedStoreSnapshot.FormatV2}.");
|
||||
}
|
||||
|
||||
// Only a v2 store may hold a variant: a v1 header over a variant record is a store no reader could trust.
|
||||
if (string.Equals(version, CultPersistedStoreSnapshot.FormatV1, StringComparison.Ordinal))
|
||||
{
|
||||
var variant = snapshot.Records.FirstOrDefault(record => record.Variant != null);
|
||||
if (variant != null)
|
||||
{
|
||||
throw new NotSupportedException(
|
||||
$"Record '{variant.Key}' (schema '{variant.SchemaId}') is a variant but the store declares {version}; variants need {CultPersistedStoreSnapshot.FormatV2}.");
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
private static void WritePersistedRecord(ref MessagePackWriter writer, CultPersistedRecord record)
|
||||
{
|
||||
writer.WriteArrayHeader(PersistedRecordFieldCount);
|
||||
writer.WriteArrayHeader(record.Variant == null ? PersistedRecordFieldCount : VariantRecordFieldCount);
|
||||
writer.Write(record.Key);
|
||||
writer.Write(record.SchemaId);
|
||||
writer.Write(record.StoredAt);
|
||||
writer.Write(record.Payload);
|
||||
if (record.Variant != null)
|
||||
{
|
||||
// Slot 4: [baseKey, overrides[]]; an override is [op, path[], id, value], a path step [slot, elementId],
|
||||
// and the value is the member's own MessagePack encoding, inline.
|
||||
writer.WriteArrayHeader(2);
|
||||
writer.Write(record.Variant.BaseKey);
|
||||
writer.WriteArrayHeader(record.Variant.Overrides.Count);
|
||||
foreach (var entry in record.Variant.Overrides)
|
||||
{
|
||||
writer.WriteArrayHeader(4);
|
||||
writer.Write((int)entry.Op);
|
||||
writer.WriteArrayHeader(entry.Path.Count);
|
||||
foreach (var step in entry.Path)
|
||||
{
|
||||
writer.WriteArrayHeader(2);
|
||||
writer.Write(step.Slot);
|
||||
writer.Write(step.ElementId);
|
||||
}
|
||||
|
||||
writer.Write(entry.Id);
|
||||
writer.WriteRaw(entry.Value);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
private static CultPersistedRecord ReadPersistedRecord(ref MessagePackReader reader)
|
||||
private static CultVariantDelta ReadVariant(ref MessagePackReader reader, string key, string schemaId)
|
||||
{
|
||||
var slots = reader.ReadArrayHeader();
|
||||
if (slots != 2)
|
||||
{
|
||||
throw new NotSupportedException(
|
||||
$"Record '{key}' (schema '{schemaId}') has a variant slot of {slots} entries; this runtime reads 2 (base key, overrides).");
|
||||
}
|
||||
|
||||
var baseKey = reader.ReadString() ?? string.Empty;
|
||||
var count = reader.ReadArrayHeader();
|
||||
var overrides = new CultVariantOverride[count];
|
||||
for (var index = 0; index < count; index++)
|
||||
{
|
||||
var fields = reader.ReadArrayHeader();
|
||||
if (fields != 4)
|
||||
{
|
||||
throw new NotSupportedException(
|
||||
$"Record '{key}' (schema '{schemaId}') has an override of {fields} entries; this runtime reads 4 (op, path, id, value).");
|
||||
}
|
||||
|
||||
var op = reader.ReadInt32();
|
||||
if (op is < 0 or > 2)
|
||||
{
|
||||
throw new NotSupportedException($"Record '{key}' (schema '{schemaId}') has an override with unknown op {op}.");
|
||||
}
|
||||
|
||||
var stepCount = reader.ReadArrayHeader();
|
||||
var path = new CultPathStep[stepCount];
|
||||
for (var step = 0; step < stepCount; step++)
|
||||
{
|
||||
var stepFields = reader.ReadArrayHeader();
|
||||
if (stepFields != 2)
|
||||
{
|
||||
throw new NotSupportedException(
|
||||
$"Record '{key}' (schema '{schemaId}') has a path step of {stepFields} entries; this runtime reads 2 (slot, elementId).");
|
||||
}
|
||||
|
||||
path[step] = new CultPathStep(reader.ReadInt32(), reader.ReadString() ?? string.Empty);
|
||||
}
|
||||
|
||||
var id = reader.ReadString() ?? string.Empty;
|
||||
var start = reader.Position;
|
||||
reader.Skip();
|
||||
var value = reader.Sequence.Slice(start, reader.Position).ToArray();
|
||||
overrides[index] = new CultVariantOverride((CultOverrideOp)op, path, id, value);
|
||||
}
|
||||
|
||||
return new CultVariantDelta(baseKey, overrides);
|
||||
}
|
||||
|
||||
public static CultPersistedRecord ReadPersistedRecord(ref MessagePackReader reader)
|
||||
{
|
||||
var fieldCount = reader.ReadArrayHeader();
|
||||
var record = new CultPersistedRecord();
|
||||
|
|
@ -204,9 +347,21 @@ public static class CultDocumentMessagePackSerialization
|
|||
record.Payload = reader.ReadBytes()?.ToArray() ?? Array.Empty<byte>();
|
||||
}
|
||||
|
||||
for (var index = PersistedRecordFieldCount; index < fieldCount; index++)
|
||||
if (fieldCount > VariantRecordFieldCount)
|
||||
{
|
||||
reader.Skip();
|
||||
throw new NotSupportedException(
|
||||
$"Record '{record.Key}' (schema '{record.SchemaId}') has {fieldCount} slots; this runtime reads {PersistedRecordFieldCount} " +
|
||||
$"(or {VariantRecordFieldCount} for a variant).");
|
||||
}
|
||||
|
||||
if (fieldCount == VariantRecordFieldCount)
|
||||
{
|
||||
record.Variant = ReadVariant(ref reader, record.Key, record.SchemaId);
|
||||
if (record.Payload.Length != 0)
|
||||
{
|
||||
throw new NotSupportedException(
|
||||
$"Record '{record.Key}' (schema '{record.SchemaId}') is a variant and must carry an empty payload.");
|
||||
}
|
||||
}
|
||||
|
||||
return record;
|
||||
|
|
@ -371,7 +526,9 @@ public class SingleFileMessagePackBackingStore : SingleFileBackingStore
|
|||
|
||||
protected override CultPersistedStoreSnapshot DeserializeSnapshot(byte[] data)
|
||||
{
|
||||
return CultDocumentMessagePackSerialization.DeserializeSnapshot(data);
|
||||
var snapshot = CultDocumentMessagePackSerialization.DeserializeSnapshot(data);
|
||||
CultDocumentMessagePackSerialization.RequireSingleFileFormat(snapshot);
|
||||
return snapshot;
|
||||
}
|
||||
|
||||
protected override byte[] SerializePayload(object document)
|
||||
|
|
|
|||
|
|
@ -135,9 +135,18 @@ public sealed class DirectoryMessagePackBackingStore : CacheBackingStore
|
|||
Trace("publish");
|
||||
}
|
||||
|
||||
// Variants wait for the directory store's own cut; until then it refuses one rather than persist a resolved view as a plain page.
|
||||
private static void RefuseVariant(CultStoredDocument entry)
|
||||
{
|
||||
if (entry.Variant != null)
|
||||
throw new NotSupportedException(
|
||||
$"Record '{entry.Key.Value}' is a variant of '{entry.Variant.BaseKey}'; the directory store does not hold document variants yet.");
|
||||
}
|
||||
|
||||
public override void Push(CultStoredDocument entry)
|
||||
{
|
||||
ThrowIfReadOnly();
|
||||
RefuseVariant(entry);
|
||||
Held(() =>
|
||||
{
|
||||
Entries[entry.Key.Value] = entry;
|
||||
|
|
@ -162,6 +171,8 @@ public sealed class DirectoryMessagePackBackingStore : CacheBackingStore
|
|||
public override CultCommitOutcome CommitBatch(CultCommitRequest request, bool wait)
|
||||
{
|
||||
ThrowIfReadOnly();
|
||||
foreach (var entry in request.Upserts)
|
||||
RefuseVariant(entry);
|
||||
return Held(() =>
|
||||
{
|
||||
Directory.CreateDirectory(_manifestFile.DirectoryName!);
|
||||
|
|
@ -328,11 +339,11 @@ public sealed class DirectoryMessagePackBackingStore : CacheBackingStore
|
|||
var started = tracePages ? Stopwatch.GetTimestamp() : 0L;
|
||||
var metadata = records[index];
|
||||
var record = ReadPersistedRecordPage(metadata, out var pagePayload);
|
||||
recordReports[index] = Registry.ResolvePersistedSchemaReport(record.SchemaId, catalogEntries);
|
||||
storedRecords[index] = ToStoredDocument(
|
||||
record,
|
||||
catalogEntries,
|
||||
(type, payload) => CultDocumentMessagePackSerialization.DeserializeUntyped(type, payload, Registry));
|
||||
(type, payload) => CultDocumentMessagePackSerialization.DeserializeUntyped(type, payload, Registry),
|
||||
out recordReports[index]);
|
||||
if (tracePages)
|
||||
{
|
||||
pageBytes[index] = pagePayload.LongLength;
|
||||
|
|
@ -491,6 +502,10 @@ public sealed class DirectoryMessagePackBackingStore : CacheBackingStore
|
|||
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}'.");
|
||||
// The shared decoder reads a variant page; this store does not hold variants, so a load refuses it as a write does.
|
||||
if (record.Variant != null)
|
||||
throw new NotSupportedException(
|
||||
$"Record '{record.Key}' is a variant of '{record.Variant.BaseKey}'; the directory store does not hold document variants yet.");
|
||||
return record;
|
||||
}
|
||||
|
||||
|
|
|
|||
|
|
@ -212,6 +212,41 @@ Example:
|
|||
The payload is the domain object only. It does not repeat the key, schema id,
|
||||
or stored timestamp.
|
||||
|
||||
Under `cultcache.store.v1` a record has exactly these four slots. A reader refuses any
|
||||
`cultcache.store.*` header it does not know and any record with more slots than its
|
||||
header allows, naming the version or the record's key and schema id. It never skips a
|
||||
slot it does not understand.
|
||||
|
||||
## Variant Records
|
||||
|
||||
A variant record is a record whose document is a base record's document with some
|
||||
members replaced. It stores the difference, never the resolved document. It carries a
|
||||
fifth slot:
|
||||
|
||||
```
|
||||
[key, schemaId, storedAt, payload, [baseKey, overrides[]]]
|
||||
```
|
||||
|
||||
- `payload` is empty. An older reader that ignores the fifth slot reads an empty
|
||||
payload as a corrupt document and refuses, which is why the delta lives outside it.
|
||||
- `schemaId` is the type's schema id, the same as the base's. A variant has its base's
|
||||
concrete type, and lives in the same store (one home store per type).
|
||||
- An override is `[op, path[], id, value]`. `op` is `0` Set, `1` Insert or `2` Remove.
|
||||
A path step is `[slot, elementId]`: `slot` is the member's MessagePack `[Key]` and
|
||||
`elementId` is `""` unless the step enters an object-list element. `value` is the
|
||||
member's own MessagePack encoding, inline. A top-level Set has one step and `id` `""`;
|
||||
a reader that resolves only that shape refuses the others, naming the variant.
|
||||
- A store holding at least one variant declares `cultcache.store.v2`; a store holding
|
||||
none declares `cultcache.store.v1` and is byte-identical to what a runtime without
|
||||
variants writes. A `v1` header over a variant record is refused.
|
||||
- A variant's resolved document is derived in memory when the cache admits the record
|
||||
or any record on its base chain, and is never written back. A plain write at a
|
||||
variant's key is refused; `Flatten` replaces a variant with a plain record holding its
|
||||
resolved document.
|
||||
- The C# runtime resolves variants. Every other runtime refuses a `v2` store by name.
|
||||
CultMesh single-file reads, the directory store and CultNet refuse a variant record by
|
||||
name until each has its own cut.
|
||||
|
||||
## Canonical Semantic Schema Hash
|
||||
|
||||
`schemaId` should be derived from a canonical semantic schema hash.
|
||||
|
|
|
|||
|
|
@ -105,3 +105,20 @@ lie about the payload:
|
|||
- no compatible local schema candidate
|
||||
|
||||
This is not negotiable. Better a loud refusal than quiet bit-rot.
|
||||
|
||||
## Variant overrides
|
||||
|
||||
A variant's override follows the same outcome as the same member on a plain record; there
|
||||
is no separate rule for variants, and no separate report.
|
||||
|
||||
- An override naming a slot the type no longer has is ignored, exactly as a plain record
|
||||
ignores a dropped member. The drift is reported once, by the store's schema resolution
|
||||
(`LastSchemaMigrationReports`), for the variant's record as for any other record of the
|
||||
schema. The variant inherits the base value.
|
||||
- An override holding a value that no longer decodes into the member's type refuses the
|
||||
load, exactly as a plain record holding such a value does; the refusal names the variant
|
||||
and the member.
|
||||
|
||||
Drift is for type changes after the fact. A write is validated: an override for a slot the
|
||||
type does not have, a value that does not decode as the member, or two overrides of one
|
||||
slot is refused when written.
|
||||
|
|
|
|||
|
|
@ -55,11 +55,17 @@ namespace GameCult.Caching
|
|||
public string SchemaId { get; set; } = string.Empty;
|
||||
public string StoredAt { get; set; } = string.Empty;
|
||||
public byte[] Payload { get; set; } = Array.Empty<byte>();
|
||||
|
||||
// Non-null for a variant record (slot 4): its base and overrides. Its payload is empty.
|
||||
public CultVariantDelta? Variant { get; set; }
|
||||
}
|
||||
|
||||
public sealed class CultPersistedStoreSnapshot
|
||||
{
|
||||
public string FormatVersion { get; set; } = "cultcache.store.v1";
|
||||
public const string FormatV1 = "cultcache.store.v1";
|
||||
public const string FormatV2 = "cultcache.store.v2";
|
||||
|
||||
public string FormatVersion { get; set; } = FormatV1;
|
||||
public CultSchemaCatalogEntry[] SchemaCatalog { get; set; } = Array.Empty<CultSchemaCatalogEntry>();
|
||||
public CultPersistedRecord[] Records { get; set; } = Array.Empty<CultPersistedRecord>();
|
||||
}
|
||||
|
|
@ -336,13 +342,43 @@ namespace GameCult.Caching
|
|||
Key = key;
|
||||
StoredAt = storedAt;
|
||||
Descriptor = descriptor;
|
||||
Document = document;
|
||||
_document = document;
|
||||
}
|
||||
|
||||
// A variant: the delta is what is stored; the cache resolves it against its base in the hold that admits it.
|
||||
internal CultStoredDocument(
|
||||
CultRecordKey key,
|
||||
string storedAt,
|
||||
CultDocumentDescriptor descriptor,
|
||||
CultVariantDelta variant,
|
||||
object? resolved)
|
||||
{
|
||||
Key = key;
|
||||
StoredAt = storedAt;
|
||||
Descriptor = descriptor;
|
||||
Variant = variant;
|
||||
_document = resolved;
|
||||
}
|
||||
|
||||
private readonly object? _document;
|
||||
|
||||
public CultRecordKey Key { get; }
|
||||
public string StoredAt { get; }
|
||||
public CultDocumentDescriptor Descriptor { get; }
|
||||
public object Document { get; }
|
||||
|
||||
// The complete document. For a variant, the resolved view: derived, never written back.
|
||||
public object Document => _document ??
|
||||
throw new InvalidOperationException($"Variant {Key.Value} has not been resolved; only the cache resolves a variant.");
|
||||
|
||||
// The base and overrides a variant record stores; null for a plain record.
|
||||
public CultVariantDelta? Variant { get; }
|
||||
|
||||
// A plain record staged by Flatten: the one way a plain record may replace a variant at its key.
|
||||
internal bool Flattens { get; set; }
|
||||
|
||||
internal bool IsResolved => _document != null;
|
||||
|
||||
internal CultStoredDocument Resolved(object document) => new(Key, StoredAt, Descriptor, Variant!, document);
|
||||
}
|
||||
|
||||
public sealed class CultDocumentRegistry
|
||||
|
|
@ -1662,11 +1698,29 @@ namespace GameCult.Caching
|
|||
private static string Identity(string key, string schemaId, string storedAt) => $"{key}\n{schemaId}\n{storedAt}";
|
||||
}
|
||||
|
||||
// One staged write: a plain record (Stored), a variant (Variant), a flatten, or, with none of those, a removal.
|
||||
internal sealed class StagedOperation
|
||||
{
|
||||
public StagedOperation(CultRecordKey key, CultStoredDocument? stored, CultVariantDelta? variant, bool flatten)
|
||||
{
|
||||
Key = key;
|
||||
Stored = stored;
|
||||
Variant = variant;
|
||||
Flatten = flatten;
|
||||
}
|
||||
|
||||
public CultRecordKey Key { get; }
|
||||
public CultStoredDocument? Stored { get; }
|
||||
public CultVariantDelta? Variant { get; }
|
||||
public bool Flatten { get; }
|
||||
public bool IsRemoval => Stored == null && Variant == null && !Flatten;
|
||||
}
|
||||
|
||||
// An explicit value: nothing staged here is visible to anyone until Commit returns.
|
||||
public sealed class CultCacheBatch
|
||||
{
|
||||
private readonly CultCache _cache;
|
||||
internal readonly Dictionary<string, (CultRecordKey Key, CultStoredDocument? Stored)> Operations = new(StringComparer.Ordinal);
|
||||
internal readonly Dictionary<string, StagedOperation> Operations = new(StringComparer.Ordinal);
|
||||
internal readonly List<(CultRecordKey Key, string? SchemaId, string? StoredAt)> Expected = new();
|
||||
internal bool ExpectsUnchanged;
|
||||
internal bool Sealed;
|
||||
|
|
@ -1691,7 +1745,24 @@ namespace GameCult.Caching
|
|||
public void Remove(CultRecordKey key)
|
||||
{
|
||||
ThrowIfSealed();
|
||||
Operations[key.Value] = (key, null);
|
||||
Operations[key.Value] = new StagedOperation(key, null, null, false);
|
||||
}
|
||||
|
||||
// Stages a variant record: its base and a sparse set of overrides, resolved by the cache when the batch commits.
|
||||
// A variant changes only through here; rebasing is this call with another base.
|
||||
public CultRecordKey UpsertVariant(CultRecordKey key, CultRecordKey baseKey, IEnumerable<CultVariantOverride>? overrides = null)
|
||||
{
|
||||
ThrowIfSealed();
|
||||
Operations[key.Value] = new StagedOperation(
|
||||
key, null, new CultVariantDelta(baseKey.Value, (overrides ?? Array.Empty<CultVariantOverride>()).ToArray()), false);
|
||||
return key;
|
||||
}
|
||||
|
||||
// Replaces a variant with a plain record holding its resolved document: the explicit, separate operation (Q1a).
|
||||
public void Flatten(CultRecordKey key)
|
||||
{
|
||||
ThrowIfSealed();
|
||||
Operations[key.Value] = new StagedOperation(key, null, null, true);
|
||||
}
|
||||
|
||||
public void Expect(CultRecordKey key, object? current)
|
||||
|
|
@ -1711,7 +1782,7 @@ namespace GameCult.Caching
|
|||
{
|
||||
ThrowIfSealed();
|
||||
var stored = _cache.CreateStoredDocument(document, key);
|
||||
Operations[stored.Key.Value] = (stored.Key, stored);
|
||||
Operations[stored.Key.Value] = new StagedOperation(stored.Key, stored, null, false);
|
||||
return stored.Key;
|
||||
}
|
||||
|
||||
|
|
@ -1728,8 +1799,12 @@ namespace GameCult.Caching
|
|||
private readonly List<(CacheBackingStore Store, Type[] Homes)> _stores = new();
|
||||
private readonly Dictionary<string, CultStoredDocument> _entries = new(StringComparer.Ordinal);
|
||||
private readonly Dictionary<Type, Dictionary<string, string>> _names = new();
|
||||
private readonly Dictionary<(Type Type, string Alias), Dictionary<string, string>> _indexes = new();
|
||||
// Every key holding a value (unordered): the index is truthful about duplicates, so removing one holder never hides another.
|
||||
private readonly Dictionary<(Type Type, string Alias), Dictionary<string, List<string>>> _indexes = new();
|
||||
private readonly Dictionary<Type, string> _globals = new();
|
||||
private readonly CultCodec? _codec;
|
||||
// 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();
|
||||
private readonly object _gate = new();
|
||||
|
|
@ -1738,13 +1813,34 @@ namespace GameCult.Caching
|
|||
[ThreadStatic] private static List<(Change Change, bool Loaded)>? _held;
|
||||
private bool _dirtyInMemory;
|
||||
|
||||
public CultCache(CultDocumentRegistry? registry = null)
|
||||
// The codec is the store's encoding (CultCacheMessagePack.Create supplies it). A cache without one holds no variants:
|
||||
// resolving a variant needs to clone documents and decode override values.
|
||||
public CultCache(CultDocumentRegistry? registry = null, CultCodec? codec = null)
|
||||
{
|
||||
_registry = registry ?? CultDocumentRegistry.Shared;
|
||||
_codec = codec;
|
||||
}
|
||||
|
||||
public CultDocumentRegistry Registry => _registry;
|
||||
|
||||
// Read under the gate, by a store judging a merge.
|
||||
internal bool HoldsVariants => _variantKeys.Count > 0;
|
||||
|
||||
public CultCodec? Codec => _codec;
|
||||
|
||||
// The whole override of one member, encoded with this cache's codec, ready for UpsertVariant.
|
||||
public CultVariantOverride Override(Type documentType, string member, object? value)
|
||||
{
|
||||
if (_codec == null) throw new InvalidOperationException("This cache has no codec; create it with CultCacheMessagePack.Create.");
|
||||
var found = _registry.GetRequired(documentType).RichMembers.FirstOrDefault(entry => entry.Member.Name == member)
|
||||
?? throw new ArgumentException($"{documentType.Name} has no persisted member '{member}'.", nameof(member));
|
||||
return CultVariantOverride.Set(
|
||||
found.Slot,
|
||||
_codec.Serialize(value!, found.MemberType, documentType));
|
||||
}
|
||||
|
||||
public CultVariantOverride Override<T>(string member, object? value) where T : class => Override(typeof(T), member, value);
|
||||
|
||||
public bool IsDirty
|
||||
{
|
||||
get
|
||||
|
|
@ -1841,7 +1937,8 @@ namespace GameCult.Caching
|
|||
|
||||
store.AttachRegistry(_registry);
|
||||
store.Cache = this;
|
||||
store.Loaded = (loaded, dropped) => Admit(loaded, dropped, store, _ => CultCommitOutcome.Committed);
|
||||
store.Loaded = (loaded, dropped) => Admit(loaded, dropped, store, (_, _) => CultCommitOutcome.Committed);
|
||||
store.Judging = (arriving, departing) => { Resolve(arriving, departing, store); };
|
||||
_stores.Add(candidate);
|
||||
try
|
||||
{
|
||||
|
|
@ -1851,6 +1948,7 @@ namespace GameCult.Caching
|
|||
{
|
||||
_stores.Remove(candidate);
|
||||
store.Loaded = null;
|
||||
store.Judging = null;
|
||||
store.Cache = null;
|
||||
throw;
|
||||
}
|
||||
|
|
@ -1915,11 +2013,39 @@ namespace GameCult.Caching
|
|||
return Task.FromResult(Write(document, key));
|
||||
}
|
||||
|
||||
// A single-call variant write; a batch stages the same thing with CultCacheBatch.UpsertVariant.
|
||||
public Task<CultRecordKey> UpsertVariantAsync(CultRecordKey key, CultRecordKey baseKey, IEnumerable<CultVariantOverride>? overrides = null)
|
||||
{
|
||||
var delta = new CultVariantDelta(baseKey.Value, (overrides ?? Array.Empty<CultVariantOverride>()).ToArray());
|
||||
return Task.FromResult(Held(() =>
|
||||
{
|
||||
var stored = StampVariant(key, DescriptorOfBase(key, delta.BaseKey, null), delta);
|
||||
Admit(new[] { stored }, Array.Empty<CultStoredDocument>(), null, (home, docs) =>
|
||||
{
|
||||
home?.Push(docs[0]);
|
||||
return CultCommitOutcome.Committed;
|
||||
});
|
||||
return key;
|
||||
}));
|
||||
}
|
||||
|
||||
// Replaces a variant with a plain record holding its resolved document (Q1a's explicit operation).
|
||||
public Task<CultRecordKey> FlattenAsync(CultRecordKey key) => Task.FromResult(Held(() =>
|
||||
{
|
||||
var stored = StampFlatten(key);
|
||||
Admit(new[] { stored }, Array.Empty<CultStoredDocument>(), null, (home, docs) =>
|
||||
{
|
||||
home?.Push(docs[0]);
|
||||
return CultCommitOutcome.Committed;
|
||||
});
|
||||
return key;
|
||||
}));
|
||||
|
||||
public bool Remove(CultRecordKey key) => Held(() =>
|
||||
{
|
||||
if (!_entries.TryGetValue(key.Value, out var existing))
|
||||
return false;
|
||||
Admit(Array.Empty<CultStoredDocument>(), new[] { existing }, null, home =>
|
||||
Admit(Array.Empty<CultStoredDocument>(), new[] { existing }, null, (home, _) =>
|
||||
{
|
||||
home?.Delete(existing);
|
||||
return CultCommitOutcome.Committed;
|
||||
|
|
@ -1950,6 +2076,13 @@ namespace GameCult.Caching
|
|||
return _handles.TryGetValue(document, out var box) ? new CultRecordHandle<T>(box.Key) : null;
|
||||
}
|
||||
|
||||
// The stored form of a record: for a variant, the delta beside the resolved document.
|
||||
public CultStoredDocument? GetStored(CultRecordKey key)
|
||||
{
|
||||
lock (_gate)
|
||||
return _entries.TryGetValue(key.Value, out var stored) ? stored : null;
|
||||
}
|
||||
|
||||
public object? Get(CultRecordKey key)
|
||||
{
|
||||
lock (_gate)
|
||||
|
|
@ -1994,11 +2127,16 @@ namespace GameCult.Caching
|
|||
.SelectMany(pair => pair.Value.TryGetValue(name, out var key) ? new[] { key } : Array.Empty<string>()));
|
||||
}
|
||||
|
||||
// A value held by one record finds it. Records of one type sharing a value (plain duplicates) find the holder with the
|
||||
// smallest key (ordinal), whatever order they were written or loaded in: the choice is a function of the held set, so
|
||||
// it is the same live, after a flush and after a reopen, and removing that holder finds the next.
|
||||
public T? GetByIndex<T>(string alias, string value) where T : class
|
||||
{
|
||||
return Single<T>($"index {alias}='{value}'", () => _indexes
|
||||
.Where(pair => pair.Key.Alias == alias && typeof(T).IsAssignableFrom(pair.Key.Type))
|
||||
.SelectMany(pair => pair.Value.TryGetValue(value, out var key) ? new[] { key } : Array.Empty<string>()));
|
||||
.SelectMany(pair => pair.Value.TryGetValue(value, out var keys)
|
||||
? new[] { keys.Aggregate((best, next) => string.CompareOrdinal(next, best) < 0 ? next : best) }
|
||||
: Array.Empty<string>()));
|
||||
}
|
||||
|
||||
public void Dispose()
|
||||
|
|
@ -2039,7 +2177,53 @@ namespace GameCult.Caching
|
|||
|
||||
// Call under the gate that admits the result, so no load can land a later storedAt in between.
|
||||
private CultStoredDocument Stamp(CultRecordKey key, CultDocumentDescriptor descriptor, object document) =>
|
||||
new(key, MintStoredAt(_entries.TryGetValue(key.Value, out var previous) ? previous.StoredAt : null), descriptor, document);
|
||||
new(key, MintStoredAt(PreviousStoredAt(key)), descriptor, document);
|
||||
|
||||
// An unresolved variant: the admitting hold resolves it against its base before anything lands.
|
||||
private CultStoredDocument StampVariant(CultRecordKey key, CultDocumentDescriptor descriptor, CultVariantDelta delta) =>
|
||||
new(key, MintStoredAt(PreviousStoredAt(key)), descriptor, delta, null);
|
||||
|
||||
// The plain record a Flatten stages: the variant's resolved document, under the variant's own key and schema.
|
||||
private CultStoredDocument StampFlatten(CultRecordKey key)
|
||||
{
|
||||
if (!_entries.TryGetValue(key.Value, out var existing) || existing.Variant == null)
|
||||
throw new InvalidOperationException($"Flatten({key.Value}): the record is not a variant.");
|
||||
return new CultStoredDocument(key, MintStoredAt(existing.StoredAt), existing.Descriptor, existing.Document) { Flattens = true };
|
||||
}
|
||||
|
||||
private string? PreviousStoredAt(CultRecordKey key) => _entries.TryGetValue(key.Value, out var previous) ? previous.StoredAt : null;
|
||||
|
||||
// The concrete type a variant takes from its base, walking bases through what the batch stages and then the cache.
|
||||
// Refuses a cycle or a base that is not there, naming the keys, exactly as the admitting hold would.
|
||||
private CultDocumentDescriptor DescriptorOfBase(CultRecordKey variant, string baseKey, CultCacheBatch? batch)
|
||||
{
|
||||
var seen = new List<string> { variant.Value };
|
||||
var next = baseKey;
|
||||
while (true)
|
||||
{
|
||||
if (seen.Contains(next))
|
||||
throw CycleRefusal(seen.Append(next));
|
||||
var staged = batch != null && batch.Operations.TryGetValue(next, out var op) ? op : null;
|
||||
if (staged != null)
|
||||
{
|
||||
if (staged.Stored != null)
|
||||
return staged.Stored.Descriptor;
|
||||
if (staged.Variant != null)
|
||||
{
|
||||
seen.Add(next);
|
||||
next = staged.Variant.BaseKey;
|
||||
continue;
|
||||
}
|
||||
|
||||
if (!staged.Flatten)
|
||||
throw MissingBaseRefusal(variant.Value, baseKey, removed: true);
|
||||
}
|
||||
|
||||
if (!_entries.TryGetValue(next, out var existing))
|
||||
throw MissingBaseRefusal(variant.Value, baseKey, removed: false);
|
||||
return existing.Descriptor;
|
||||
}
|
||||
}
|
||||
|
||||
internal CultStoredDocument? Observe(CultRecordKey key, object? current)
|
||||
{
|
||||
|
|
@ -2068,9 +2252,9 @@ namespace GameCult.Caching
|
|||
private CultRecordKey Write(object document, CultRecordKey? key) => Held(() =>
|
||||
{
|
||||
var stored = CreateStoredDocument(document, key);
|
||||
Admit(new[] { stored }, Array.Empty<CultStoredDocument>(), null, home =>
|
||||
Admit(new[] { stored }, Array.Empty<CultStoredDocument>(), null, (home, docs) =>
|
||||
{
|
||||
home?.Push(stored);
|
||||
home?.Push(docs[0]);
|
||||
return CultCommitOutcome.Committed;
|
||||
});
|
||||
return stored.Key;
|
||||
|
|
@ -2094,16 +2278,19 @@ namespace GameCult.Caching
|
|||
{
|
||||
// Staging stamped outside this gate; a pull since then may hold a later storedAt, so stamp again.
|
||||
var upserts = batch.Operations.Values
|
||||
.Where(op => op.Stored != null)
|
||||
.Select(op => Stamp(op.Key, op.Stored!.Descriptor, op.Stored.Document))
|
||||
.Where(op => !op.IsRemoval)
|
||||
.Select(op => op.Stored != null ? Stamp(op.Key, op.Stored.Descriptor, op.Stored.Document)
|
||||
: op.Variant != null ? StampVariant(op.Key, DescriptorOfBase(op.Key, op.Variant.BaseKey, batch), op.Variant)
|
||||
: StampFlatten(op.Key))
|
||||
.ToArray();
|
||||
var deletes = batch.Operations.Values
|
||||
.Where(op => op.Stored == null && _entries.ContainsKey(op.Key.Value))
|
||||
.Where(op => op.IsRemoval && _entries.ContainsKey(op.Key.Value))
|
||||
.Select(op => _entries[op.Key.Value])
|
||||
.ToArray();
|
||||
var request = new CultCommitRequest(upserts, deletes, batch.Expected.ToArray(), batch.ExpectsUnchanged);
|
||||
return Admit(upserts, deletes, null, home =>
|
||||
return Admit(upserts, deletes, null, (home, resolved) =>
|
||||
{
|
||||
// What the store holds is what the hold resolved: a variant's delta beside its resolved view.
|
||||
var request = new CultCommitRequest(resolved, deletes, batch.Expected.ToArray(), batch.ExpectsUnchanged);
|
||||
if (home != null)
|
||||
{
|
||||
if (request.HasConditions && home.IsDirty)
|
||||
|
|
@ -2127,14 +2314,18 @@ namespace GameCult.Caching
|
|||
IReadOnlyList<CultStoredDocument> admitted,
|
||||
IReadOnlyList<CultStoredDocument> evicted,
|
||||
CacheBackingStore? source,
|
||||
Func<CacheBackingStore?, CultCommitOutcome> land) => Held(() =>
|
||||
Func<CacheBackingStore?, IReadOnlyList<CultStoredDocument>, CultCommitOutcome> land) => Held(() =>
|
||||
{
|
||||
if (_held == null)
|
||||
throw new InvalidOperationException("An admission reached the cache under a plain lock on its gate; every admission runs in a hold.");
|
||||
var outcome = land(Validate(admitted, evicted, source));
|
||||
var home = Validate(admitted, evicted, source);
|
||||
// The one resolution: a variant admitted, a base admitted or evicted, all resolved here against the post-batch
|
||||
// set, before land and before memory. land receives the admitted records with variants resolved.
|
||||
var plan = Resolve(admitted, evicted, source);
|
||||
var outcome = land(home, plan.Admitted);
|
||||
if (outcome != CultCommitOutcome.Committed)
|
||||
return outcome;
|
||||
foreach (var change in Apply(admitted, evicted, source))
|
||||
foreach (var change in Apply(plan, evicted, source))
|
||||
_held.Add((change, source != null));
|
||||
return CultCommitOutcome.Committed;
|
||||
});
|
||||
|
|
@ -2262,12 +2453,264 @@ namespace GameCult.Caching
|
|||
}
|
||||
}
|
||||
|
||||
private List<Change> Apply(
|
||||
private sealed class VariantPlan
|
||||
{
|
||||
public VariantPlan(IReadOnlyList<CultStoredDocument> admitted)
|
||||
{
|
||||
Admitted = admitted;
|
||||
}
|
||||
|
||||
// The admitted records, variants resolved.
|
||||
public IReadOnlyList<CultStoredDocument> Admitted { get; }
|
||||
|
||||
// Variants this admission did not write whose base chain it changed: re-resolved, same delta, same storedAt.
|
||||
public List<CultStoredDocument> Dependents { get; } = new();
|
||||
}
|
||||
|
||||
// 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(
|
||||
IReadOnlyList<CultStoredDocument> admitted,
|
||||
IReadOnlyList<CultStoredDocument> evicted,
|
||||
CacheBackingStore? source)
|
||||
{
|
||||
var changes = new List<Change>(admitted.Count + evicted.Count);
|
||||
if (_variantKeys.Count == 0 && admitted.All(stored => stored.Variant == null))
|
||||
return new VariantPlan(admitted);
|
||||
|
||||
var incoming = admitted.ToDictionary(stored => stored.Key.Value, StringComparer.Ordinal);
|
||||
var gone = evicted.Select(stored => stored.Key.Value).ToHashSet(StringComparer.Ordinal);
|
||||
CultStoredDocument? Lookup(string key) =>
|
||||
incoming.TryGetValue(key, out var found) ? found
|
||||
: gone.Contains(key) ? null
|
||||
: _entries.TryGetValue(key, out var held) ? held : null;
|
||||
|
||||
// A variant is written only through the variant API: a plain record never lands on a variant's key, and the
|
||||
// reverse is a rebase or a flatten, never an accident. A load reports what is on disk and is not a write.
|
||||
if (source == null)
|
||||
{
|
||||
foreach (var stored in admitted)
|
||||
{
|
||||
_entries.TryGetValue(stored.Key.Value, out var present);
|
||||
if (stored.Variant == null && !stored.Flattens && present?.Variant != null)
|
||||
throw new InvalidOperationException(
|
||||
$"Record {stored.Key.Value} is a variant of {present.Variant.BaseKey}; a plain write cannot replace it. " +
|
||||
"Change it through the variant API, or Flatten it.");
|
||||
if (stored.Variant != null && present != null && present.Variant == null)
|
||||
throw new InvalidOperationException(
|
||||
$"Record {stored.Key.Value} is a plain record; it cannot become a variant of {stored.Variant.BaseKey} in place. Use a new key.");
|
||||
if (stored.Variant != null && present?.Variant != null &&
|
||||
present.Descriptor.DocumentType != stored.Descriptor.DocumentType)
|
||||
throw new InvalidOperationException(
|
||||
$"Variant {stored.Key.Value} is a {present.Descriptor.DocumentType.Name}; " +
|
||||
$"rebasing it onto {stored.Variant.BaseKey} would make it a {stored.Descriptor.DocumentType.Name}.");
|
||||
}
|
||||
}
|
||||
|
||||
var changed = new HashSet<string>(incoming.Keys.Concat(gone), StringComparer.Ordinal);
|
||||
// A flatten resolves like the variant it replaces, against the post-batch set, so a base edited in the same
|
||||
// batch is in it; it lands as the plain record of that resolution.
|
||||
var toResolve = new List<string>(admitted.Where(stored => stored.Variant != null || stored.Flattens).Select(stored => stored.Key.Value));
|
||||
foreach (var variantKey in _variantKeys)
|
||||
{
|
||||
if (incoming.ContainsKey(variantKey) || gone.Contains(variantKey))
|
||||
continue;
|
||||
var next = _entries[variantKey].Variant!.BaseKey;
|
||||
for (var steps = 0; steps <= _entries.Count; steps++)
|
||||
{
|
||||
if (changed.Contains(next))
|
||||
{
|
||||
toResolve.Add(variantKey);
|
||||
break;
|
||||
}
|
||||
|
||||
var link = Lookup(next);
|
||||
if (link?.Variant == null)
|
||||
break;
|
||||
next = link.Variant.BaseKey;
|
||||
}
|
||||
}
|
||||
|
||||
if (toResolve.Count == 0)
|
||||
{
|
||||
var unchanged = new VariantPlan(admitted);
|
||||
RefuseVariantIndexSharing(unchanged, incoming, gone);
|
||||
return unchanged;
|
||||
}
|
||||
|
||||
var pending = new HashSet<string>(toResolve, StringComparer.Ordinal);
|
||||
var done = new Dictionary<string, CultStoredDocument>(StringComparer.Ordinal);
|
||||
var stack = new List<string>();
|
||||
foreach (var key in toResolve)
|
||||
ResolveOne(key);
|
||||
|
||||
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)
|
||||
{
|
||||
if (done.TryGetValue(key, out var finished))
|
||||
return finished;
|
||||
var variant = Lookup(key)!;
|
||||
if (stack.Contains(key))
|
||||
throw CycleRefusal(stack.SkipWhile(entry => entry != key).Append(key));
|
||||
stack.Add(key);
|
||||
|
||||
// A flatten carries no delta of its own; the variant it replaces does.
|
||||
var isVariant = variant.Variant != null;
|
||||
var delta = variant.Variant ?? _entries[key].Variant!;
|
||||
var baseStored = Lookup(delta.BaseKey) ?? throw MissingBaseRefusal(key, delta.BaseKey, gone.Contains(delta.BaseKey));
|
||||
if (pending.Contains(delta.BaseKey))
|
||||
baseStored = ResolveOne(delta.BaseKey);
|
||||
|
||||
var descriptor = variant.Descriptor;
|
||||
if (_codec == null)
|
||||
throw new InvalidOperationException(
|
||||
$"Variant {key} needs a codec to resolve; this cache has none. Create it with CultCacheMessagePack.Create.");
|
||||
if (baseStored.Descriptor.DocumentType != descriptor.DocumentType)
|
||||
throw new InvalidOperationException(
|
||||
$"Variant {key} is a {descriptor.DocumentType.Name} but its base {delta.BaseKey} is a {baseStored.Descriptor.DocumentType.Name}; " +
|
||||
"a variant has its base's concrete type.");
|
||||
|
||||
var type = descriptor.DocumentType;
|
||||
var kept = new List<KeyValuePair<int, byte[]>>();
|
||||
var seen = new HashSet<int>();
|
||||
foreach (var entry in delta.Overrides)
|
||||
{
|
||||
if (entry.Op != CultOverrideOp.Set || entry.Path.Count != 1 || entry.Path[0].ElementId.Length != 0 || entry.Id.Length != 0)
|
||||
throw new InvalidOperationException(
|
||||
$"Variant {key} carries {entry.Op} at {entry.PathText}; this runtime resolves top-level Set overrides only.");
|
||||
var slot = entry.Path[0].Slot;
|
||||
if (!seen.Add(slot))
|
||||
throw new InvalidOperationException($"Variant {key} overrides slot {slot} more than once; a variant has one override per slot.");
|
||||
var member = descriptor.RichMembers.FirstOrDefault(candidate => candidate.Slot == slot);
|
||||
// Drift is the load's business (ToStoredDocument sheds an override of a slot the type lacks), so a delta
|
||||
// reaching here names only slots the type has, unless someone is writing one it never had.
|
||||
if (member == null)
|
||||
throw new InvalidOperationException($"Variant {key} overrides slot {slot}, which {type.Name} does not have.");
|
||||
|
||||
try
|
||||
{
|
||||
_codec.Deserialize(member.MemberType, type, entry.Value);
|
||||
}
|
||||
catch (Exception exception)
|
||||
{
|
||||
// A value that no longer decodes refuses exactly as a plain record holding it does.
|
||||
throw new InvalidOperationException(
|
||||
$"Variant {key} overrides '{member.Member.Name}' (slot {slot}) with a value that does not decode as {member.MemberType.Name}: " +
|
||||
exception.GetBaseException().Message, exception);
|
||||
}
|
||||
|
||||
kept.Add(new KeyValuePair<int, byte[]>(slot, entry.Value));
|
||||
}
|
||||
|
||||
var payload = _codec.Serialize(baseStored.Document, type, type);
|
||||
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)
|
||||
: new CultStoredDocument(variant.Key, variant.StoredAt, variant.Descriptor, document) { Flattens = true };
|
||||
}
|
||||
}
|
||||
|
||||
// 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)
|
||||
{
|
||||
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 landingByKey = landing.ToDictionary(stored => stored.Key.Value, StringComparer.Ordinal);
|
||||
|
||||
bool IsVariant(string key) =>
|
||||
landingByKey.TryGetValue(key, out var landed) ? landed.Variant != null : _variantKeys.Contains(key);
|
||||
|
||||
// One pass over what lands, one lookup per (index, value): the rule is linear in the records landing.
|
||||
var landedValues = new List<(CultStoredDocument Stored, (Type Type, string Alias) Index, string Value)>();
|
||||
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)
|
||||
{
|
||||
var value = pair.Value(stored.Document);
|
||||
if (string.IsNullOrWhiteSpace(value))
|
||||
continue;
|
||||
var index = (stored.Descriptor.DocumentType, pair.Key);
|
||||
landedValues.Add((stored, index, value));
|
||||
if (!landed.TryGetValue((index, value), out var landedKeys))
|
||||
landed[(index, value)] = landedKeys = new List<string>();
|
||||
landedKeys.Add(stored.Key.Value);
|
||||
}
|
||||
}
|
||||
|
||||
var holdersOf = new Dictionary<((Type Type, string Alias) Index, string Value), (string[] All, string[] Variants)>();
|
||||
foreach (var (stored, index, value) in landedValues)
|
||||
{
|
||||
if (!holdersOf.TryGetValue((index, value), out var known))
|
||||
{
|
||||
var all = (_indexes.TryGetValue(index, out var held) && held.TryGetValue(value, out var heldKeys)
|
||||
? heldKeys.Where(heldKey => !replaced.Contains(heldKey))
|
||||
: Enumerable.Empty<string>())
|
||||
.Concat(landed[(index, value)])
|
||||
.Distinct(StringComparer.Ordinal)
|
||||
.ToArray();
|
||||
holdersOf[(index, value)] = known = (all, all.Where(IsVariant).ToArray());
|
||||
}
|
||||
|
||||
var self = stored.Key.Value;
|
||||
var holder = known.All.FirstOrDefault(candidate => candidate != self);
|
||||
if (stored.Variant != null && holder != null)
|
||||
throw new InvalidOperationException(
|
||||
$"Variant {self} and {holder} both hold index {index.Alias} '{value}'; a variant must override its indexed member.");
|
||||
var variantHolder = known.Variants.FirstOrDefault(candidate => candidate != self);
|
||||
if (stored.Variant == null && variantHolder != null)
|
||||
throw new InvalidOperationException(
|
||||
$"Record {self} and variant {variantHolder} both hold index {index.Alias} '{value}'; " +
|
||||
"a variant may not share an indexed value with another record.");
|
||||
}
|
||||
}
|
||||
|
||||
private static InvalidOperationException CycleRefusal(IEnumerable<string> keys) =>
|
||||
new($"Variant bases form a cycle: {string.Join(" -> ", keys)}.");
|
||||
|
||||
private static InvalidOperationException MissingBaseRefusal(string variant, string baseKey, bool removed) =>
|
||||
new(removed
|
||||
? $"Record {baseKey} cannot go: variant {variant} is based on it. Remove or rebase the variant in the same commit."
|
||||
: $"Variant {variant} is based on {baseKey}, which does not exist.");
|
||||
|
||||
private List<Change> Apply(
|
||||
VariantPlan plan,
|
||||
IReadOnlyList<CultStoredDocument> evicted,
|
||||
CacheBackingStore? source)
|
||||
{
|
||||
var admitted = plan.Admitted;
|
||||
var changes = new List<Change>(admitted.Count + evicted.Count + plan.Dependents.Count);
|
||||
foreach (var stored in evicted)
|
||||
{
|
||||
if (!_entries.TryGetValue(stored.Key.Value, out var existing))
|
||||
|
|
@ -2275,10 +2718,11 @@ namespace GameCult.Caching
|
|||
Unindex(existing);
|
||||
_entries.Remove(stored.Key.Value);
|
||||
_handles.Remove(existing.Document);
|
||||
_variantKeys.Remove(stored.Key.Value);
|
||||
changes.Add(new Change(CultCacheDocumentChangeKind.Removed, existing, null, existing.Document, ++_sequence));
|
||||
}
|
||||
|
||||
foreach (var stored in admitted)
|
||||
foreach (var stored in admitted.Concat(plan.Dependents))
|
||||
{
|
||||
_entries.TryGetValue(stored.Key.Value, out var previous);
|
||||
if (previous != null)
|
||||
|
|
@ -2290,6 +2734,10 @@ namespace GameCult.Caching
|
|||
_entries[stored.Key.Value] = stored;
|
||||
_handles.AddOrUpdate(stored.Document, new KeyBox(stored.Key));
|
||||
Index(stored);
|
||||
if (stored.Variant == null)
|
||||
_variantKeys.Remove(stored.Key.Value);
|
||||
else
|
||||
_variantKeys.Add(stored.Key.Value);
|
||||
changes.Add(new Change(
|
||||
previous == null ? CultCacheDocumentChangeKind.Added : CultCacheDocumentChangeKind.Updated,
|
||||
stored,
|
||||
|
|
@ -2353,7 +2801,7 @@ namespace GameCult.Caching
|
|||
{
|
||||
var value = pair.Value(stored.Document);
|
||||
if (!string.IsNullOrWhiteSpace(value))
|
||||
MapOf(_indexes, (type, pair.Key))[value] = stored.Key.Value;
|
||||
AddHolder(_indexes, (type, pair.Key), value, stored.Key.Value);
|
||||
}
|
||||
}
|
||||
|
||||
|
|
@ -2366,7 +2814,26 @@ namespace GameCult.Caching
|
|||
if (_names.TryGetValue(type, out var names))
|
||||
RemoveKey(names, stored.Key.Value);
|
||||
foreach (var pair in _indexes.Where(pair => pair.Key.Type == type))
|
||||
RemoveKey(pair.Value, stored.Key.Value);
|
||||
RemoveHolder(pair.Value, stored.Key.Value);
|
||||
}
|
||||
|
||||
private static void AddHolder(Dictionary<(Type Type, string Alias), Dictionary<string, List<string>>> indexes, (Type, string) index, string value, string key)
|
||||
{
|
||||
if (!indexes.TryGetValue(index, out var map))
|
||||
indexes[index] = map = new Dictionary<string, List<string>>(StringComparer.Ordinal);
|
||||
if (!map.TryGetValue(value, out var keys))
|
||||
map[value] = keys = new List<string>();
|
||||
keys.Remove(key);
|
||||
keys.Add(key);
|
||||
}
|
||||
|
||||
private static void RemoveHolder(Dictionary<string, List<string>> map, string key)
|
||||
{
|
||||
foreach (var pair in map.ToArray())
|
||||
{
|
||||
if (pair.Value.Remove(key) && pair.Value.Count == 0)
|
||||
map.Remove(pair.Key);
|
||||
}
|
||||
}
|
||||
|
||||
private static Dictionary<string, string> MapOf<TKey>(Dictionary<TKey, Dictionary<string, string>> maps, TKey key)
|
||||
|
|
@ -2440,6 +2907,11 @@ namespace GameCult.Caching
|
|||
// any of it; if the cache refuses a record the call throws and the store keeps its previous view.
|
||||
protected internal Action<IReadOnlyList<CultStoredDocument>, IReadOnlyList<CultStoredDocument>>? Loaded;
|
||||
|
||||
// Set by the cache at attach: the cache's own resolution (variants, their indexed values, their bases) run over a
|
||||
// set of records a store is about to hold, mutating nothing. It throws the refusal the cache would give the same
|
||||
// set arriving as a load.
|
||||
protected internal Action<IReadOnlyList<CultStoredDocument>, IReadOnlyList<CultStoredDocument>>? Judging;
|
||||
|
||||
private readonly object _detachedGate = new();
|
||||
internal CultCache? Cache;
|
||||
|
||||
|
|
@ -2486,21 +2958,62 @@ namespace GameCult.Caching
|
|||
|
||||
protected CultPersistedRecord ToPersistedRecord(CultStoredDocument entry, Func<object, byte[]> serializePayload)
|
||||
{
|
||||
// A variant persists its delta and an empty payload; the resolved view is never written.
|
||||
return new CultPersistedRecord
|
||||
{
|
||||
Key = entry.Key.Value,
|
||||
SchemaId = entry.Descriptor.SchemaId,
|
||||
StoredAt = entry.StoredAt,
|
||||
Payload = serializePayload(entry.Document)
|
||||
Payload = entry.Variant != null ? Array.Empty<byte>() : serializePayload(entry.Document),
|
||||
Variant = entry.Variant
|
||||
};
|
||||
}
|
||||
|
||||
// The one load surface: a persisted record resolved against the current type, with the report of what that
|
||||
// resolution shed. A plain record sheds a member its type dropped by never carrying it into the document; a variant
|
||||
// sheds the override of such a slot by never carrying it into the delta, so a later type reusing the slot number
|
||||
// cannot resurrect it and a flush needs no rule of its own. The report is the schema diff's ignored slots plus the
|
||||
// overrides whose slot the type does not have, including one the persisted schema never listed.
|
||||
protected CultStoredDocument ToStoredDocument(
|
||||
CultPersistedRecord record,
|
||||
IReadOnlyCollection<CultSchemaCatalogEntry> catalog,
|
||||
Func<Type, byte[], object> deserializePayload)
|
||||
Func<Type, byte[], object> deserializePayload,
|
||||
out CultSchemaMigrationReport report)
|
||||
{
|
||||
var resolution = Registry.ResolvePersistedSchemaDetailed(record.SchemaId, catalog);
|
||||
report = resolution.Report;
|
||||
if (record.Variant != null)
|
||||
{
|
||||
var descriptor = resolution.Descriptor;
|
||||
bool Has(CultVariantOverride entryOverride) =>
|
||||
entryOverride.Path.Count != 1 || descriptor.RichMembers.Any(member => member.Slot == entryOverride.Path[0].Slot);
|
||||
var shed = record.Variant.Overrides
|
||||
.Where(entryOverride => !Has(entryOverride))
|
||||
.Select(entryOverride => entryOverride.Path[0].Slot)
|
||||
.Distinct()
|
||||
.OrderBy(slot => slot)
|
||||
.ToArray();
|
||||
if (shed.Length > 0)
|
||||
{
|
||||
// A slot the schema diff already reported is not reported twice.
|
||||
var unreported = shed.Except(report.IgnoredExtraSlots).ToArray();
|
||||
report.IgnoredExtraSlots = report.IgnoredExtraSlots.Concat(unreported).OrderBy(slot => slot).ToArray();
|
||||
report.Warnings = report.Warnings.Concat(unreported.Select(slot => new CultSchemaMigrationWarning
|
||||
{
|
||||
Code = "ignored_extra_slot",
|
||||
Message = $"Variant {record.Key} overrides slot {slot}, which {descriptor.DocumentType.Name} does not have; the override is ignored and shed on flush."
|
||||
})).ToArray();
|
||||
}
|
||||
|
||||
// The cache resolves it against its base when it admits the load.
|
||||
return new CultStoredDocument(
|
||||
new CultRecordKey(record.Key),
|
||||
record.StoredAt,
|
||||
descriptor,
|
||||
new CultVariantDelta(record.Variant.BaseKey, record.Variant.Overrides.Where(Has).ToArray()),
|
||||
null);
|
||||
}
|
||||
|
||||
var document = deserializePayload(resolution.Descriptor.DocumentType, record.Payload);
|
||||
return new CultStoredDocument(
|
||||
new CultRecordKey(record.Key),
|
||||
|
|
@ -2556,8 +3069,8 @@ namespace GameCult.Caching
|
|||
var persisted = new Dictionary<string, CultStoredDocument>(StringComparer.Ordinal);
|
||||
foreach (var record in snapshot.Records)
|
||||
{
|
||||
reports.Add(Registry.ResolvePersistedSchemaReport(record.SchemaId, snapshot.SchemaCatalog));
|
||||
var stored = ToStoredDocument(record, snapshot.SchemaCatalog, DeserializePayload);
|
||||
var stored = ToStoredDocument(record, snapshot.SchemaCatalog, DeserializePayload, out var report);
|
||||
reports.Add(report);
|
||||
persisted[stored.Key.Value] = stored;
|
||||
}
|
||||
|
||||
|
|
@ -2640,6 +3153,11 @@ namespace GameCult.Caching
|
|||
var catalog = ontoDisk
|
||||
? disk.SchemaCatalog
|
||||
: Entries.Values.Select(entry => entry.Descriptor.ToCatalogEntry());
|
||||
// The committer judged the batch against its own view; the file may have moved since. A merge is judged on the
|
||||
// set the file will hold, exactly as that set would be judged loading: what other processes wrote (arriving),
|
||||
// what they removed (departing), and this batch.
|
||||
if (ontoDisk && Judging != null && MergeInvolvesVariants(request, disk))
|
||||
JudgeMerge(request, disk);
|
||||
foreach (var entry in request.Deletes)
|
||||
records.Remove(entry.Key.Value);
|
||||
foreach (var entry in request.Upserts)
|
||||
|
|
@ -2654,6 +3172,35 @@ namespace GameCult.Caching
|
|||
return CultCommitOutcome.Committed;
|
||||
}
|
||||
|
||||
// Only a variant makes a merge more than the committer's own judgement: a variant it lands, one another writer wrote
|
||||
// (read from the record's header, never its payload), or one this cache holds. A plain-only store never decodes
|
||||
// another writer's records, so a schema this cache does not register cannot fail a commit that involves no variant.
|
||||
private bool MergeInvolvesVariants(CultCommitRequest request, CultPersistedStoreSnapshot disk) =>
|
||||
Cache?.HoldsVariants == true ||
|
||||
request.Upserts.Any(entry => entry.Variant != null) ||
|
||||
disk.Records.Any(record => record.Variant != null);
|
||||
|
||||
private void JudgeMerge(CultCommitRequest request, CultPersistedStoreSnapshot disk)
|
||||
{
|
||||
var landing = request.Upserts.Select(entry => entry.Key.Value).ToHashSet(StringComparer.Ordinal);
|
||||
var removing = request.Deletes.Select(entry => entry.Key.Value).ToHashSet(StringComparer.Ordinal);
|
||||
var onDisk = disk.Records.Select(record => record.Key).ToHashSet(StringComparer.Ordinal);
|
||||
var arriving = new List<CultStoredDocument>(request.Upserts);
|
||||
foreach (var record in disk.Records)
|
||||
{
|
||||
if (landing.Contains(record.Key) || removing.Contains(record.Key))
|
||||
continue;
|
||||
if (Entries.TryGetValue(record.Key, out var known) && known.StoredAt == record.StoredAt && known.Descriptor.SchemaId == record.SchemaId)
|
||||
continue;
|
||||
arriving.Add(ToStoredDocument(record, disk.SchemaCatalog, DeserializePayload, out _));
|
||||
}
|
||||
|
||||
var departing = new List<CultStoredDocument>(request.Deletes);
|
||||
departing.AddRange(Entries.Values.Where(known =>
|
||||
!onDisk.Contains(known.Key.Value) && !landing.Contains(known.Key.Value) && !removing.Contains(known.Key.Value)));
|
||||
Judging!(arriving, departing);
|
||||
}
|
||||
|
||||
private CultPersistedStoreSnapshot? ReadSnapshot()
|
||||
{
|
||||
FileInfo.Refresh();
|
||||
|
|
@ -2675,6 +3222,10 @@ namespace GameCult.Caching
|
|||
var used = new HashSet<string>(ordered.Select(record => record.SchemaId), StringComparer.Ordinal);
|
||||
var snapshot = new CultPersistedStoreSnapshot
|
||||
{
|
||||
// v2 exactly when the store holds a variant: a store without one stays byte-identical v1.
|
||||
FormatVersion = ordered.Any(record => record.Variant != null)
|
||||
? CultPersistedStoreSnapshot.FormatV2
|
||||
: CultPersistedStoreSnapshot.FormatV1,
|
||||
SchemaCatalog = catalog
|
||||
.GroupBy(entry => entry.SchemaId, StringComparer.Ordinal)
|
||||
.Select(group => group.First())
|
||||
|
|
|
|||
|
|
@ -292,22 +292,24 @@ namespace GameCult.Caching
|
|||
typeof(int), typeof(long), typeof(uint), typeof(short), typeof(ushort), typeof(byte), typeof(sbyte)
|
||||
};
|
||||
|
||||
private readonly Func<object, Type, Type, byte[]> _serialize;
|
||||
private readonly Func<Type, byte[], object> _deserialize;
|
||||
private readonly CultCodec _codec;
|
||||
private readonly Dictionary<Type, CultInspectorShape> _shapes = new Dictionary<Type, CultInspectorShape>();
|
||||
private readonly Dictionary<MemberInfo, CultInspectorMetadata> _metadata = new Dictionary<MemberInfo, CultInspectorMetadata>();
|
||||
|
||||
// serialize (value, value type, owning document type) and deserialize are the store's codec
|
||||
// (CultCacheMessagePack.CreateInspectorModel for .cc stores). Edits clone documents through both; dictionary keys
|
||||
// compare by serialize under their owning document, exactly as the store writes them inside it, so serialize must
|
||||
// take any value, not only documents.
|
||||
public CultInspectorModel(CultDocumentRegistry registry, Func<object, Type, Type, byte[]> serialize, Func<Type, byte[], object> deserialize)
|
||||
// The codec is the store's (CultCacheMessagePack.CreateInspectorModel for .cc stores), the one a CultCache resolves
|
||||
// variants with. Edits clone documents through it; dictionary keys compare by its Serialize under their owning
|
||||
// document, exactly as the store writes them inside it.
|
||||
public CultInspectorModel(CultDocumentRegistry registry, CultCodec codec)
|
||||
{
|
||||
Registry = registry ?? throw new ArgumentNullException(nameof(registry));
|
||||
_serialize = serialize ?? throw new ArgumentNullException(nameof(serialize));
|
||||
_deserialize = deserialize ?? throw new ArgumentNullException(nameof(deserialize));
|
||||
_codec = codec ?? throw new ArgumentNullException(nameof(codec));
|
||||
}
|
||||
|
||||
private byte[] _serialize(object value, Type type, Type document) => _codec.Serialize(value, type, document);
|
||||
|
||||
private object _deserialize(Type type, byte[] bytes) =>
|
||||
_codec.Deserialize(type, type, bytes) ?? throw new InvalidOperationException($"The codec returned null for {type.FullName}.");
|
||||
|
||||
public CultDocumentRegistry Registry { get; }
|
||||
|
||||
public static string RecordLabel(CultStoredDocument record)
|
||||
|
|
|
|||
91
src/GameCult.Caching/CultVariants.cs
Normal file
91
src/GameCult.Caching/CultVariants.cs
Normal file
|
|
@ -0,0 +1,91 @@
|
|||
using System;
|
||||
using System.Collections.Generic;
|
||||
using System.Linq;
|
||||
|
||||
namespace GameCult.Caching
|
||||
{
|
||||
// The store's encoding, as the cache needs it: the one pair CultInspectorModel and variant resolution share.
|
||||
// Serialize takes any value, not only documents, under its owning document type's options; Deserialize is its
|
||||
// inverse (a document type is checked against the registry, a member type is not); Overlay replaces slots of a
|
||||
// serialized document payload with already-encoded member values and touches nothing else.
|
||||
public sealed class CultCodec
|
||||
{
|
||||
public CultCodec(
|
||||
Func<object, Type, Type, byte[]> serialize,
|
||||
Func<Type, Type, byte[], object?> deserialize,
|
||||
Func<byte[], IReadOnlyList<KeyValuePair<int, byte[]>>, byte[]> overlay)
|
||||
{
|
||||
Serialize = serialize ?? throw new ArgumentNullException(nameof(serialize));
|
||||
Deserialize = deserialize ?? throw new ArgumentNullException(nameof(deserialize));
|
||||
Overlay = overlay ?? throw new ArgumentNullException(nameof(overlay));
|
||||
}
|
||||
|
||||
// (value, value type, owning document type)
|
||||
public Func<object, Type, Type, byte[]> Serialize { get; }
|
||||
|
||||
// (value type, owning document type, bytes)
|
||||
public Func<Type, Type, byte[], object?> Deserialize { get; }
|
||||
|
||||
// (document payload, slot and encoded value pairs)
|
||||
public Func<byte[], IReadOnlyList<KeyValuePair<int, byte[]>>, byte[]> Overlay { get; }
|
||||
}
|
||||
|
||||
public enum CultOverrideOp
|
||||
{
|
||||
Set = 0,
|
||||
Insert = 1,
|
||||
Remove = 2
|
||||
}
|
||||
|
||||
// One step of a member path: the MessagePack slot, and the id of the object-list element the step enters ("" when it
|
||||
// does not enter one).
|
||||
public sealed class CultPathStep
|
||||
{
|
||||
public CultPathStep(int slot, string elementId = "")
|
||||
{
|
||||
Slot = slot;
|
||||
ElementId = elementId ?? string.Empty;
|
||||
}
|
||||
|
||||
public int Slot { get; }
|
||||
public string ElementId { get; }
|
||||
|
||||
public override string ToString() => ElementId.Length == 0 ? $"[{Slot}]" : $"[{Slot}:{ElementId}]";
|
||||
}
|
||||
|
||||
// The wire shape [op, path[], id, value]; value is the override's already-encoded MessagePack value.
|
||||
public sealed class CultVariantOverride
|
||||
{
|
||||
public CultVariantOverride(CultOverrideOp op, IReadOnlyList<CultPathStep> path, string id, byte[] value)
|
||||
{
|
||||
Op = op;
|
||||
Path = path ?? throw new ArgumentNullException(nameof(path));
|
||||
Id = id ?? string.Empty;
|
||||
Value = value ?? throw new ArgumentNullException(nameof(value));
|
||||
}
|
||||
|
||||
public CultOverrideOp Op { get; }
|
||||
public IReadOnlyList<CultPathStep> Path { get; }
|
||||
public string Id { get; }
|
||||
public byte[] Value { get; }
|
||||
|
||||
// A top-level Set: the whole member at slot takes the encoded value.
|
||||
public static CultVariantOverride Set(int slot, byte[] value) =>
|
||||
new(CultOverrideOp.Set, new[] { new CultPathStep(slot) }, string.Empty, value);
|
||||
|
||||
internal string PathText => string.Concat(Path.Select(step => step.ToString()));
|
||||
}
|
||||
|
||||
// What a variant record stores: its base and its overrides. Never the resolved document.
|
||||
public sealed class CultVariantDelta
|
||||
{
|
||||
public CultVariantDelta(string baseKey, IReadOnlyList<CultVariantOverride> overrides)
|
||||
{
|
||||
BaseKey = baseKey ?? throw new ArgumentNullException(nameof(baseKey));
|
||||
Overrides = overrides ?? throw new ArgumentNullException(nameof(overrides));
|
||||
}
|
||||
|
||||
public string BaseKey { get; }
|
||||
public IReadOnlyList<CultVariantOverride> Overrides { get; }
|
||||
}
|
||||
}
|
||||
|
|
@ -156,6 +156,8 @@ namespace GameCult.Mesh
|
|||
$"CultCache document '{path}' record '{key.Value}' has schema '{record.SchemaId}', expected '{expectedSchemaId}'.");
|
||||
}
|
||||
|
||||
RefuseVariant(path, record);
|
||||
|
||||
if (!PublishesSchema(snapshot.SchemaCatalog, expectedSchemaId))
|
||||
{
|
||||
throw new InvalidDataException(
|
||||
|
|
@ -198,6 +200,15 @@ namespace GameCult.Mesh
|
|||
return record.Payload;
|
||||
}
|
||||
|
||||
// A variant record's payload is empty; its document exists only as the cache resolves it against its base.
|
||||
private static void RefuseVariant(string path, CultPersistedRecord record)
|
||||
{
|
||||
if (record.Variant != null)
|
||||
throw new NotSupportedException(
|
||||
$"CultCache document '{path}' record '{record.Key}' is a variant of '{record.Variant.BaseKey}'; " +
|
||||
"CultMesh does not resolve document variants, open the store with a CultCache.");
|
||||
}
|
||||
|
||||
private static void WriteSingleFileDocumentPayload(
|
||||
string path,
|
||||
CultRecordKey key,
|
||||
|
|
@ -236,14 +247,18 @@ namespace GameCult.Mesh
|
|||
private static CultPersistedStoreSnapshot ReadSingleFileSnapshot(string path)
|
||||
{
|
||||
var bytes = File.ReadAllBytes(path);
|
||||
CultPersistedStoreSnapshot snapshot;
|
||||
try
|
||||
{
|
||||
return CultDocumentMessagePackSerialization.DeserializeSnapshot(bytes);
|
||||
snapshot = CultDocumentMessagePackSerialization.DeserializeSnapshot(bytes);
|
||||
}
|
||||
catch (Exception ex) when (ex is MessagePackSerializationException or InvalidOperationException)
|
||||
{
|
||||
return ReadLegacySingleFileSnapshot(bytes);
|
||||
snapshot = ReadLegacySingleFileSnapshot(bytes);
|
||||
}
|
||||
|
||||
CultDocumentMessagePackSerialization.RequireSingleFileFormat(snapshot);
|
||||
return snapshot;
|
||||
}
|
||||
|
||||
private static CultPersistedStoreSnapshot ReadLegacySingleFileSnapshot(byte[] bytes)
|
||||
|
|
@ -252,7 +267,8 @@ namespace GameCult.Mesh
|
|||
var fieldCount = reader.ReadArrayHeader();
|
||||
var snapshot = new CultPersistedStoreSnapshot();
|
||||
if (fieldCount > 0)
|
||||
snapshot.FormatVersion = reader.ReadString() ?? "cultcache.store.v1";
|
||||
snapshot.FormatVersion = reader.ReadString()
|
||||
?? throw new NotSupportedException("Store snapshot declares no format version.");
|
||||
|
||||
if (fieldCount > 1)
|
||||
{
|
||||
|
|
@ -267,7 +283,7 @@ namespace GameCult.Mesh
|
|||
var recordCount = reader.ReadArrayHeader();
|
||||
snapshot.Records = new CultPersistedRecord[recordCount];
|
||||
for (var index = 0; index < recordCount; index++)
|
||||
snapshot.Records[index] = ReadLegacyPersistedRecord(ref reader);
|
||||
snapshot.Records[index] = CultDocumentMessagePackSerialization.ReadPersistedRecord(ref reader);
|
||||
}
|
||||
|
||||
for (var index = 3; index < fieldCount; index++)
|
||||
|
|
@ -303,23 +319,6 @@ namespace GameCult.Mesh
|
|||
return entry;
|
||||
}
|
||||
|
||||
private static CultPersistedRecord ReadLegacyPersistedRecord(ref MessagePackReader reader)
|
||||
{
|
||||
var fieldCount = reader.ReadArrayHeader();
|
||||
var record = new CultPersistedRecord();
|
||||
if (fieldCount > 0) record.Key = reader.ReadString() ?? string.Empty;
|
||||
if (fieldCount > 1) record.SchemaId = reader.ReadString() ?? string.Empty;
|
||||
if (fieldCount > 2) record.StoredAt = reader.ReadString() ?? string.Empty;
|
||||
if (fieldCount > 3)
|
||||
{
|
||||
var payload = reader.ReadBytes();
|
||||
record.Payload = payload.HasValue ? payload.Value.ToArray() : Array.Empty<byte>();
|
||||
}
|
||||
for (var index = 4; index < fieldCount; index++)
|
||||
reader.Skip();
|
||||
return record;
|
||||
}
|
||||
|
||||
private static bool PublishesSchema(CultSchemaCatalogEntry[] catalog, string schemaId)
|
||||
{
|
||||
return catalog.Any(entry =>
|
||||
|
|
|
|||
|
|
@ -47,6 +47,14 @@ The content protocol uses one bounded response per manifest chunk. A snapshot
|
|||
response containing `gamecult.mesh.cdn_artifact_chunk.v1` payload records is a
|
||||
legacy transport path and must not be used for bulk delivery.
|
||||
|
||||
The Rust runtime speaks the same chunk messages through `cultnet-rs`
|
||||
`fetch_content`, which verifies every chunk and then the whole body, and
|
||||
`answer_content_chunk_request`, which mirrors the legacy server's validation
|
||||
order and error spelling. Its transport is an explicit closure over the session
|
||||
the caller already holds, carrying the chunks as ordinary schema frames until
|
||||
Rust has an authenticated content connector; the chunk bytes, manifest shape
|
||||
and verification do not change when that connector arrives.
|
||||
|
||||
The transfer owner may keep a bounded window of requests in flight per content
|
||||
hash (four by default, never more than 32). Candidate chunks can arrive out of
|
||||
order, but only the transfer owner writes them, and it flushes and checkpoints
|
||||
|
|
|
|||
|
|
@ -102,6 +102,14 @@ lower priority than TCP. Existing hot-state publishers that still package
|
|||
payloads as schema messages must move to the realtime connector contract; the
|
||||
new seam does not pretend that migration has already occurred.
|
||||
|
||||
The Rust runtime's content path is this compatibility path, chosen explicitly:
|
||||
`cultnet-rs` sends chunk requests and reads chunk responses on the session the
|
||||
client already holds, byte-identical on the wire to
|
||||
`CultMeshLegacyRudpContentServer` (`fetch_content` and
|
||||
`answer_content_chunk_request`). It is never an implicit default, and it lasts
|
||||
until Rust has an authenticated content connector (TCP+TLS or QUIC), which will
|
||||
sit behind the same `fetch_content` owner rather than beside it.
|
||||
|
||||
## Security and release gate
|
||||
|
||||
The current TCP control and content connectors are plaintext and therefore
|
||||
|
|
|
|||
|
|
@ -1,5 +1,6 @@
|
|||
using System;
|
||||
using System.Collections.Concurrent;
|
||||
using System.Collections.Generic;
|
||||
using System.Linq;
|
||||
using System.Reflection;
|
||||
using System.Threading.Tasks;
|
||||
|
|
@ -502,16 +503,48 @@ namespace GameCult.Networking
|
|||
string subscriptionId,
|
||||
CultNetServerPeer peer)
|
||||
{
|
||||
// Keys this subscriber only ever received as a refusal: it was never given them as records.
|
||||
var refused = new HashSet<string>(StringComparer.Ordinal);
|
||||
return _database.WatchAllChanges().Subscribe(change =>
|
||||
{
|
||||
var outbound = CreateChangeMessage(change, subscriptionId, selection);
|
||||
var outbound = DeliverChange(change, subscriptionId, selection, refused, error => peer.SendCultNet(error));
|
||||
if (outbound != null)
|
||||
{
|
||||
peer.SendCultNet(outbound);
|
||||
}
|
||||
});
|
||||
}
|
||||
|
||||
// One subscriber's view of one change. A variant is not a record CultNet can carry (Q6): the subscriber is told, by key, and
|
||||
// is not later told the variant was removed, because it never held it.
|
||||
internal CultNetDatabaseChangeRawMessage? DeliverChange(
|
||||
object change,
|
||||
string subscriptionId,
|
||||
CultNetSelection selection,
|
||||
HashSet<string> refused,
|
||||
Action<CultNetErrorMessage> sendError)
|
||||
{
|
||||
CultNetDatabaseChangeRawMessage? outbound;
|
||||
try
|
||||
{
|
||||
outbound = CreateChangeMessage(change, subscriptionId, selection);
|
||||
}
|
||||
catch (NotSupportedException refusal)
|
||||
{
|
||||
var refusedKey = change.GetType().GetProperty("Key")?.GetValue(change) is CultRecordKey changed ? changed.Value : string.Empty;
|
||||
lock (refused)
|
||||
refused.Add(refusedKey);
|
||||
sendError(new CultNetErrorMessage { Error = refusal.Message });
|
||||
return null;
|
||||
}
|
||||
|
||||
if (outbound == null)
|
||||
return null;
|
||||
var recordKey = outbound.RecordKey ?? outbound.Document?.RecordKey ?? string.Empty;
|
||||
bool wasRefused;
|
||||
lock (refused)
|
||||
wasRefused = refused.Remove(recordKey);
|
||||
return wasRefused && outbound.ChangeKind == "removed" ? null : outbound;
|
||||
}
|
||||
|
||||
internal CultNetDatabaseChangeRawMessage? CreateChangeMessage(
|
||||
object change,
|
||||
string subscriptionId,
|
||||
|
|
@ -549,6 +582,7 @@ namespace GameCult.Networking
|
|||
};
|
||||
}
|
||||
|
||||
CultNetDocumentRegistry.RefuseVariantChange(_database.Cache, key);
|
||||
return new CultNetDatabaseChangeRawMessage
|
||||
{
|
||||
MessageId = Guid.NewGuid().ToString("N"),
|
||||
|
|
|
|||
|
|
@ -204,6 +204,13 @@ namespace GameCult.Networking
|
|||
peer.SendCultNet(CultNetErrorMessage.ForReferenceOutsideTarget(ex));
|
||||
return Task.CompletedTask;
|
||||
}
|
||||
catch (NotSupportedException refusal)
|
||||
{
|
||||
// Q6: a snapshot that selects a variant is refused to this subscriber as a typed error.
|
||||
Withdraw(key, sendRemovals: false, forgetRequest: true);
|
||||
peer.SendCultNet(CultNetErrorMessage.ForVariantUnsupported(refusal.Message, subscriptionId));
|
||||
return Task.CompletedTask;
|
||||
}
|
||||
catch
|
||||
{
|
||||
Withdraw(key, sendRemovals: false, forgetRequest: true);
|
||||
|
|
@ -315,7 +322,18 @@ namespace GameCult.Networking
|
|||
}
|
||||
|
||||
var sourceRecordKey = ResolveChangeRecordKey(change);
|
||||
var matched = CreateMatchedRecord(change, request, peer);
|
||||
CultNetRawDocumentRecord? matched;
|
||||
try
|
||||
{
|
||||
matched = CreateMatchedRecord(change, request, peer);
|
||||
}
|
||||
catch (NotSupportedException refusal)
|
||||
{
|
||||
// Q6: a variant is not a record CultNet can carry; the subscriber that would have received it is told, by key.
|
||||
peer.SendCultNet(CultNetErrorMessage.ForVariantUnsupported(refusal.Message));
|
||||
return;
|
||||
}
|
||||
|
||||
ApplyProjectedChange(
|
||||
projection,
|
||||
sourceRecordKey,
|
||||
|
|
@ -331,9 +349,23 @@ namespace GameCult.Networking
|
|||
if (!_projections.TryGetValue(key, out var projection)) return;
|
||||
var legacyRequest = request.ToLegacyShape(key.Id);
|
||||
var authorized = _authorizeRequest?.Invoke(legacyRequest, key.Peer) != false;
|
||||
var next = authorized
|
||||
? CreateProjectedSnapshot(request, key.Peer)
|
||||
: ProjectedSnapshot.Empty;
|
||||
ProjectedSnapshot next;
|
||||
try
|
||||
{
|
||||
next = authorized
|
||||
? CreateProjectedSnapshot(request, key.Peer)
|
||||
: ProjectedSnapshot.Empty;
|
||||
}
|
||||
catch (NotSupportedException refusal)
|
||||
{
|
||||
// Q6: the selection selects a variant, which CultNet cannot carry. The subscription is withdrawn, so the peer is
|
||||
// told once, not once per store change; the rows it delivered are withdrawn too (removals first), so the peer
|
||||
// does not keep them as live, and the typed error names the subscription that ended. A change never throws out of
|
||||
// the change handler.
|
||||
Withdraw(key, sendRemovals: true, forgetRequest: true);
|
||||
key.Peer.SendCultNet(CultNetErrorMessage.ForVariantUnsupported(refusal.Message, key.Id));
|
||||
return;
|
||||
}
|
||||
|
||||
// With _projectRecord gone (docs/cultnet-selection-cut.md, S2-2), a projection's dictionary
|
||||
// key is always the record's own RecordKey/SchemaId, so the two can never disagree here;
|
||||
|
|
@ -541,6 +573,7 @@ namespace GameCult.Networking
|
|||
if (kind == CultNetDatabaseChangeKind.Removed || document == null)
|
||||
return null;
|
||||
|
||||
CultNetDocumentRegistry.RefuseVariantChange(_database.Cache, key);
|
||||
return _database.Documents.ToRawRecord(descriptor, key, document, DateTimeOffset.UtcNow.ToString("O"));
|
||||
}
|
||||
|
||||
|
|
|
|||
|
|
@ -391,11 +391,13 @@ namespace GameCult.Networking
|
|||
var stored = cache.AllStoredDocuments;
|
||||
if (rowFilter != null)
|
||||
stored = stored.Where(entry => rowFilter(entry.Descriptor, entry.Key));
|
||||
var rows = stored
|
||||
var entries = stored.ToArray();
|
||||
var rows = entries
|
||||
.Select(entry => new CultNetSelectionEvaluator.Row(
|
||||
entry.Descriptor, entry.Key, entry.Document, ordinalOf(entry.Descriptor.SchemaId, entry.Key), entry.StoredAt))
|
||||
.ToArray();
|
||||
var full = CultNetSelectionEvaluator.EvaluateAll(_documents, rows, selection);
|
||||
RefuseVariants(entries, full.Ordered.Select(row => row.Key));
|
||||
// R-Q: a page's asOf is exact only when every matched row is committed through one shard's
|
||||
// log - a caller that knows about shards (CultNetDatabaseServer) supplies shardIdOf; one
|
||||
// that does not (the raw v0/shard-scoped rowFilter paths, which are already bounded to a
|
||||
|
|
@ -415,6 +417,7 @@ namespace GameCult.Networking
|
|||
}
|
||||
|
||||
var evaluation = CultNetSelectionEvaluator.Page(full, selection, asOf, cursorKey);
|
||||
RefuseVariants(entries, evaluation.Edges.Select(edge => edge.From.Key));
|
||||
var records = evaluation.Rows.Select(row => ToRawRecord(row, options)).ToArray();
|
||||
var wantDocument = selection.Projection == CultNetSelectionProjections.Document;
|
||||
|
||||
|
|
@ -485,17 +488,20 @@ namespace GameCult.Networking
|
|||
var stored = cache.AllStoredDocuments;
|
||||
if (rowFilter != null)
|
||||
stored = stored.Where(entry => rowFilter(entry.Descriptor, entry.Key));
|
||||
var rows = stored
|
||||
var entries = stored.ToArray();
|
||||
var rows = entries
|
||||
.Select(entry => new CultNetSelectionEvaluator.Row(
|
||||
entry.Descriptor, entry.Key, entry.Document, ordinalOf(entry.Descriptor.SchemaId, entry.Key), entry.StoredAt))
|
||||
.ToArray();
|
||||
|
||||
var full = CultNetSelectionEvaluator.EvaluateAll(_documents, rows, selection);
|
||||
RefuseVariants(entries, full.Ordered.Select(row => row.Key));
|
||||
var records = full.Ordered.Select(row => ToRawRecord(row, options)).ToArray();
|
||||
var wantDocument = selection.Projection == CultNetSelectionProjections.Document;
|
||||
var edges = selection.HasHop
|
||||
? CultNetSelectionEvaluator.EdgesFor(full.Ordered, full).Select(edge => ToEdge(edge, wantDocument)).ToArray()
|
||||
: null;
|
||||
var hopEdges = selection.HasHop ? CultNetSelectionEvaluator.EdgesFor(full.Ordered, full) : null;
|
||||
if (hopEdges != null)
|
||||
RefuseVariants(entries, hopEdges.Select(edge => edge.From.Key));
|
||||
var edges = hopEdges?.Select(edge => ToEdge(edge, wantDocument)).ToArray();
|
||||
|
||||
return new CultNetSelectionPage
|
||||
{
|
||||
|
|
@ -549,6 +555,34 @@ namespace GameCult.Networking
|
|||
};
|
||||
}
|
||||
|
||||
// CultNet carries no variant deltas yet, and a resolved view sent as a plain record would be a lie about the store.
|
||||
// The refusal follows the selection: a variant is refused only when the selection selects it, never for existing. An
|
||||
// edge carries its citer's reference payload, read from the citer's resolved document, so a variant citing is selected
|
||||
// by the selection's hop exactly as a variant row is.
|
||||
private static void RefuseVariants(IReadOnlyList<CultStoredDocument> entries, IEnumerable<CultRecordKey> selected)
|
||||
{
|
||||
if (!entries.Any(entry => entry.Variant != null))
|
||||
return;
|
||||
var variants = entries.Where(entry => entry.Variant != null).ToDictionary(entry => entry.Key.Value, StringComparer.Ordinal);
|
||||
foreach (var key in selected)
|
||||
{
|
||||
if (variants.TryGetValue(key.Value, out var variant))
|
||||
throw VariantRefusal(variant);
|
||||
}
|
||||
}
|
||||
|
||||
// The live-change funnel's refusal: a load or write that lands a variant must not reach a subscriber as a record.
|
||||
internal static void RefuseVariantChange(CultCache cache, CultRecordKey key)
|
||||
{
|
||||
// Recorded, not fixed: a Flatten committed on another thread between the change's admission and this read makes
|
||||
// the record plain here, and its resolved view is delivered. The window is one thread hop wide.
|
||||
if (cache.GetStored(key) is { Variant: not null } entry)
|
||||
throw VariantRefusal(entry);
|
||||
}
|
||||
|
||||
private static NotSupportedException VariantRefusal(CultStoredDocument entry) =>
|
||||
new($"Record '{entry.Key.Value}' is a variant of '{entry.Variant!.BaseKey}'; CultNet does not carry document variants yet.");
|
||||
|
||||
/// <summary>
|
||||
/// Builds the wire record for one evaluated row. The shared path under snapshot and change
|
||||
/// (docs/cultnet-selection-cut.md, section 8's "shared paths").
|
||||
|
|
|
|||
|
|
@ -546,6 +546,18 @@ namespace GameCult.Networking
|
|||
: null
|
||||
};
|
||||
|
||||
/// <summary>
|
||||
/// Builds the wire error for a selection that selects a document variant, which CultNet does not carry yet: code
|
||||
/// <c>variant_unsupported</c>, details <c>{ field: "subscriptionId", value }</c> when a subscription was ended by it.
|
||||
/// </summary>
|
||||
public static CultNetErrorMessage ForVariantUnsupported(string message, string? subscriptionId = null) =>
|
||||
new CultNetErrorMessage
|
||||
{
|
||||
Error = message,
|
||||
Code = "variant_unsupported",
|
||||
Details = subscriptionId == null ? null : new CultNetErrorDetails { Field = "subscriptionId", Value = subscriptionId }
|
||||
};
|
||||
|
||||
/// <summary>
|
||||
/// Builds the wire error for an out-of-target reference refusal (R-N): code
|
||||
/// <c>reference_outside_target</c>, no details.
|
||||
|
|
|
|||
|
|
@ -707,6 +707,7 @@ namespace GameCult.Caching.Tests
|
|||
}
|
||||
|
||||
[Test]
|
||||
[Platform("Win", Reason = "Holds an open FileShare.Read handle and expects a delete or replace to fail; Linux unlink and rename ignore open handles.")]
|
||||
public async Task DirectoryMessagePackBackingStore_Deletion_Commits_While_Locked_Old_Page_Remains_An_Orphan()
|
||||
{
|
||||
var filePath = Path.Combine(Path.GetTempPath(), $"cultlib-tests-{Guid.NewGuid():N}.cc");
|
||||
|
|
|
|||
|
|
@ -37,6 +37,7 @@ namespace GameCult.Caching.Tests
|
|||
}
|
||||
|
||||
[Test]
|
||||
[Platform("Win", Reason = "Holds an open FileShare.Read handle and expects a delete or replace to fail; Linux unlink and rename ignore open handles.")]
|
||||
public async Task FailedManifestReplaceKeepsPreviousGeneration()
|
||||
{
|
||||
using var cache = Open(out _);
|
||||
|
|
|
|||
|
|
@ -1,6 +1,7 @@
|
|||
#nullable enable
|
||||
using System;
|
||||
using System.IO;
|
||||
using System.Linq;
|
||||
using System.Threading.Tasks;
|
||||
using GameCult.Caching;
|
||||
using GameCult.Caching.MessagePack;
|
||||
|
|
@ -83,6 +84,101 @@ namespace GameCult.Caching.Tests
|
|||
}
|
||||
}
|
||||
|
||||
// Shared refusal vectors: tests/vectors/document-variants-c0, read by every runtime's tests.
|
||||
private const string ItemSchemaId = "sha256:88d3fdf0a927acf3b163940d8f8c7fe62b3316542ce771a67ec8bc038f594788";
|
||||
|
||||
private static string VectorPath(string name)
|
||||
{
|
||||
for (var dir = new DirectoryInfo(TestContext.CurrentContext.TestDirectory); dir != null; dir = dir.Parent)
|
||||
{
|
||||
var candidate = Path.Combine(dir.FullName, "tests", "vectors", "document-variants-c0", name);
|
||||
if (File.Exists(candidate)) return candidate;
|
||||
}
|
||||
throw new FileNotFoundException($"Shared vector {name} not found above {TestContext.CurrentContext.TestDirectory}.");
|
||||
}
|
||||
|
||||
private static string Refusal(string vector)
|
||||
{
|
||||
var root = Path.Combine(Path.GetTempPath(), $"cultlib-vector-{Guid.NewGuid():N}");
|
||||
Directory.CreateDirectory(root);
|
||||
try
|
||||
{
|
||||
var file = Path.Combine(root, "store.msgpack");
|
||||
File.Copy(VectorPath(vector), file);
|
||||
using var cache = new CultCache();
|
||||
var error = Assert.Catch(() => cache.AddBackingStore(new SingleFileMessagePackBackingStore(file)));
|
||||
Assert.That(error, Is.Not.Null);
|
||||
Assert.That(error!.ToString(), Does.Contain(nameof(NotSupportedException)));
|
||||
return error.ToString();
|
||||
}
|
||||
finally
|
||||
{
|
||||
if (Directory.Exists(root)) Directory.Delete(root, recursive: true);
|
||||
}
|
||||
}
|
||||
|
||||
[Test]
|
||||
public void SingleFileRefusesUnknownHeaderByName()
|
||||
{
|
||||
Assert.That(Refusal("unknown-header.msgpack"), Does.Contain("cultcache.store.v9"));
|
||||
}
|
||||
|
||||
[Test]
|
||||
public void SingleFileRefusesExtraRecordSlotNamingTheRecord()
|
||||
{
|
||||
var message = Refusal("extra-slot-full-payload.msgpack");
|
||||
Assert.That(message, Does.Contain("item:anvil"));
|
||||
Assert.That(message, Does.Contain(ItemSchemaId));
|
||||
}
|
||||
|
||||
// C1 reads v2. This vector was written by hand before C1 existed and its variant keeps its base's name, so a
|
||||
// cache with a codec refuses it under R6, naming both records; a cache without one cannot resolve it at all.
|
||||
[Test]
|
||||
public void SingleFileRefusesTheHandWrittenVariantVectorNamingTheRecords()
|
||||
{
|
||||
var root = Path.Combine(Path.GetTempPath(), $"cultlib-vector-{Guid.NewGuid():N}");
|
||||
Directory.CreateDirectory(root);
|
||||
try
|
||||
{
|
||||
var file = Path.Combine(root, "store.msgpack");
|
||||
File.Copy(VectorPath("variant-v2.msgpack"), file);
|
||||
|
||||
using var withCodec = new CultCache(CultDocumentRegistry.Shared, CultCacheMessagePack.CreateCodec(CultDocumentRegistry.Shared));
|
||||
var named = Assert.Throws<InvalidOperationException>(() => withCodec.AddBackingStore(new SingleFileMessagePackBackingStore(file)))!;
|
||||
Assert.That(named.Message, Does.Contain("item:anvil-big").And.Contain("item:anvil"));
|
||||
|
||||
using var without = new CultCache();
|
||||
var codecless = Assert.Throws<InvalidOperationException>(() => without.AddBackingStore(new SingleFileMessagePackBackingStore(file)))!;
|
||||
Assert.That(codecless.Message, Does.Contain("item:anvil-big").And.Contain("codec"));
|
||||
}
|
||||
finally
|
||||
{
|
||||
if (Directory.Exists(root)) Directory.Delete(root, recursive: true);
|
||||
}
|
||||
}
|
||||
|
||||
[Test]
|
||||
public void SnapshotWithoutAFormatVersionIsRefusedNotDefaultedToV1()
|
||||
{
|
||||
// [nil, [], []]
|
||||
var bytes = new byte[] { 0x93, 0xc0, 0x90, 0x90 };
|
||||
|
||||
Assert.That(() => CultDocumentMessagePackSerialization.DeserializeSnapshot(bytes),
|
||||
Throws.TypeOf<NotSupportedException>().With.Message.Contains("format version"));
|
||||
}
|
||||
|
||||
[Test]
|
||||
public void V1StoreWrittenAtTheBaseCommitStillDecodesByteForByte()
|
||||
{
|
||||
var snapshot = CultDocumentMessagePackSerialization.DeserializeSnapshot(File.ReadAllBytes(VectorPath("v1-base.msgpack")));
|
||||
CultDocumentMessagePackSerialization.RequireSingleFileFormat(snapshot);
|
||||
|
||||
Assert.That(snapshot.FormatVersion, Is.EqualTo("cultcache.store.v1"));
|
||||
Assert.That(snapshot.Records.Select(record => record.Key), Is.EqualTo(new[] { "alpha", "beta" }));
|
||||
Assert.That(snapshot.Records[0].Payload, Is.EqualTo(new byte[] { 0x92, 0xa5, (byte)'a', (byte)'l', (byte)'p', (byte)'h', (byte)'a', 0x01 }));
|
||||
Assert.That(snapshot.Records[1].Payload, Is.EqualTo(new byte[] { 0x92, 0xa4, (byte)'b', (byte)'e', (byte)'t', (byte)'a', 0x02 }));
|
||||
}
|
||||
|
||||
// Format strings taken from DirectoryMessagePackBackingStore.cs at 0db1fe5.
|
||||
[TestCase("cultcache.store.v1")]
|
||||
[TestCase("cultcache.store.v1.directory")]
|
||||
|
|
|
|||
|
|
@ -439,6 +439,7 @@ namespace GameCult.Caching.Tests
|
|||
}
|
||||
|
||||
[Test]
|
||||
[Platform("Win", Reason = "Holds an open FileShare.Read handle and expects a delete or replace to fail; Linux unlink and rename ignore open handles.")]
|
||||
public void BatchIsAllOrNothingOnStoreFailure()
|
||||
{
|
||||
var registry = Registry();
|
||||
|
|
|
|||
1461
tests/GameCult.Caching.Tests/VariantTests.cs
Normal file
1461
tests/GameCult.Caching.Tests/VariantTests.cs
Normal file
File diff suppressed because it is too large
Load diff
284
tests/GameCult.Mesh.Tests/CultMeshContentVectorTests.cs
Normal file
284
tests/GameCult.Mesh.Tests/CultMeshContentVectorTests.cs
Normal file
|
|
@ -0,0 +1,284 @@
|
|||
using System;
|
||||
using System.Collections.Generic;
|
||||
using System.IO;
|
||||
using System.Linq;
|
||||
using System.Text.Json;
|
||||
using System.Threading.Tasks;
|
||||
using FluentAssertions;
|
||||
using GameCult.Caching;
|
||||
using GameCult.Networking;
|
||||
using MessagePack;
|
||||
using NUnit.Framework;
|
||||
|
||||
namespace GameCult.Mesh.Tests;
|
||||
|
||||
/// <summary>
|
||||
/// Content-plane parity vectors shared with <c>packages/cultnet-rs/tests/content.rs</c>. Each runtime
|
||||
/// writes its own file under <c>contracts/cultmesh</c> and judges both. The chunk answers in these
|
||||
/// files are produced by <see cref="CultMeshLegacyRudpContentServer"/> itself, so the failure
|
||||
/// spellings are the reference's own bytes.
|
||||
/// </summary>
|
||||
[TestFixture]
|
||||
public sealed class CultMeshContentVectorTests
|
||||
{
|
||||
private const int BodyLength = 1_315_551;
|
||||
private const int ChunkSize = 262_144;
|
||||
private const string CreatedAtUtc = "2026-09-22T00:00:00.0000000+00:00";
|
||||
private const string ArtifactId = "eureka/content-vector";
|
||||
|
||||
private sealed record Vector(string Label, string Kind, byte[] Bytes);
|
||||
|
||||
[Test]
|
||||
public void WriteContentVectors()
|
||||
{
|
||||
if (Environment.GetEnvironmentVariable("CULTNET_WRITE_VECTORS") != "1")
|
||||
Assert.Ignore("Set CULTNET_WRITE_VECTORS=1 to (re)write the committed vector file.");
|
||||
File.WriteAllText(VectorPath("content-vectors.cs-written.json"), ToJson(BuildVectors(out _, out _)));
|
||||
}
|
||||
|
||||
[Test]
|
||||
public void CommittedCsVectorsEqualAFreshEncode()
|
||||
{
|
||||
var fresh = BuildVectors(out _, out _);
|
||||
var committed = ReadVectors("content-vectors.cs-written.json");
|
||||
committed.Select(v => (v.Label, v.Kind)).Should().Equal(fresh.Select(v => (v.Label, v.Kind)));
|
||||
foreach (var (expected, actual) in fresh.Zip(committed))
|
||||
actual.Bytes.Should().Equal(expected.Bytes, $"vector '{actual.Label}' drifted from the reference's encode");
|
||||
}
|
||||
|
||||
[Test]
|
||||
public void RustVectorsDecodeInTheReference()
|
||||
{
|
||||
BuildVectors(out var cache, out var messages);
|
||||
var rust = ReadVectors("content-vectors.rs-written.json");
|
||||
rust.Should().NotBeEmpty();
|
||||
rust.Select(v => v.Label).Should().Equal(messages.Keys, "both runtimes write the same labelled vectors");
|
||||
foreach (var vector in rust)
|
||||
{
|
||||
var expected = messages[vector.Label];
|
||||
switch (vector.Kind)
|
||||
{
|
||||
case "request":
|
||||
var request = MessagePackSerializer.Deserialize<CultMeshContentChunkRequestMessage>(vector.Bytes, CultNetSchemaMessageSerialization.Options);
|
||||
request.Should().BeEquivalentTo((CultMeshContentChunkRequestMessage)expected);
|
||||
Reencode(request).Should().Equal(vector.Bytes, vector.Label);
|
||||
break;
|
||||
case "response":
|
||||
var response = MessagePackSerializer.Deserialize<CultMeshContentChunkResponseMessage>(vector.Bytes, CultNetSchemaMessageSerialization.Options);
|
||||
response.Should().BeEquivalentTo((CultMeshContentChunkResponseMessage)expected);
|
||||
Reencode(response).Should().Equal(vector.Bytes, vector.Label);
|
||||
break;
|
||||
case "manifest":
|
||||
var manifest = MessagePackSerializer.Deserialize<CultMeshCdnArtifactManifest>(vector.Bytes, CultNetSchemaMessageSerialization.Options);
|
||||
manifest.Should().BeEquivalentTo((CultMeshCdnArtifactManifest)expected);
|
||||
Reencode(manifest).Should().Equal(vector.Bytes, vector.Label);
|
||||
break;
|
||||
default:
|
||||
Assert.Fail($"unknown vector kind '{vector.Kind}'");
|
||||
break;
|
||||
}
|
||||
}
|
||||
|
||||
// Rust's answers to Rust's requests must be what the reference answers to the same bytes.
|
||||
foreach (var vector in rust.Where(v => v.Label.EndsWith(".request", StringComparison.Ordinal)))
|
||||
{
|
||||
var request = MessagePackSerializer.Deserialize<CultMeshContentChunkRequestMessage>(vector.Bytes, CultNetSchemaMessageSerialization.Options);
|
||||
var rustAnswer = rust.Single(v => v.Label == vector.Label[..^".request".Length] + ".response");
|
||||
Reencode(Answer(cache, request)).Should().Equal(rustAnswer.Bytes, vector.Label);
|
||||
}
|
||||
}
|
||||
|
||||
[Test]
|
||||
public void PackArtifactOfTheFixtureBodyEqualsTheFixtureManifest()
|
||||
{
|
||||
var artifact = CultMeshCdn.PackArtifact(ArtifactId, Body(), Options());
|
||||
var committed = ReadVectors("content-vectors.cs-written.json").Single(v => v.Label == "manifest");
|
||||
Reencode(artifact.Manifest).Should().Equal(committed.Bytes);
|
||||
var rust = ReadVectors("content-vectors.rs-written.json").Single(v => v.Label == "manifest");
|
||||
rust.Bytes.Should().Equal(committed.Bytes, "Rust's pack_content and the reference pack the same bytes to the same manifest");
|
||||
}
|
||||
|
||||
private static byte[] Body() =>
|
||||
Enumerable.Range(0, BodyLength).Select(i => (byte)(i % 251)).ToArray();
|
||||
|
||||
private static CultMeshCdnPackOptions Options() => new()
|
||||
{
|
||||
ChunkSizeBytes = ChunkSize,
|
||||
Version = "1",
|
||||
MimeType = "application/x-cultnet-vector",
|
||||
CreatedAtUtc = CreatedAtUtc
|
||||
};
|
||||
|
||||
private static byte[] Reencode(CultMeshContentChunkRequestMessage message) =>
|
||||
CultNetSchemaMessageSerialization.Serialize(message);
|
||||
|
||||
private static byte[] Reencode(CultMeshContentChunkResponseMessage message) =>
|
||||
CultNetSchemaMessageSerialization.Serialize(message);
|
||||
|
||||
private static byte[] Reencode(CultMeshCdnArtifactManifest manifest) =>
|
||||
MessagePackSerializer.Serialize(manifest, CultNetSchemaMessageSerialization.Options);
|
||||
|
||||
private static CultMeshContentChunkRequestMessage Request(string id, string hash, string key, int size) => new()
|
||||
{
|
||||
MessageId = id,
|
||||
ChunkHash = hash,
|
||||
RecordKey = key,
|
||||
ExpectedSizeBytes = size
|
||||
};
|
||||
|
||||
/// <summary>The cs-written file's vectors, in file order. Messages are keyed by label.</summary>
|
||||
private static List<Vector> BuildVectors(out CultCache cache, out Dictionary<string, object> messages)
|
||||
{
|
||||
var artifact = CultMeshCdn.PackArtifact(ArtifactId, Body(), Options());
|
||||
var content = new CultCache(CultMesh.CreateCultCacheDocumentRegistry(
|
||||
typeof(CultMeshCdnArtifactManifest), typeof(CultMeshCdnArtifactChunk)));
|
||||
CultMeshCdn.PublishAsync(content, artifact).GetAwaiter().GetResult();
|
||||
cache = content;
|
||||
|
||||
var last = artifact.Chunks[^1];
|
||||
var key = "mesh:cdn:chunk:" + last.ChunkHash;
|
||||
var lastDigit = last.ChunkHash[^1] == '0' ? '1' : '0';
|
||||
var vectors = new List<Vector>();
|
||||
var map = new Dictionary<string, object>(StringComparer.Ordinal);
|
||||
messages = map;
|
||||
|
||||
void AddRequest(string label, CultMeshContentChunkRequestMessage message)
|
||||
{
|
||||
map[label] = message;
|
||||
vectors.Add(new Vector(label, "request", Reencode(message)));
|
||||
}
|
||||
|
||||
void AddResponse(string label, CultMeshContentChunkResponseMessage message)
|
||||
{
|
||||
map[label] = message;
|
||||
vectors.Add(new Vector(label, "response", Reencode(message)));
|
||||
}
|
||||
|
||||
void AddAnswer(string name, CultMeshContentChunkRequestMessage request)
|
||||
{
|
||||
AddRequest(name + ".request", request);
|
||||
AddResponse(name + ".response", Answer(content, request));
|
||||
}
|
||||
|
||||
AddAnswer("answer_found", Request("vector-found", "SHA256:" + last.ChunkHash, key, last.SizeBytes));
|
||||
AddAnswer("answer_not_found", Request("vector-missing", new string('0', 64), string.Empty, 100));
|
||||
AddAnswer("answer_record_key_disagrees", Request("vector-key", last.ChunkHash, "mesh:cdn:chunk:other", last.SizeBytes));
|
||||
AddAnswer("answer_size_mismatch", Request("vector-size", last.ChunkHash, key, last.SizeBytes - 1));
|
||||
// Requests the reference refuses in its handler, never at deserialisation: each is answered.
|
||||
AddAnswer("answer_blank_message_id", Request(string.Empty, last.ChunkHash, key, last.SizeBytes));
|
||||
AddAnswer("answer_whitespace_message_id", Request(" ", last.ChunkHash, key, last.SizeBytes));
|
||||
AddAnswer("answer_blank_hash", Request("vector-blank-hash", string.Empty, string.Empty, 100));
|
||||
AddAnswer("answer_whitespace_hash", Request("vector-space-hash", " ", string.Empty, 100));
|
||||
AddAnswer("answer_prefix_only_hash", Request("vector-prefix-hash", "sha256: ", string.Empty, 100));
|
||||
AddAnswer("answer_negative_size", Request("vector-negative", last.ChunkHash, key, -1));
|
||||
AddAnswer("answer_record_key_case", Request("vector-key-case", last.ChunkHash, key.ToUpperInvariant(), last.SizeBytes));
|
||||
AddAnswer("answer_blank_record_key", Request("vector-key-blank", last.ChunkHash, " ", last.SizeBytes));
|
||||
AddAnswer("answer_double_prefix", Request("vector-double", "sha256:sha256:" + last.ChunkHash, string.Empty, last.SizeBytes));
|
||||
|
||||
// A caller that leaves a string null writes msgpack nil; the reference reads it back as null and
|
||||
// answers. These are judged by Rust decoding the reference's bytes (Rust never writes nil), so
|
||||
// they stay out of the label-matched mirror set.
|
||||
void AddNilAnswer(string name, CultMeshContentChunkRequestMessage request)
|
||||
{
|
||||
vectors.Add(new Vector(name + ".request", "request", Reencode(request)));
|
||||
vectors.Add(new Vector(name + ".response", "response", Reencode(Answer(content, request))));
|
||||
}
|
||||
|
||||
AddNilAnswer("nil_message_id", Request(null, last.ChunkHash, key, last.SizeBytes));
|
||||
AddNilAnswer("nil_hash", Request("vector-nil-hash", null, string.Empty, 100));
|
||||
AddNilAnswer("nil_record_key", Request("vector-nil-key", new string('0', 64), null, 100));
|
||||
AddResponse("response_hash_last_digit", new CultMeshContentChunkResponseMessage
|
||||
{
|
||||
MessageId = "vector-digit",
|
||||
Found = true,
|
||||
ChunkHash = last.ChunkHash[..^1] + lastDigit,
|
||||
SizeBytes = last.SizeBytes,
|
||||
Payload = last.Payload,
|
||||
Error = string.Empty
|
||||
});
|
||||
|
||||
void AddManifest(string label, CultMeshCdnArtifactManifest manifest)
|
||||
{
|
||||
map[label] = manifest;
|
||||
vectors.Add(new Vector(label, "manifest", Reencode(manifest)));
|
||||
}
|
||||
|
||||
AddManifest("manifest", artifact.Manifest);
|
||||
var shuffled = CultMeshCdn.PackArtifact(ArtifactId, Body(), Options()).Manifest;
|
||||
shuffled.Chunks = new[] { 3, 0, 5, 1, 4, 2 }.Select(i => shuffled.Chunks[i]).ToArray();
|
||||
AddManifest("manifest_out_of_order", shuffled);
|
||||
var tagged = CultMeshCdn.PackArtifact(ArtifactId, Body(), Options()).Manifest;
|
||||
tagged.Metadata = new Dictionary<string, string> { ["zeta"] = "1", ["alpha"] = "2", ["mid"] = "3" };
|
||||
AddManifest("manifest_metadata_order", tagged);
|
||||
AddManifest("manifest_empty_body", CultMeshCdn.PackArtifact(ArtifactId, Array.Empty<byte>(), Options()).Manifest);
|
||||
return vectors;
|
||||
}
|
||||
|
||||
private static CultMeshContentChunkResponseMessage Answer(CultCache cache, CultMeshContentChunkRequestMessage request)
|
||||
{
|
||||
var host = new ReferenceHost();
|
||||
using var server = new CultMeshLegacyRudpContentServer(host, cache);
|
||||
var peer = new ReferencePeer();
|
||||
host.Dispatch(request, peer).GetAwaiter().GetResult();
|
||||
return peer.Sent ?? throw new InvalidOperationException("The reference server answered with silence.");
|
||||
}
|
||||
|
||||
private sealed class ReferenceHost : ICultNetSchemaServer
|
||||
{
|
||||
private Func<CultMeshContentChunkRequestMessage, ICultNetSchemaServerPeer, Task>? _handler;
|
||||
|
||||
public void OnCultNet<TMessage>(Func<TMessage, ICultNetSchemaServerPeer, Task> callback)
|
||||
where TMessage : ICultNetSchemaMessage =>
|
||||
_handler = (Func<CultMeshContentChunkRequestMessage, ICultNetSchemaServerPeer, Task>)(object)callback;
|
||||
|
||||
public void RemoveCultNetMessageListener<TMessage>(Delegate callback)
|
||||
where TMessage : ICultNetSchemaMessage => _handler = null;
|
||||
|
||||
public Task Dispatch(CultMeshContentChunkRequestMessage request, ICultNetSchemaServerPeer peer) =>
|
||||
_handler!(request, peer);
|
||||
}
|
||||
|
||||
private sealed class ReferencePeer : ICultNetSchemaServerPeer
|
||||
{
|
||||
public CultMeshContentChunkResponseMessage? Sent { get; private set; }
|
||||
|
||||
public void SendCultNet<TMessage>(TMessage message) where TMessage : ICultNetSchemaMessage =>
|
||||
Sent = (CultMeshContentChunkResponseMessage)(object)message;
|
||||
}
|
||||
|
||||
private static string ToJson(List<Vector> vectors) => JsonSerializer.Serialize(
|
||||
new
|
||||
{
|
||||
vectors = vectors.Select(v => new
|
||||
{
|
||||
label = v.Label,
|
||||
kind = v.Kind,
|
||||
messagePackBase64 = Convert.ToBase64String(v.Bytes)
|
||||
})
|
||||
},
|
||||
new JsonSerializerOptions { WriteIndented = true });
|
||||
|
||||
private static List<Vector> ReadVectors(string name)
|
||||
{
|
||||
var path = VectorPath(name);
|
||||
if (!File.Exists(path))
|
||||
Assert.Inconclusive($"{path} is missing - write it first (CULTNET_WRITE_VECTORS=1).");
|
||||
using var document = JsonDocument.Parse(File.ReadAllText(path));
|
||||
return document.RootElement.GetProperty("vectors").EnumerateArray()
|
||||
.Select(v => new Vector(
|
||||
v.GetProperty("label").GetString()!,
|
||||
v.GetProperty("kind").GetString()!,
|
||||
Convert.FromBase64String(v.GetProperty("messagePackBase64").GetString()!)))
|
||||
.ToList();
|
||||
}
|
||||
|
||||
private static string VectorPath(string name) => Path.Combine(RepoRoot(), "contracts", "cultmesh", name);
|
||||
|
||||
private static string RepoRoot()
|
||||
{
|
||||
var directory = new DirectoryInfo(TestContext.CurrentContext.TestDirectory);
|
||||
while (directory != null && !File.Exists(Path.Combine(directory.FullName, "CultLib.sln")))
|
||||
directory = directory.Parent;
|
||||
return directory?.FullName ?? throw new InvalidOperationException("CultLib.sln was not found above the test directory.");
|
||||
}
|
||||
}
|
||||
60
tests/GameCult.Mesh.Tests/CultMeshVariantRefusalTests.cs
Normal file
60
tests/GameCult.Mesh.Tests/CultMeshVariantRefusalTests.cs
Normal file
|
|
@ -0,0 +1,60 @@
|
|||
using System;
|
||||
using System.IO;
|
||||
using FluentAssertions;
|
||||
using GameCult.Caching;
|
||||
using NUnit.Framework;
|
||||
|
||||
#nullable enable
|
||||
|
||||
namespace GameCult.Mesh.Tests;
|
||||
|
||||
// Shared refusal vectors: tests/vectors/document-variants-c0, read by every runtime's tests.
|
||||
public sealed class CultMeshVariantRefusalTests
|
||||
{
|
||||
private const string ItemSchemaId = "sha256:88d3fdf0a927acf3b163940d8f8c7fe62b3316542ce771a67ec8bc038f594788";
|
||||
|
||||
private static string VectorPath(string name)
|
||||
{
|
||||
for (var dir = new DirectoryInfo(TestContext.CurrentContext.TestDirectory); dir != null; dir = dir.Parent)
|
||||
{
|
||||
var candidate = Path.Combine(dir.FullName, "tests", "vectors", "document-variants-c0", name);
|
||||
if (File.Exists(candidate)) return candidate;
|
||||
}
|
||||
throw new FileNotFoundException($"Shared vector {name} not found above {TestContext.CurrentContext.TestDirectory}.");
|
||||
}
|
||||
|
||||
private static NotSupportedException Refusal(string vector) =>
|
||||
Assert.Throws<NotSupportedException>(() =>
|
||||
CultMesh.ReadSingleFileDocumentPayload(VectorPath(vector), new CultRecordKey("item:bellows"), ItemSchemaId))!;
|
||||
|
||||
[Test]
|
||||
public void ReadSingleFileDocument_RefusesUnknownHeaderByName() =>
|
||||
Refusal("unknown-header.msgpack").Message.Should().Contain("cultcache.store.v9");
|
||||
|
||||
[Test]
|
||||
public void ReadSingleFileDocument_RefusesExtraRecordSlotNamingTheRecord()
|
||||
{
|
||||
var message = Refusal("extra-slot-full-payload.msgpack").Message;
|
||||
message.Should().Contain("item:anvil").And.Contain(ItemSchemaId);
|
||||
}
|
||||
|
||||
[Test]
|
||||
public void ReadSingleFileDocument_RefusesExtraRecordSlotInTheLegacyCatalogLayoutToo()
|
||||
{
|
||||
var message = Refusal("legacy-catalog-extra-slot.msgpack").Message;
|
||||
message.Should().Contain("item:anvil").And.Contain(ItemSchemaId);
|
||||
}
|
||||
|
||||
// Q6: CultMesh does not resolve variants. It refuses a variant key naming it and its base, and still reads the plain
|
||||
// records of the same v2 store.
|
||||
[Test]
|
||||
public void ReadSingleFileDocument_RefusesAVariantKeyByNameButReadsItsPlainNeighbours()
|
||||
{
|
||||
var refusal = Assert.Throws<NotSupportedException>(() =>
|
||||
CultMesh.ReadSingleFileDocumentPayload(VectorPath("variant-v2.msgpack"), new CultRecordKey("item:anvil-big"), ItemSchemaId))!;
|
||||
refusal.Message.Should().Contain("item:anvil-big").And.Contain("item:anvil'");
|
||||
|
||||
CultMesh.ReadSingleFileDocumentPayload(VectorPath("variant-v2.msgpack"), new CultRecordKey("item:bellows"), ItemSchemaId)
|
||||
.Should().NotBeEmpty();
|
||||
}
|
||||
}
|
||||
|
|
@ -0,0 +1,470 @@
|
|||
#nullable enable
|
||||
using System;
|
||||
using System.Collections.Concurrent;
|
||||
using System.IO;
|
||||
using System.Linq;
|
||||
using System.Net;
|
||||
using System.Net.Sockets;
|
||||
using System.Reflection;
|
||||
using System.Threading;
|
||||
using System.Threading.Tasks;
|
||||
using GameCult.Caching;
|
||||
using GameCult.Caching.MessagePack;
|
||||
using MessagePack;
|
||||
using NUnit.Framework;
|
||||
|
||||
namespace GameCult.Networking.Tests
|
||||
{
|
||||
// Q6 (docs/document-variants-cut.md C1): CultNet carries no variant deltas yet, so building a row for one is refused
|
||||
// loudly, on the v1 selection path and on the v0 snapshot path alike.
|
||||
public sealed class CultNetDocumentRegistryVariantTests
|
||||
{
|
||||
private static readonly CultRecordKey BaseKey = new("variant-fixture-base");
|
||||
private static readonly CultRecordKey VariantKey = new("variant-fixture-big");
|
||||
|
||||
private static async Task<(CultCache Cache, CultNetDocumentRegistry Documents)> BuildFixtureAsync(bool withVariant)
|
||||
{
|
||||
var registry = CultDocumentRegistry.Shared;
|
||||
var cache = new CultCache(registry, CultCacheMessagePack.CreateCodec(registry));
|
||||
var documents = new CultNetDocumentRegistry(registry)
|
||||
.Register(CultNetDocumentBinding.ForDocument<VariantWireFixture>(registry));
|
||||
await cache.UpsertAsync(new VariantWireFixture { Name = "base", Power = 1 }, new CultRecordHandle<VariantWireFixture>(BaseKey));
|
||||
if (withVariant)
|
||||
await cache.UpsertVariantAsync(VariantKey, BaseKey, new[]
|
||||
{
|
||||
cache.Override<VariantWireFixture>(nameof(VariantWireFixture.Name), "big"),
|
||||
cache.Override<VariantWireFixture>(nameof(VariantWireFixture.Power), 9)
|
||||
});
|
||||
return (cache, documents);
|
||||
}
|
||||
|
||||
[Test]
|
||||
public async Task SelectionResponseRefusesAVariantRowNamingIt()
|
||||
{
|
||||
var (cache, documents) = await BuildFixtureAsync(withVariant: true);
|
||||
var selection = new CultNetSelection { Projection = CultNetSelectionProjections.Document };
|
||||
|
||||
var error = Assert.Throws<NotSupportedException>(() =>
|
||||
documents.CreateSelectionResponse(cache, "m1", selection, ordinalOf: (_, _) => 1, asOf: 1))!;
|
||||
|
||||
Assert.That(error.Message, Does.Contain(VariantKey.Value).And.Contain(BaseKey.Value));
|
||||
}
|
||||
|
||||
[Test]
|
||||
public async Task RawSnapshotResponseRefusesAVariantRowNamingIt()
|
||||
{
|
||||
var (cache, documents) = await BuildFixtureAsync(withVariant: true);
|
||||
|
||||
var error = Assert.Throws<NotSupportedException>(() => documents.CreateRawSnapshotResponse(cache, "m1"))!;
|
||||
|
||||
Assert.That(error.Message, Does.Contain(VariantKey.Value));
|
||||
}
|
||||
|
||||
[Test]
|
||||
public async Task ACacheWithoutVariantsStillAnswersBothPaths()
|
||||
{
|
||||
var (cache, documents) = await BuildFixtureAsync(withVariant: false);
|
||||
var selection = new CultNetSelection { Projection = CultNetSelectionProjections.Document };
|
||||
|
||||
Assert.That(documents.CreateSelectionResponse(cache, "m1", selection, ordinalOf: (_, _) => 1, asOf: 1).Documents, Has.Length.EqualTo(1));
|
||||
Assert.That(documents.CreateRawSnapshotResponse(cache, "m2").Documents, Has.Length.EqualTo(1));
|
||||
}
|
||||
|
||||
// The live-change funnel: a load that lands a variant reaches a subscriber as neither a record nor silence.
|
||||
[Test]
|
||||
public async Task ALoadThatLandsAVariantNeverReachesASubscriberAsARecordAndTheSubscriberIsToldByKey()
|
||||
{
|
||||
var registry = CultDocumentRegistry.Shared;
|
||||
var directory = Path.Combine(Path.GetTempPath(), $"cultlib-variant-live-{Guid.NewGuid():N}");
|
||||
Directory.CreateDirectory(directory);
|
||||
try
|
||||
{
|
||||
var path = Path.Combine(directory, "wire.cc");
|
||||
using (var writer = CultCacheMessagePack.Create(path, new CultCacheOpenOptions { Registry = registry }))
|
||||
{
|
||||
writer.Commit(batch => batch.Upsert(typeof(VariantWireFixture), new VariantWireFixture { Name = "base", Power = 1 }, BaseKey));
|
||||
writer.Commit(batch => batch.UpsertVariant(VariantKey, BaseKey, new[]
|
||||
{
|
||||
writer.Override<VariantWireFixture>(nameof(VariantWireFixture.Name), "big"),
|
||||
writer.Override<VariantWireFixture>(nameof(VariantWireFixture.Power), 9)
|
||||
}));
|
||||
}
|
||||
|
||||
var cache = new CultCache(registry, CultCacheMessagePack.CreateCodec(registry));
|
||||
var documents = new CultNetDocumentRegistry(registry)
|
||||
.Register(CultNetDocumentBinding.ForDocument<VariantWireFixture>(registry));
|
||||
var database = new CultNetDatabase(cache, new CultNetDatabaseOptions { DocumentRegistry = documents });
|
||||
var socket = new Socket(AddressFamily.InterNetwork, SocketType.Dgram, ProtocolType.Udp);
|
||||
socket.Bind(new IPEndPoint(IPAddress.Loopback, 0));
|
||||
socket.ReceiveTimeout = 20;
|
||||
using var server = new RudpCultNetSchemaServer(new RudpCultNetSchemaServerOptions
|
||||
{
|
||||
RuntimeId = "variant-live-server",
|
||||
Socket = socket
|
||||
});
|
||||
using var subscriptions = new CultNetDatabaseSubscriptionServer(server, database);
|
||||
using var cancellation = new CancellationTokenSource();
|
||||
var serverThread = new Thread(() =>
|
||||
{
|
||||
while (!cancellation.IsCancellationRequested)
|
||||
{
|
||||
_ = server.PollOnceAsync().GetAwaiter().GetResult();
|
||||
Thread.Sleep(1);
|
||||
}
|
||||
}) { IsBackground = true };
|
||||
serverThread.Start();
|
||||
try
|
||||
{
|
||||
using var client = CultNetSchemaClients.CreateRudp("variant-live-client");
|
||||
var snapshot = new TaskCompletionSource<bool>(TaskCreationOptions.RunContinuationsAsynchronously);
|
||||
var changes = new ConcurrentQueue<CultNetDatabaseChangeRawMessage>();
|
||||
var errors = new ConcurrentQueue<CultNetErrorMessage>();
|
||||
client.OnCultNet<CultNetSnapshotResponseRawMessage>(_ => snapshot.TrySetResult(true));
|
||||
client.OnCultNet<CultNetDatabaseChangeRawMessage>(changes.Enqueue);
|
||||
client.OnCultNet<CultNetErrorMessage>(errors.Enqueue);
|
||||
client.Connect("127.0.0.1", server.LocalEndPoint.Port);
|
||||
await WaitUntilAsync(() => client.Connected);
|
||||
client.SendCultNet(new CultNetDatabaseSubscribeMessage
|
||||
{
|
||||
MessageId = "subscribe-all",
|
||||
SubscriptionId = "all",
|
||||
RecordKeys = new[] { BaseKey.Value, VariantKey.Value },
|
||||
IncludeSnapshot = true
|
||||
});
|
||||
await WaitUntilAsync(() => snapshot.Task.IsCompleted);
|
||||
|
||||
cache.AddBackingStore(new SingleFileMessagePackBackingStore(path));
|
||||
|
||||
await WaitUntilAsync(() => !errors.IsEmpty || changes.Any(change => change.Document?.RecordKey == VariantKey.Value),
|
||||
() => $"changes={string.Join(",", changes.Select(c => c.ChangeKind + ":" + c.Document?.RecordKey))} errors={string.Join(",", errors.Select(e => e.Error))} cacheKeys={cache.GetStored(BaseKey) != null}/{cache.GetStored(VariantKey) != null}");
|
||||
await Task.Delay(200); // let anything else already in flight arrive
|
||||
|
||||
Assert.That(changes.Select(change => change.Document?.RecordKey), Does.Not.Contain(VariantKey.Value),
|
||||
"a variant must not reach a subscriber as a plain record");
|
||||
Assert.That(errors.Select(error => error.Error), Has.Some.Contains(VariantKey.Value),
|
||||
"the subscriber is told, naming the variant");
|
||||
}
|
||||
finally
|
||||
{
|
||||
cancellation.Cancel();
|
||||
serverThread.Join();
|
||||
}
|
||||
}
|
||||
finally
|
||||
{
|
||||
Directory.Delete(directory, recursive: true);
|
||||
}
|
||||
}
|
||||
|
||||
[Test]
|
||||
public async Task TheDatabaseServersLiveChangeForAVariantIsRefusedNamingIt()
|
||||
{
|
||||
var (cache, documents) = await BuildFixtureAsync(withVariant: true);
|
||||
var database = new CultNetDatabase(cache, new CultNetDatabaseOptions { DocumentRegistry = documents });
|
||||
using var server = new Server(cache, ServerSecurityOptions.Development());
|
||||
using var databaseServer = new CultNetDatabaseServer(server, database);
|
||||
var schemaId = cache.Registry.GetRequired<VariantWireFixture>().SchemaId;
|
||||
var change = new CultNetDatabaseChange<VariantWireFixture>(
|
||||
CultNetDatabaseChangeKind.Added,
|
||||
VariantKey,
|
||||
schemaId,
|
||||
database.Shards[0],
|
||||
cache.Get<VariantWireFixture>(VariantKey)!,
|
||||
previousDocument: null);
|
||||
var method = typeof(CultNetDatabaseServer).GetMethod("CreateChangeMessage", BindingFlags.Instance | BindingFlags.NonPublic)!;
|
||||
|
||||
var refused = Assert.Throws<TargetInvocationException>(() => method.Invoke(databaseServer, new object[]
|
||||
{
|
||||
change, "sub-1", new CultNetSelection { Projection = CultNetSelectionProjections.Document }
|
||||
}))!;
|
||||
|
||||
Assert.That(refused.InnerException, Is.TypeOf<NotSupportedException>());
|
||||
Assert.That(refused.InnerException!.Message, Does.Contain(VariantKey.Value).And.Contain(BaseKey.Value));
|
||||
}
|
||||
|
||||
|
||||
// A hop-bearing selection reconciles the whole store on every change. The refusal follows the selection: a subscriber
|
||||
// whose selection never selects the variant keeps receiving; one that does is told, as a typed error, not a silent stop.
|
||||
[Test]
|
||||
public async Task AHopBearingSubscriptionReconcilesPastAVariantItDoesNotSelectAndIsToldWhenItDoes()
|
||||
{
|
||||
var registry = CultDocumentRegistry.Shared;
|
||||
var cache = new CultCache(registry, CultCacheMessagePack.CreateCodec(registry));
|
||||
var documents = new CultNetDocumentRegistry(registry)
|
||||
.Register(CultNetDocumentBinding.ForDocument<VariantWireFixture>(registry))
|
||||
.Register(CultNetDocumentBinding.ForDocument<VariantCiterFixture>(registry));
|
||||
var wireSchemaId = registry.GetRequired<VariantWireFixture>().SchemaId;
|
||||
cache.Commit(batch =>
|
||||
{
|
||||
batch.Upsert(typeof(VariantWireFixture), new VariantWireFixture { Name = "base", Power = 1 }, BaseKey);
|
||||
batch.Upsert(typeof(VariantCiterFixture), Citer("citer-one", BaseKey), new CultRecordKey("citer-one"));
|
||||
});
|
||||
var database = new CultNetDatabase(cache, new CultNetDatabaseOptions { DocumentRegistry = documents });
|
||||
var socket = new Socket(AddressFamily.InterNetwork, SocketType.Dgram, ProtocolType.Udp);
|
||||
socket.Bind(new IPEndPoint(IPAddress.Loopback, 0));
|
||||
socket.ReceiveTimeout = 20;
|
||||
using var server = new RudpCultNetSchemaServer(new RudpCultNetSchemaServerOptions { RuntimeId = "variant-hop-server", Socket = socket });
|
||||
using var subscriptions = new CultNetDatabaseSubscriptionServer(server, database);
|
||||
using var cancellation = new CancellationTokenSource();
|
||||
var serverThread = new Thread(() =>
|
||||
{
|
||||
while (!cancellation.IsCancellationRequested)
|
||||
{
|
||||
_ = server.PollOnceAsync().GetAwaiter().GetResult();
|
||||
Thread.Sleep(1);
|
||||
}
|
||||
}) { IsBackground = true };
|
||||
serverThread.Start();
|
||||
try
|
||||
{
|
||||
using var client = CultNetSchemaClients.CreateRudp("variant-hop-client");
|
||||
var snapshots = new ConcurrentQueue<CultNetSnapshotResponseRawV1Message>();
|
||||
var changes = new ConcurrentQueue<CultNetDatabaseChangeRawMessage>();
|
||||
var errors = new ConcurrentQueue<CultNetErrorMessage>();
|
||||
client.OnCultNet<CultNetSnapshotResponseRawV1Message>(snapshots.Enqueue);
|
||||
client.OnCultNet<CultNetDatabaseChangeRawMessage>(changes.Enqueue);
|
||||
client.OnCultNet<CultNetErrorMessage>(errors.Enqueue);
|
||||
client.Connect("127.0.0.1", server.LocalEndPoint.Port);
|
||||
await WaitUntilAsync(() => client.Connected);
|
||||
string Diagnostic() =>
|
||||
$"changes={string.Join(",", changes.Select(c => c.SubscriptionId + ":" + c.ChangeKind + ":" + (c.Document?.RecordKey ?? c.RecordKey)))} " +
|
||||
$"errors={string.Join(",", errors.Select(e => e.Error))}";
|
||||
|
||||
// "citers": rows citing the base. It never selects the variant.
|
||||
client.SendCultNet(new CultNetDatabaseSubscribeV1Message
|
||||
{
|
||||
MessageId = "citers",
|
||||
SubscriptionId = "citers",
|
||||
IncludeSnapshot = true,
|
||||
Selection = new CultNetSelection
|
||||
{
|
||||
Cites = new CultNetCitation { Target = new CultNetRecordRef { SchemaId = wireSchemaId, RecordKey = BaseKey.Value }, Role = "Ref" }
|
||||
}
|
||||
});
|
||||
await WaitUntilAsync(() => snapshots.Count == 1, Diagnostic);
|
||||
|
||||
await database.PutAsync(new CultRecordKey("citer-two"), Citer("citer-two", BaseKey));
|
||||
await WaitUntilAsync(() => changes.Any(change => change.SubscriptionId == "citers" && change.Document?.RecordKey == "citer-two"), Diagnostic);
|
||||
|
||||
// With a variant in the store, the same subscriber keeps receiving.
|
||||
await cache.UpsertVariantAsync(VariantKey, BaseKey, new[]
|
||||
{
|
||||
cache.Override<VariantWireFixture>(nameof(VariantWireFixture.Name), "big")
|
||||
});
|
||||
await database.PutAsync(new CultRecordKey("citer-three"), Citer("citer-three", BaseKey));
|
||||
await WaitUntilAsync(() => changes.Any(change => change.SubscriptionId == "citers" && change.Document?.RecordKey == "citer-three"), Diagnostic);
|
||||
Assert.That(errors, Is.Empty, "a subscriber that never selects the variant is never told about it");
|
||||
|
||||
// "cited": wire rows some citer cites. Once a citer cites the variant, it selects it.
|
||||
client.SendCultNet(new CultNetDatabaseSubscribeV1Message
|
||||
{
|
||||
MessageId = "cited",
|
||||
SubscriptionId = "cited",
|
||||
IncludeSnapshot = true,
|
||||
Selection = new CultNetSelection
|
||||
{
|
||||
Schemas = new[] { wireSchemaId },
|
||||
Cited = new CultNetIncoming { Role = "Ref", Exists = true }
|
||||
}
|
||||
});
|
||||
await WaitUntilAsync(() => snapshots.Count == 2, Diagnostic);
|
||||
Assert.That(errors, Is.Empty, "only the base is cited yet");
|
||||
await database.PutAsync(new CultRecordKey("citer-four"), Citer("citer-four", VariantKey));
|
||||
|
||||
await WaitUntilAsync(() => errors.Any(error => error.Error.Contains(VariantKey.Value)), Diagnostic);
|
||||
var refusal = errors.First(error => error.Error.Contains(VariantKey.Value));
|
||||
Assert.That(refusal.Code, Is.EqualTo("variant_unsupported"));
|
||||
Assert.That(refusal.Details?.Value, Is.EqualTo("cited"), "the peer can tell which subscription ended");
|
||||
await WaitUntilAsync(() => changes.Any(change => change.SubscriptionId == "cited" && change.ChangeKind == "removed" && change.RecordKey == BaseKey.Value), Diagnostic);
|
||||
Assert.That(changes.Where(change => change.SubscriptionId == "cited").Select(change => change.Document?.RecordKey),
|
||||
Does.Not.Contain(VariantKey.Value), "a variant never reaches a subscriber as a record");
|
||||
|
||||
// The first subscriber is still alive after the refusal; the refused one is withdrawn, not told again per change.
|
||||
var told = errors.Count;
|
||||
await database.PutAsync(new CultRecordKey("citer-five"), Citer("citer-five", BaseKey));
|
||||
await WaitUntilAsync(() => changes.Any(change => change.SubscriptionId == "citers" && change.Document?.RecordKey == "citer-five"), Diagnostic);
|
||||
await Task.Delay(200);
|
||||
Assert.That(errors.Count, Is.EqualTo(told), "a refused subscription is withdrawn: one error, not one per store change");
|
||||
}
|
||||
finally
|
||||
{
|
||||
cancellation.Cancel();
|
||||
serverThread.Join();
|
||||
}
|
||||
}
|
||||
|
||||
// An edge carries its citer's reference payload, read from the citer's resolved document. A selection whose hop
|
||||
// reaches a variant citer is refused as a selection of a variant row is, though only the cited row is selected.
|
||||
private static async Task<(CultCache Cache, CultNetDocumentRegistry Documents, CultNetSelection Selection, CultRecordKey CiterVariant)> BuildCitedByVariantFixtureAsync()
|
||||
{
|
||||
var registry = CultDocumentRegistry.Shared;
|
||||
var cache = new CultCache(registry, CultCacheMessagePack.CreateCodec(registry));
|
||||
var documents = new CultNetDocumentRegistry(registry)
|
||||
.Register(CultNetDocumentBinding.ForDocument<VariantWireFixture>(registry))
|
||||
.Register(CultNetDocumentBinding.ForDocument<VariantCiterFixture>(registry));
|
||||
cache.Commit(batch =>
|
||||
{
|
||||
batch.Upsert(typeof(VariantWireFixture), new VariantWireFixture { Name = "base", Power = 1 }, BaseKey);
|
||||
batch.Upsert(typeof(VariantCiterFixture), Citer("citer-one", BaseKey), new CultRecordKey("citer-one"));
|
||||
});
|
||||
var citerVariant = new CultRecordKey("citer-variant");
|
||||
await cache.UpsertVariantAsync(citerVariant, new CultRecordKey("citer-one"), new[]
|
||||
{
|
||||
cache.Override<VariantCiterFixture>(nameof(VariantCiterFixture.Name), "citer variant")
|
||||
});
|
||||
var selection = new CultNetSelection
|
||||
{
|
||||
Schemas = new[] { cache.Registry.GetRequired<VariantWireFixture>().SchemaId },
|
||||
Cited = new CultNetIncoming { Role = "Ref", Exists = true },
|
||||
Projection = CultNetSelectionProjections.Document
|
||||
};
|
||||
return (cache, documents, selection, citerVariant);
|
||||
}
|
||||
|
||||
[Test]
|
||||
public async Task AHopEdgeWhoseCiterIsAVariantIsRefusedNamingItAndAStoreWithoutOneAnswers()
|
||||
{
|
||||
var (cache, documents, selection, citerVariant) = await BuildCitedByVariantFixtureAsync();
|
||||
|
||||
var error = Assert.Throws<NotSupportedException>(() =>
|
||||
documents.CreateSelectionResponse(cache, "m1", selection, ordinalOf: (_, _) => 1, asOf: 1))!;
|
||||
Assert.That(error.Message, Does.Contain(citerVariant.Value));
|
||||
|
||||
cache.Commit(batch => batch.Remove(citerVariant));
|
||||
var answered = documents.CreateSelectionResponse(cache, "m2", selection, ordinalOf: (_, _) => 1, asOf: 1);
|
||||
Assert.That(answered.Edges, Has.Length.EqualTo(1));
|
||||
Assert.That(answered.Edges![0].From.RecordKey, Is.EqualTo("citer-one"));
|
||||
}
|
||||
|
||||
[Test]
|
||||
public async Task AHopSubscriptionWhoseEdgeCiterIsAVariantIsRefusedOnceAndWithdrawn()
|
||||
{
|
||||
var (cache, documents, selection, citerVariant) = await BuildCitedByVariantFixtureAsync();
|
||||
var database = new CultNetDatabase(cache, new CultNetDatabaseOptions { DocumentRegistry = documents });
|
||||
var socket = new Socket(AddressFamily.InterNetwork, SocketType.Dgram, ProtocolType.Udp);
|
||||
socket.Bind(new IPEndPoint(IPAddress.Loopback, 0));
|
||||
socket.ReceiveTimeout = 20;
|
||||
using var server = new RudpCultNetSchemaServer(new RudpCultNetSchemaServerOptions { RuntimeId = "variant-edge-server", Socket = socket });
|
||||
using var subscriptions = new CultNetDatabaseSubscriptionServer(server, database);
|
||||
using var cancellation = new CancellationTokenSource();
|
||||
var serverThread = new Thread(() =>
|
||||
{
|
||||
while (!cancellation.IsCancellationRequested)
|
||||
{
|
||||
_ = server.PollOnceAsync().GetAwaiter().GetResult();
|
||||
Thread.Sleep(1);
|
||||
}
|
||||
}) { IsBackground = true };
|
||||
serverThread.Start();
|
||||
try
|
||||
{
|
||||
using var client = CultNetSchemaClients.CreateRudp("variant-edge-client");
|
||||
var snapshots = new ConcurrentQueue<CultNetSnapshotResponseRawV1Message>();
|
||||
var errors = new ConcurrentQueue<CultNetErrorMessage>();
|
||||
client.OnCultNet<CultNetSnapshotResponseRawV1Message>(snapshots.Enqueue);
|
||||
client.OnCultNet<CultNetErrorMessage>(errors.Enqueue);
|
||||
client.Connect("127.0.0.1", server.LocalEndPoint.Port);
|
||||
await WaitUntilAsync(() => client.Connected);
|
||||
|
||||
client.SendCultNet(new CultNetDatabaseSubscribeV1Message
|
||||
{
|
||||
MessageId = "edges",
|
||||
SubscriptionId = "edges",
|
||||
IncludeSnapshot = true,
|
||||
Selection = selection
|
||||
});
|
||||
await WaitUntilAsync(() => errors.Any(error => error.Error.Contains(citerVariant.Value)));
|
||||
Assert.That(snapshots, Is.Empty, "the snapshot's edges would carry the variant's resolved reference");
|
||||
Assert.That(errors, Has.Count.EqualTo(1));
|
||||
}
|
||||
finally
|
||||
{
|
||||
cancellation.Cancel();
|
||||
serverThread.Join();
|
||||
}
|
||||
}
|
||||
|
||||
private static CultNetDatabaseChangeRawMessage? Deliver(
|
||||
CultNetDatabaseServer server,
|
||||
object change,
|
||||
CultNetSelection selection,
|
||||
System.Collections.Generic.HashSet<string> refused,
|
||||
System.Collections.Generic.List<CultNetErrorMessage> errors)
|
||||
{
|
||||
var method = typeof(CultNetDatabaseServer).GetMethod("DeliverChange", BindingFlags.Instance | BindingFlags.NonPublic)!;
|
||||
return (CultNetDatabaseChangeRawMessage?)method.Invoke(server, new object[]
|
||||
{
|
||||
change, "sub", selection, refused, (Action<CultNetErrorMessage>)errors.Add
|
||||
});
|
||||
}
|
||||
|
||||
private static VariantCiterFixture Citer(string name, CultRecordKey target) =>
|
||||
new() { Name = name, Ref = new CultRecordRef<VariantWireFixture>(target) };
|
||||
|
||||
// A subscriber told a variant only as an error is not later told it was removed: it never held it.
|
||||
[Test]
|
||||
public async Task RemovingAVariantTheSubscriberWasOnlyToldAboutAsAnErrorSendsNoRemoval()
|
||||
{
|
||||
var (cache, documents) = await BuildFixtureAsync(withVariant: true);
|
||||
var database = new CultNetDatabase(cache, new CultNetDatabaseOptions { DocumentRegistry = documents });
|
||||
using var server = new Server(cache, ServerSecurityOptions.Development());
|
||||
using var databaseServer = new CultNetDatabaseServer(server, database);
|
||||
var schemaId = cache.Registry.GetRequired<VariantWireFixture>().SchemaId;
|
||||
var selection = new CultNetSelection { Projection = CultNetSelectionProjections.Document };
|
||||
var refused = new System.Collections.Generic.HashSet<string>();
|
||||
var errors = new System.Collections.Generic.List<CultNetErrorMessage>();
|
||||
|
||||
var added = new CultNetDatabaseChange<VariantWireFixture>(
|
||||
CultNetDatabaseChangeKind.Added, VariantKey, schemaId, database.Shards[0], cache.Get<VariantWireFixture>(VariantKey)!, previousDocument: null);
|
||||
Assert.That(Deliver(databaseServer, added, selection, refused, errors), Is.Null);
|
||||
Assert.That(errors, Has.Count.EqualTo(1));
|
||||
|
||||
var removed = new CultNetDatabaseChange<VariantWireFixture>(
|
||||
CultNetDatabaseChangeKind.Removed, VariantKey, schemaId, database.Shards[0], document: null, previousDocument: cache.Get<VariantWireFixture>(VariantKey)!);
|
||||
Assert.That(Deliver(databaseServer, removed, selection, refused, errors), Is.Null,
|
||||
"no removal for a key the subscriber never held as a record");
|
||||
|
||||
// A record it did hold is still told about.
|
||||
var baseRemoved = new CultNetDatabaseChange<VariantWireFixture>(
|
||||
CultNetDatabaseChangeKind.Removed, BaseKey, schemaId, database.Shards[0], document: null, previousDocument: cache.Get<VariantWireFixture>(BaseKey)!);
|
||||
Assert.That(Deliver(databaseServer, baseRemoved, selection, refused, errors)?.ChangeKind, Is.EqualTo("removed"));
|
||||
}
|
||||
|
||||
private static async Task WaitUntilAsync(Func<bool> condition, Func<string>? diagnostic = null)
|
||||
{
|
||||
var deadline = DateTimeOffset.UtcNow + TimeSpan.FromSeconds(5);
|
||||
while (!condition())
|
||||
{
|
||||
if (DateTimeOffset.UtcNow > deadline)
|
||||
Assert.Fail("Condition was not satisfied before timeout. " + diagnostic?.Invoke());
|
||||
await Task.Delay(5);
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
[CultDocument("variants.wire-fixture", "variants.wire-fixture.v1")]
|
||||
[MessagePackObject(AllowPrivate = true)]
|
||||
public sealed class VariantWireFixture
|
||||
{
|
||||
[Key(0)]
|
||||
[CultName]
|
||||
public string Name = string.Empty;
|
||||
|
||||
[Key(1)]
|
||||
public int Power;
|
||||
}
|
||||
|
||||
[CultDocument("variants.wire-citer-fixture", "variants.wire-citer-fixture.v1")]
|
||||
[MessagePackObject(AllowPrivate = true)]
|
||||
public sealed class VariantCiterFixture
|
||||
{
|
||||
[Key(0)]
|
||||
[CultName]
|
||||
public string Name = string.Empty;
|
||||
|
||||
[Key(1)]
|
||||
[CultReference(typeof(VariantWireFixture))]
|
||||
public CultRecordRef<VariantWireFixture> Ref;
|
||||
}
|
||||
}
|
||||
}
|
||||
3
tests/vectors/document-variants-c0/.gitattributes
vendored
Normal file
3
tests/vectors/document-variants-c0/.gitattributes
vendored
Normal file
|
|
@ -0,0 +1,3 @@
|
|||
# Refusal vectors are byte-exact; never convert line endings.
|
||||
* binary
|
||||
*.py text
|
||||
Binary file not shown.
43
tests/vectors/document-variants-c0/generate.py
Normal file
43
tests/vectors/document-variants-c0/generate.py
Normal file
|
|
@ -0,0 +1,43 @@
|
|||
"""Generates the shared C0 refusal vectors from the pre-Cut 2 v1 store (written before any
|
||||
variant code existed). Every runtime's tests read the committed bytes; nothing regenerates them
|
||||
at test time. Run: python generate.py (needs msgpack).
|
||||
|
||||
unknown-header.msgpack header cultcache.store.v9, otherwise the v1 store
|
||||
extra-slot-full-payload.msgpack v1 header, record item:anvil gains slot 4, payload stays full
|
||||
legacy-catalog-extra-slot.msgpack
|
||||
v1 header, catalog entry in the older layout (contentHash at slot
|
||||
5), so CultMesh's legacy snapshot reader takes it, plus the
|
||||
extra-slot record
|
||||
v1-base.msgpack NOT generated here: written once by the Python runtime at CultLib
|
||||
69a21bb (SingleFileMessagePackBackingStore.push of alpha and
|
||||
beta, type vectors.item, before any C0 code existed)
|
||||
variant-v2.msgpack the wire shape of a variant record, hand-built: header v2, record slot 4 =
|
||||
[baseKey, overrides[]], empty payload (override op Set = 0, path steps
|
||||
are [slot, elementId]). C1 does not write this store and refuses to load
|
||||
it: the variant resolves to its base's name (R6). It exercises readers
|
||||
that refuse a variant by version or record.
|
||||
"""
|
||||
import pathlib
|
||||
|
||||
import msgpack
|
||||
|
||||
here = pathlib.Path(__file__).resolve().parent
|
||||
source = here.parent.parent / "GameCult.Caching.Tests" / "Fixtures" / "pre-cut2" / "single-file-v1" / "store.msgpack"
|
||||
header, catalog, records = msgpack.unpackb(source.read_bytes(), raw=False)
|
||||
assert header == "cultcache.store.v1"
|
||||
anvil = records[0]
|
||||
assert anvil[0] == "item:anvil"
|
||||
|
||||
|
||||
def write(name, snapshot):
|
||||
(here / name).write_bytes(msgpack.packb(snapshot, use_bin_type=True))
|
||||
|
||||
|
||||
write("unknown-header.msgpack", ["cultcache.store.v9", catalog, records])
|
||||
write("extra-slot-full-payload.msgpack",
|
||||
[header, catalog, [anvil + [["item:bellows", []]]] + records[1:]])
|
||||
variant = ["item:anvil-big", anvil[1], anvil[2], b"", ["item:anvil", [[0, [[1, ""]], "", 99]]]]
|
||||
write("variant-v2.msgpack", ["cultcache.store.v2", catalog, records + [variant]])
|
||||
legacy_entry = [catalog[0][0], catalog[0][1], catalog[0][2], catalog[0][4], None, catalog[0][3], []]
|
||||
write("legacy-catalog-extra-slot.msgpack",
|
||||
[header, [legacy_entry], [anvil + [["item:bellows", []]]]])
|
||||
|
|
@ -0,0 +1 @@
|
|||
“²cultcache.store.v1‘—ÙGsha256:88d3fdf0a927acf3b163940d8f8c7fe62b3316542ce771a67ec8bc038f594788µfixtures.precut2.item¸fixtures.precut2.item.v1Úp{"schemaName":"fixtures.precut2.item","schemaVersion":"fixtures.precut2.item.v1","members":[{"slot":0,"name":"Name","type":"System.String","isReference":false,"many":false,"targetSchemaName":null,"indexAlias":null,"isName":true},{"slot":1,"name":"Count","type":"System.Int32","isReference":false,"many":false,"targetSchemaName":null,"indexAlias":null,"isName":false}]}ÀÙGsha256:dadf30bc920849ee89ed5d70cc73027070dd7571c5f878db1901f3abc459cc0c<30>‘•ªitem:anvilÙGsha256:88d3fdf0a927acf3b163940d8f8c7fe62b3316542ce771a67ec8bc038f594788Ù!2026-09-13T15:14:36.4032226+00:00Ä’¥anvil’¬item:bellows<77>
|
||||
BIN
tests/vectors/document-variants-c0/unknown-header.msgpack
Normal file
BIN
tests/vectors/document-variants-c0/unknown-header.msgpack
Normal file
Binary file not shown.
1
tests/vectors/document-variants-c0/v1-base.msgpack
Normal file
1
tests/vectors/document-variants-c0/v1-base.msgpack
Normal file
|
|
@ -0,0 +1 @@
|
|||
“²cultcache.store.v1‘—¬vectors.item¬vectors.item¯vectors.item.v1¬vectors.itemÙL{"schemaName":"vectors.item","schemaVersion":"vectors.item.v1","members":[]}‘¬vectors.item<65>’”¥alpha¬vectors.item¹2026-09-29T00:00:00+00:00Ä’¥alpha”¤beta¬vectors.item¹2026-09-29T00:00:01+00:00Ä’¤beta
|
||||
BIN
tests/vectors/document-variants-c0/variant-v2.msgpack
Normal file
BIN
tests/vectors/document-variants-c0/variant-v2.msgpack
Normal file
Binary file not shown.
3
tests/vectors/document-variants-c1/.gitattributes
vendored
Normal file
3
tests/vectors/document-variants-c1/.gitattributes
vendored
Normal file
|
|
@ -0,0 +1,3 @@
|
|||
# Refusal vectors are byte-exact; never convert line endings.
|
||||
* binary
|
||||
*.py text
|
||||
BIN
tests/vectors/document-variants-c1/variant-store.msgpack
Normal file
BIN
tests/vectors/document-variants-c1/variant-store.msgpack
Normal file
Binary file not shown.
Loading…
Reference in a new issue