diff --git a/design/architecture/microservices/game-session-service/runtime-and-data.md b/design/architecture/microservices/game-session-service/runtime-and-data.md index f260531c05..2dfc2de1aa 100644 --- a/design/architecture/microservices/game-session-service/runtime-and-data.md +++ b/design/architecture/microservices/game-session-service/runtime-and-data.md @@ -18,11 +18,11 @@ The sections below define the target-state runtime contract. Current implementat - **Local NEW current issuer membership:** `game_session_canonical_issuer_current_local_operation` references immutable local operations. Registration adds a reference, pending cleanup retains it, and exactly proven completed retirement removes it. Ordinary reads use this current set while original operations, reservations and completion receipts remain retained provenance; this adds no inventory or admission authority. The [Redis issuer-index contract](../../system-architecture-redis.md#issuer-active-binding-index) owns this boundary. -- **Issuer qualification limits:** these owners remain manually composed and unregistered. Their focused proofs do not establish operational source or incarnation custody, legacy recovery, production PKI, registration or activation. A separate admitting issuer acknowledgement, issuer barrier/`OPEN`, final CAS and admission remain outside this component boundary; the [Player Access tracker](../../../project-management/implementation-tracking/player-access-and-session.md#canonical-new-admission-components) owns detailed proof attribution and gaps. +- **Issuer qualification limits:** these owners remain manually composed and unregistered. Their focused proofs do not establish operational source or incarnation custody, legacy recovery, production PKI, registration or activation. The added readiness owner is manually composed and unregistered; it does not supply final session CAS or admission; the [Player Access tracker](../../../project-management/implementation-tracking/player-access-and-session.md#canonical-new-admission-components) owns detailed proof attribution and gaps. - **Local NEW account-member repair:** the unregistered owner prepares the original binding-local operation, performs one global account-member write and physical readback outside SQL, then accepts its exact acknowledgement in SQL. This supplies `ADD_OR_RETAIN` evidence only; the candidate remains provisional. Account-wide lifecycle writers, remaining index and region acknowledgements, and the guarded final admission CAS remain open. See [Session Behavior](../../system-architecture-session-behavior.md#global-account-active-binding-index) and [Player Access and Session](../../../project-management/implementation-tracking/player-access-and-session.md#canonical-new-admission-components). -- **Account-fence intent and CLOSED target preparation:** local sources persist account acquisition intent and cohort, tenant-to-gameplay-tag mapping, protected current observations, a one-key CLOSED installer/readback, and immutable per-target receipts. A receipt is historical AS-OF evidence; targets remain `REQUIRED`. Operational protected-incarnation authority, all-target `INSTALLED`, barrier `OPEN`, token release, final admitting CAS, and production admission remain unproved. See [Player Access and Session](../../../project-management/implementation-tracking/player-access-and-session.md#canonical-new-admission-components) for proof attribution and limits. +- **Account-fence intent and CLOSED target preparation:** local sources persist account acquisition intent and cohort, tenant-to-gameplay-tag mapping, protected current observations, a one-key CLOSED installer/readback, and immutable per-target receipts. A receipt is historical AS-OF evidence; targets remain `REQUIRED`. The unregistered INITIAL-only Account OPEN component does not complete account-wide acquisition or release. Operational protected-incarnation authority, all-target `INSTALLED`, token release, final admitting CAS and production admission remain unproved. See [Player Access and Session](../../../project-management/implementation-tracking/player-access-and-session.md#canonical-new-admission-components) for proof attribution and limits. - **Current first-party receiving boundary:** Game Session's prepared receiver verifies the Gateway-signed context and rechecks the canonical target and retained private-handle evidence. When that first-party context is present, bare `LOGIN` and `PLAY` return `FIRST_PARTY_AUTHORITY_UNAVAILABLE` before legacy Account authentication, Entity resolution, or gameplay binding effects. Recovery from registry loss still requires the persisted compact JWS to remain valid; registry loss does not extend its expiry. The public Gateway cookie path is currently denied and its gameplay-route readiness is `OUT_OF_SERVICE`; no first-party wire success or admission is claimed. Account context production, shared replay fencing, and dedicated Gateway key qualification remain open. diff --git a/design/architecture/system-architecture-redis.md b/design/architecture/system-architecture-redis.md index a3755e06ca..6d491d275f 100644 --- a/design/architecture/system-architecture-redis.md +++ b/design/architecture/system-architecture-redis.md @@ -473,6 +473,10 @@ The physical v2 HASH value above is a projection, not the installed anchor or an A pending initial candidate whose inventory snapshot became stale may be superseded only before any issuer anchor is installed. The owner serializes on the inventory clock and exact current control, preserves the original intent, cohort and all issued work, and captures a fresh immutable candidate with a distinct request and strictly advancing operation and coverage fences. An immutable supersession relation and the current-control change commit atomically. The replacement uses a strictly newer trusted layout version so previously issued physical work remains in its original Redis key domain; it does not overwrite, delete or acknowledge cleanup of those retained keys. Exact replay retains the same replacement, while a changed original, stale control or installed anchor refuses the operation. This is recovery of an uninstalled initial candidate, not authority to rotate an active layout or waive any new candidate's current source, complete-cohort, capacity, acknowledgement or admission checks. +Within the existing Game Session issuer inventory owner, initial tenant-local issuer barriers use a distinct typed live admission-control row. The immutable bootstrap intent, control row and installed anchor retain their original layout provenance; the live barrier epoch is independently owner-allocated and never interpreted as the bootstrap epoch. Installation requires the qualified anchor, exact current Account source, registered target and stable storage incarnation. Every ordinary preparation, pending initializer, issuer acknowledgement, barrier read and final consumer joins current live control in the same inventory, layout-control and admission-control lock order. Under that current authority, the owner persists one immutable initializer and its complete intended `OPEN` tuple before Redis work. Neither a missing key, an installed anchor alone nor Account's `NO_ACTIVE_ACCOUNT_WIDE_FLOW` state authorizes initialization. Pending initializers participate in the same serialized issuer intent/cutoff cohort as binding preparations: a concurrent intent blocks new initializers, captures every existing initializer, installs the required tenant-local cutoff barriers, and reaches declared `INSTALLED` only after its complete cohort qualifies. The initial one-key tenant-slot CAS refuses conflicting, residual, previously `CLOSED`, newer-epoch or reset state; it never reopens or overwrites a cutoff. Exact independent readback and a durable original-initializer receipt precede use, with current control, epoch, source and incarnation revalidated after the remote phase and again for an admitting issuer acknowledgement and final tenant-local CAS. No SQL transaction spans Redis. Lost replies and partial attempts retain the original initializer and stay non-admitting on uncertainty; they create no reset, recovery or activation authority. + +See the [implementation tracker](../project-management/implementation-tracking/player-access-and-session.md#canonical-new-admission-components) for current coverage, retained evidence and recovery proof gaps. + ### Recovery and Cutoff Scope Authority The permitted scope is part of the evidence contract, not an operator hint. A region- or tenant-scoped preserved-session parent may enumerate only its binding-local snapshot, repair the region-local and tenant-scoped families it owns, and validate a linked child result. It may not map an issuer layout, perform issuer Redis field or reservation-capacity repair, read back issuer partitions for coverage, publish an issuer-partition acknowledgement, or claim global account-index coverage from its narrow snapshot. An issuer-wide child or standalone issuer operation must use a complete authoritative issuer inventory. A standalone operation carries `parentRecoveryOperationId=NOT_APPLICABLE`, `parentLifecycle=NOT_APPLICABLE`, `parentOperationFence=NOT_APPLICABLE`, and `parentCoverageFence=NOT_APPLICABLE`, then uses its own `issuerCoverageOperationId`, `issuerCoverageOperationFence`, distinct `coverageFence`, later `coverageGeneration`, pinned layout, and all finite partitions. A linked child retains the exact parent tuple through its independent edge but does not nest under the parent maintenance lock; the parent owns that lock and the child owns only its operation and coverage fences. An account-wide operation may cover only the untagged account family from a complete account inventory and its own account coverage evidence; it cannot substitute for issuer coverage. A cluster recovery must rebuild or consume complete per-account and per-issuer coverage for the deployment rather than treating a local region, tenant, or aggregate snapshot as global proof. diff --git a/design/architecture/system-architecture-session-behavior.md b/design/architecture/system-architecture-session-behavior.md index c7e673ea42..5f04e3e3cf 100644 --- a/design/architecture/system-architecture-session-behavior.md +++ b/design/architecture/system-architecture-session-behavior.md @@ -185,7 +185,7 @@ Target-state Game Session must also maintain bounded authoritative secondary ind Index contract requirements: - In target state, Game Session is the sole writer for all six index families; Account authority and realm-grant state remain the authorization source, not the indexes. -- The shard-local CAS/update flow mutates exactly the gameplay session record plus the four tenant-scoped indexes: character, account-tenant, tenant, and realm-grant. The final binding CAS additionally reads the exact account-admission barrier as a checked key and never writes it; the separate one-key CLOSED installer owns that mutation. All of these keys share `{tenantGameplayTag}`. The initial CAS publishes only the provisional candidate; the final follow-up CAS is the atomic controller boundary for takeover, resume, and tenant/grant-binding decisions inside Redis Cluster, and exact-compares the provisional generation, Account-owned exact-binding admission lease identity, monotonic lease fence, applicable authority cutoff checkpoint, and required follow-up acknowledgements. +- The shard-local CAS/update flow mutates the gameplay session record plus every applicable tenant-scoped index. Public-production and realm-unscoped bindings use character, account-tenant and tenant indexes; a grant-gated binding additionally uses its real Account-owned `grant/v1` realm-grant index. The final binding CAS also reads the exact account-admission and issuer-admission barriers as checked keys and never writes either barrier. The closed key set therefore contains six keys for public-production or realm-unscoped bindings and seven for grant-gated bindings, all sharing `{tenantGameplayTag}`. The owner selects that set from validated realm scope and rejects an inapplicable or missing key; a fabricated grant or sentinel key is not permitted. The initial CAS publishes only the typed non-admitting provisional candidate; the final follow-up CAS is the atomic controller boundary for takeover, resume, and tenant/grant-binding decisions inside Redis Cluster, and exact-compares the provisional generation, Account-owned exact-binding admission lease identity, monotonic lease fence, applicable authority cutoff checkpoint, and required follow-up acknowledgements. - The cross-tenant `session:game:index:account:` and issuer-partition indexes are explicitly excluded from that shard-local CAS because they span tenant hash slots or issuer partitions. The untagged account key is also excluded from every tenant-local Lua invocation. Before the tenant-scoped CAS publishes a new binding, Game Session durably commits deterministic account-index and issuer-index repair obligations keyed to that binding transition. The account obligation contains the expected prior generation, candidate `bindingGeneration`, unique transition identity, desired add/remove, and `accountIndexFence`; the issuer obligation also carries its exact reservation identity. The shard-local CAS may publish only a provisional binding with each applicable `accountIndexState=REPAIR_REQUIRED` and `issuerIndexState=REPAIR_REQUIRED`; it is not admissible for gameplay, resume, or takeover. Game Session then performs each separate idempotent single-key index/capacity compare-and-set, reads back the exact generation/fence-qualified member and reservation state, and durably acknowledges each matching account/issuer obligation. The region-lease bridge is another ordered, separately acknowledged follow-up using the validated binding generation and region epoch. Only after all required account, issuer, and region acknowledgements does the final follow-up shard-local CAS exact-compare the provisional generation, set the applicable states to `ACKNOWLEDGED`, and admit the binding at the controller linearization point. This ordered protocol closes the cross-slot and region-bridge crash windows without claiming a cross-store transaction. - An issuer-index write or removal atomically compares the complete expected physical v2 value, including its anchor tuple, the independently preserved original reservation coverage tuple, and local member-operation and control/incarnation evidence, before changing the hash field. The operation also compares the exact original reservation owner, transition, partition/layout, lifecycle, reservation fence and revision; the original reservation tuple is not reconstructed from or required to equal the anchor tuple. For bootstrap, the owner must prove that the original reservation belongs to the frozen complete cohort and is linked to the exact bootstrap operation and fences. An identical already-applied value is an idempotent success, while a newer or conflicting value is a repair conflict. At the start of an issuer cutoff or recovery, Game Session captures the active layout pointer's version, partition count, and capacity while establishing the operation and coverage fences, then reads exactly that pinned finite partition range and maps every binding through the canonical mapping helper; it does not reread the pointer and mix layouts during the operation. If the pointer no longer matches before acknowledgement, the current operation fails closed or enters the explicit layout-transition workflow, which accounts for the complete pinned old layout and separately built new layout before cutover; neither workflow evaluates a mixed partition set. The operation validates every returned value and reservation, then fences or terminates the referenced bindings through their ordinary binding CAS. Missing Redis responses, unreadable partitions, unresolved reservations or repair obligations, or conflicting field values are unavailable or ambiguous coverage, never an empty result. Recovery rebuilds each partition from the complete durable active-binding and reservation inventory using the same expected-value compare-and-set, canonical mapping, and capacity rules and clears the repair obligation only after every required partition, reservation, and binding acknowledgement is proven. - An issuer-partition acknowledgement is a durable evidence object, not an aggregate flag. For preserved region/tenant recovery it must carry the child-owned `issuerCoverageOperationId` and child lifecycle, the child `issuerCoverageOperationFence`, distinct issuer-wide `coverageFence`, `coverageGeneration`, issuer-wide `inventorySnapshotRevision`, pinned `issuerIndexLayoutVersion`, pinned partition count and capacity, `partitionId`, the exact `issuer/` cutoff checkpoint (`issuerAuthGeneration`, `issuanceFence`, and complete applicable `outboxCheckpoints`), every reservation identity with its owner, transition, lifecycle, fence, and inventory revision, and the capacity tuple `{partitionId, reservationCount, partitionCapacity, aggregateReservationCount, aggregateCapacity}`. The independent parent edge and the parent's consumption record carry the exact linked `parentRecoveryOperationId`, both current lifecycles, parent `operationFence`, distinct `parentCoverageFence`, resolved issuer/scope, and link revision; the child request/digest, transition, partition and reservation readback, acknowledgement, and immutable child result are parent-independent. `coverageGeneration=NOT_YET_ISSUED` remains the pre-coverage value and becomes concrete only after complete finite coverage is proven. For a standalone issuer-wide operation, the operation identity is its own issuer coverage operation identity and still carries its own maintenance fence and coverage fence; all parent fields and account-wide fields are the exact `NOT_APPLICABLE` marker plus `NO_ACTIVE_ACCOUNT_WIDE_FLOW`. The acknowledgement is valid only when all of that evidence comes from the same complete issuer-wide snapshot and operation attempt, with exact readback of the partition and reservation state. Cross-snapshot, cross-attempt, narrow-scope, stale-layout, changed-cutoff, mixed-partition, missing-reservation, or partial-capacity evidence is rejected; no acknowledgement may be assembled from separately read responses or used to authorize a different operation or layout. @@ -247,6 +247,8 @@ Account-control acquisition and per-tenant barrier installation are a separate a The account-qualified barrier key is `session:game:account-admission:{tenantGameplayTag}::`. Its persistent hash has exactly nine fields: `schema=gs_account_admission_barrier/v1`, `accountId`, `tenantId`, `playableStateNamespaceId`, `tenantGameplayTag`, `ownerOperationId`, `ownerFenceEpoch`, `incarnationDigest`, and `state`. Epochs are canonical decimal strings compared without floating-point conversion. A `CLOSED` acquisition uses a positive epoch; the positively established initial no-active control epoch may be zero, so the first acquisition may close a prior `OPEN` epoch `0` at epoch `1`. Zero never stands for a missing control row. A missing key may be created `CLOSED` only under the current original intent. An older well-formed barrier may advance only under a newer epoch and a different owner operation; equal epoch permits only exact same-operation, same-incarnation `CLOSED` replay. Malformed, expiring, foreign-scope, equal-conflicting, or newer barriers are refused without mutation. This key shares the tenant gameplay slot with the final session CAS; the global account index is never a member of that Lua invocation. A `CLOSED` write or a key-builder result grants no opening or admission authority. +An INITIAL-only `OPEN` install requires a positively present SQL `NO_ACTIVE_ACCOUNT_WIDE_FLOW` source and uses its exact nonnegative control epoch, including zero when established by that owner. SQL control is not Account identity, membership, token or storage-incarnation authority. The existing inventory-clock-to-Account-control serialization retains one original initializer for the exact account, tenant and playable-state namespace target, complete source tuple and protected incarnation. Pending initializers are part of the next acquisition's frozen cohort and target derivation; the racing initializer is included or refused when the intent wins. Before any create attempt, SQL durably records that dispatch may have occurred. Only the original never-installed target may be created `OPEN`, followed by independent exact physical readback, protected observations and guarded SQL completion against current control. Retry of an existing original `OPEN` is read-only; missing storage after possible dispatch or completed installation is reset or uncertainty, never permission to recreate. A previously `CLOSED` target cannot reopen under this arm, and a newer cutoff wins. No SQL transaction spans Redis or protected-source calls. The final session CAS still requires both exact current `OPEN` barriers, original Account commit and all account, issuer and region acknowledgements. + The stable `incarnationDigest` is SHA-256 over strict canonical JSON for the protected attestor binding, accepted canonical attestation digest, complete `targetDeploymentEvidence/v1` tuple (including deployment, Redis build, Lua registry, boot/startup and storage/AOF generations), and separately observed ACL and Redis-configuration digests. Fresh current-observation nonces, observation times, operation context, and signing-key identifiers do not change that stable storage binding. Each signed bounded current observation must bind the fresh receiver nonce and time window to the original account operation/fence, frozen cohort and exact tenant/namespace target, and must match the fixed trusted deployment expectation. The operational accepted-attestation/current-proof source is not supplied by the local controlled-signature fixture, so that fixture proves verifier mechanics only, not production custody or reset continuity. A retained barrier with the same operation and epoch but a changed stable incarnation is a conflict even after a fresh protected observation; it cannot be rewritten in place by an exact retry. Game Session’s account-wide fenced recovery owner must resolve replacement under the [canonical reset and recovery boundary](./system-architecture-redis-reset-and-recovery.md#canonical-reset-sequence-boundary), preserving the original intent and historical evidence while the affected target stays closed and unresolved. The local CLOSED installer does not supply that recovery; see the [implementation gap](../project-management/implementation-tracking/player-access-and-session.md#canonical-new-admission-components). diff --git a/design/project-management/ai-observations.md b/design/project-management/ai-observations.md index f217c5bdf4..ec697f79c4 100644 --- a/design/project-management/ai-observations.md +++ b/design/project-management/ai-observations.md @@ -454,6 +454,21 @@ Entry format: - Outcome: full Entity R722 executes 584 methods, with 519 passing, 46 failing on a missing placeholder in the new historical INSERT and 19 failing on separate PostgreSQL connection setup. R723 corrects only that placeholder and passes all 65 affected native cases with no skips; the 454 unit methods and other 65 native cases retain their R722 passing attribution. Enabled affected static analysis and formatting pass. The failed full-check aggregate remains recorded; the focused recovery does not relabel it as green. - Expected pattern: retain the exact pre-upgrade schema, source rows and history in migration proof. Use explicitly historical fixture input when current Java requires a later schema; do not add production compatibility branches or backfill authority merely to seed a test. +- `2026-10-27`: A running test task can conceal an already recorded failure + - Context: #3315 Game Session job `121874695249` first logged a bootstrap assertion failure at 11:28 NZDT but remained running until 11:53 NZDT; Gradle Checks took about 50 minutes. The shared observer reported the actual terminal failure, but the job conclusion could not expose the earlier assertion. + - Observation: Monitoring completed job conclusions prevents missed failures but does not provide early feedback while a long test task continues after its first failure. This is distinct from the earlier active-job-filter observer bug. + - Expected pattern: Keep scoped local migration and shared-fixture proof ahead of publication. If these delays recur, assess bounded test grouping or failure reporting in the existing CI runner against the loss of full failure diagnostics; do not treat a running job as green or retrigger it merely for a faster status. + +- `2026-10-27`: A global WAL insert fence can outlive quiet-server flush progress + - Context: #2972 R763 passed 23 of 25 native cases; actual bound issuance and a populated historical receipt upgrade refused durability because the captured global insert position remained 56 bytes beyond flush. The exact record type is unknown. + - Observation: PostgreSQL background WAL flushing considers full pages and asynchronous transaction work; an unrelated partial-page tail need not advance during a bounded read. Raising a polling count or lowering the proof fence would not establish the required durability. + - Qualified recovery: retain the SQL-issued snapshot and exact upper fence in a private pending capability, finish its capture transaction, then explicitly observe flush coverage of that same fence outside SQL locks and independently compare the original immutable receipt. No reader COMMIT authenticates the original clock, and no marker, forced flush or replacement timing is introduced. R766 passes all 26 selected PostgreSQL/Redis cases, including quiet-server frozen-fence coverage, unchanged retained migration rows and lost-confirmation recovery; the previous failed aggregates remain recorded. + +- `2026-10-27`: Apply the existing Flyway frontier check before publishing receiving migrations + - Context: #3320 CI job `121922001160` rejected new Account V161/V162 below the effective parent frontier V1011. The prior 2026-10-15 observation already described this service/shared-history ordering risk; the local receiving checks omitted `checkFlywayVersions` against the exact PR parent. + - Consequence and correction: fresh-schema tests passed while the proposed migration order was unsuitable for an existing parent deployment. Move only these new, unapplied migrations to V1012/V1013, preserve all parent migration names/checksums, and prove populated upgrade plus the canonical frontier check against the published parent. No out-of-order execution or host change is authorized. + - Outcome: R768 passes the actual-parent frontier guard, jOOQ generation and all 26 selected PostgreSQL/Redis cases with the V1012→V1013 upgrade; integration static/format and documentation checks pass, and all five observed containers are independently absent. Replacement hosted CI is still required. + - `2026-10-27`: Completed Hosted publication remained in native provider wait - Context: #3310 Hosted5 completed on the exact requested head at 16:32:58 NZDT, but the original FireController operation still reported `active / provider_wait / trigger_recovered` after the completed publication was visible. - Observation: the status did not expose the completed review or a capture failure. A bounded provider inspection found review 5661910348 and its six actionable comments; FireController's owner confirmed that the retained capture already contained the publication and began checking parser/attribution. The source completion mismatch delayed consuming the findings. @@ -462,10 +477,29 @@ Entry format: - Recovery: FireController identified six separately fingerprinted findings grouped into five comment containers. Parser fix `8f6e6121` recovered the same original attempt and all six exact findings; Gameplay verified the pinned head/base and finalized their native decisions. No trigger, allowance or controls changed. Full required controller CI was still pending at its owner's recovery handoff; native/race and packaged checks had passed. -- `2026-10-29`: Abbreviated source-refresh IDs returned unrelated advice - - Context: Source-refresh IDs missing the `review_refresh_` prefix returned unrelated startup-binding advice. The original full receipt IDs recovered the existing observations without another fetch. - - Observation: FireController owner reports client-only fix `18cf3b4d` now identifies `refresh_id`, its required prefix/format and retained-receipt recovery; an existing MCP process keeps its prior binary until normal reconnection. - - Expected pattern: Preserve exact full handles in delegation messages rather than abbreviating tool arguments. +- `2026-10-29`: Quiet native proof and JVM process matching need distinct evidence. The full 256-cycle issuer retirement regression produced no fresh integration XML or Gradle log output for many minutes while its owned PostgreSQL commits continued; it ultimately passed with the other selected Game Session cases. A generic process-name filter also falsely suggested the executor had exited because the process name was `java`. Confirm exact owned PIDs and use a read-only thread dump or run-owned database progress before diagnosing a hang or disappearance. A quiet task, an absent grep match and old XML establish neither failure nor success; preserve the eventual terminal result and fresh reports. + +- `2026-10-29`: A new provider summary section blocked an otherwise attributed Hosted capture. CodeRabbit returned an inline finding plus an explicitly unverified finding under “Additional comments”; FireController rejected the unfamiliar inventory format instead of inventing an empty review. The original attempt and comparison remain held while its independent owner adds bounded decoding and recovers the same capture. Do not repost, spend another allowance or treat provider acknowledgement as zero findings; recovery is still pending at this checkpoint. + +- 2026-10-29: Follow-up to the retained Hosted additional-comment capture issue: FireController recovered the same original attempt after updating its summary parser; both findings were independently adjudicated without a replacement trigger or allowance reset. Existing MCP sessions did not understand the new source kind, so the release-matched worker-bound CLI supplied the evidence until host reconnection. + +- 2026-10-29: A local tracker conflict edit failed its preservation assertion, but subsequent shell lines still staged and committed the unresolved text. Canonical documentation checks failed before publication. Preserve each side explicitly, verify conflict markers are absent, and make dependent staging/commit commands fail with the edit (for example checked subprocess calls); do not assume newline-separated shell commands stop on failure. The local follow-up correction preserves both proof histories and is rechecked before pushing. + +## 2026-10-29 — Hosted completion parsing and capture diagnostics + +Gameplay #3310 Hosted7 finished at 03:51:18 NZDT but its native evidence was recorded at 04:30:37, a 39-minute 19-second capture delay. FireController identified an optional `review_info_content` marker that broke standing-result parsing and unrelated CI-bot edits that masked the useful capture diagnostic. The owner deployed parser/diagnostic regression fixes in `2f1e5da5` and recovered the original zero-finding evidence without another trigger or spent reservation. Retain optional-marker and unrelated-comment cases in completion recovery tests; provider check success alone cannot establish a zero-finding native review. + +- `2026-10-29`: Check owner reachability before adjudicating a schema-level review claim + - Context: #3320 CLI reported that a later issuer cutoff could strand an older CLOSED barrier because the SQL operation schema permits positive prior epochs. + - Observation: Gameplay initially accepted and escalated that claim before reading the actual owner. `beginCutoff` already requires current OPEN control and the original anchor-install operation, rejecting INSTALLED before allocation. The source claim was corrected in native review history and the unnecessary decision request withdrawn. + - Expected pattern: Verify the concrete owner guards and supported lifecycle before accepting a finding or escalating a design choice; a table admitting a representation does not establish a reachable supported transition. Preserve the original adjudication audit and correction without expanding fail-closed behavior. + +- `2026-10-29`: Tracker proof-cell links need the architecture contract check + - Context: #3320 added production/test anchors and a link from a capability proof cell to its own proof-summary paragraph. + - Observation: links and Markdown passed locally, but CI architecture-doc-contracts rejected the proof-cell documentation path; that column permits executable tests or canonical validation/smoke tooling. The test links were valid and remain retained. + - Expected pattern: run the existing architecture-doc-contracts check when changing capability anchors; keep summary/gap links outside proof cells and retain direct executable proof links inside them. This is a selection correction, not a new validation tool. + +- `2026-10-29`: Malformed source-refresh IDs missing the `review_refresh_` prefix returned unrelated startup-binding advice. The original full receipt IDs recovered the existing observations without another fetch. FireController owner reports client-only fix `18cf3b4d` now identifies `refresh_id`, its required prefix/format and retained-receipt recovery; an existing MCP process keeps its prior binary until normal reconnection. Preserve exact full handles in delegation messages rather than abbreviating tool arguments. - `2026-10-29`: Shared static Testcontainers blocked the retirement suite - Context: The split issuer capacity/retirement proof shared static Testcontainers objects in an abstract fixture across two independently managed test classes. diff --git a/design/project-management/implementation-tracking/player-access-and-session.md b/design/project-management/implementation-tracking/player-access-and-session.md index e8a465aed9..d0fa5d3fff 100644 --- a/design/project-management/implementation-tracking/player-access-and-session.md +++ b/design/project-management/implementation-tracking/player-access-and-session.md @@ -24,6 +24,14 @@ Ordinary NEW exact retry now reconstructs the original durable local issuer oper The current local review corrections permit ordinary NEW only after proving the complete retained supersession chain ends at exact installed control. Forward V1038.4 retains prior partition heads and mutation receipts while separating their bootstrap lineages. Local physical projection batches source reads for its target partition, retains issuer-wide capacity/accounting checks on every snapshot, and fences target-partition changes independently of unrelated partition progress. R862 freshly passes all 20 selected PostgreSQL/Redis cases, including real retained-work supersession through installation and ordinary NEW, populated forward-migration retention, unrelated-partition progress and same-partition currentness refusal. Its aggregate fails two new test-only nullable-read warnings. R863 subsequently passes all 21 selected cases and the affected enabled main/integration static, migration-frontier, jOOQ generation, formatting and documentation checks after those warnings are corrected. This recovery also proves exact retained-abort retry comparison and ADD-mutation batch reads bounded to unretired local operations. The earlier failed R862 aggregate remains retained. Earlier results below retain their original source attribution. +The receiving #3320 prerequisite contains unregistered issuer LIVE control, tenant-local issuer OPEN/cutoff owners and the separate binding-local issuer acknowledgement, together with INITIAL-only Account OPEN initialization. Ordinary binding preparation and issuer projection join current live issuer control; pending Account initializers are included in the acquisition cohort, and both barrier owners retain original dispatch and exact readback evidence without reopening uncertain or CLOSED targets. The INITIAL Account arm retains one original initializer per account, tenant and playable-state namespace even when the original LOGIN is abandoned before dispatch. A later LOGIN cannot retarget that retained `NEVER_DISPATCHED` initializer or allocate a replacement through this arm; absence of Redis work does not grant new initialization authority. Account-wide fenced recovery and settlement are not supplied here, so recovery of that scope remains unqualified and non-admitting. R902 freshly passes 55 selected cases: 14 Game Session units, 30 physical Game Session cases and 11 actual Account–Game Session abort/migration compositions, with affected enabled main/unit/integration static analysis, formatting and documentation checks. Prepared issuer reads no longer consume creation authority; each owner validates its local script inputs before its durable one-shot claim. Proof covers retained preclaim failure and valid retry, competing claims with one winner, lost-claim absence refusal, cutoffs before and after a claim, abandoned INITIAL retention, and PostgreSQL-observed inventory/control serialization in both arrival orders. The claims still commit before the remote attempt, so postclaim interruption remains non-admitting uncertainty without rearming or automatic recovery. This is focused component/composition proof with controlled upstream source and test PKI inputs, not a complete service-suite or production-admission result. This readiness boundary does not contain original-NEW candidate installation, Account bound credential/handle issuance, the final controller CAS, committed Game Session result reader or whole-flow coordinator; those remain dependent preparation and final-admission work. Extraction receiving proof R849 passes 75 of 76 selected unit/native cases, including the full 256-cycle physical-retirement case; its aggregate remains failed because the historical Account fixture opened V1038 while invoking current issuer readiness. R855 then passes both the corrected current authenticated-owner composition and a separate populated V1038→V1038.1 migration-retention proof. Its aggregate failed only an unused private fixture overload; R856 passes affected Account static, formatting and documentation checks after removing that overload. The migration fixture uses controlled historical terminal rows, while the current composition independently proves real owner calls. Earlier component evidence below retains its original source attribution; this is focused receiving proof, not a complete service-suite or public admission result. R867 subsequently passes 23 current-parent receiving cases, including latest-schema issuer OPEN composition, controlled predecessor mutation receipt retention, shared region/Human regressions and authenticated Account abort cleanup, with affected static, frontier, generation, formatting and documentation checks. Historical receipt correlation remains controlled and claims no ordinary-NEW producer at the older schema. The current parent now owns the separately controlled V1038→V1038.1 retention case in the Account abort-composition test; its duplicate standalone Game Session fixture is removed here. Earlier proof retains its original source attribution. Operational source/incarnation custody, production PKI, default registration, public admission and activation remain unproved. + +The issuer INITIAL arm has a tenant/namespace-wide liveness limit: if its frozen originating NEW becomes `ABORTED` while the initializer remains `PREPARED`, later eligible NEW attempts at that live epoch retain the same initializer but cannot claim creation. An absent tenant-slot key stays absent, leaving every affected account non-admitting. No creator transfer, initializer replacement, automatic rearming or OPEN restoration through cutoff is supplied. Preserve the original evidence and keep the scope fenced; a qualified recovery mechanism and its proof remain missing. R907 freshly passes all 37 issuer-admission native cases with zero skips, including the distinct-account aborted-origin refusal, populated V1047→V1047.1 upgrade preserving all original evidence bytes, row versions and prior Flyway history, direct update/delete/truncate refusal for all five retained families, legal completion/retry and rollback-only corruption checks. Frontier, jOOQ generation, affected integration static analysis, formatting and documentation checks pass. Forward V1047.1 enforces retained-evidence guards without replacing the missing recovery mechanism or granting runtime authority. + +The next receiving correction adds forward [V1047.2](../../../services/game-session-service/src/main/resources/db/migration/V1047.2__issuer_admission_live_control_guards.sql) live counter/control guards: immutable provenance, original forward transitions, retention and deferred commit-time epoch coherence, preserving initial zero-without-control and same-epoch cutoff completion. Both INITIAL Redis owners now verify the principal and script on one connection before committing their one-shot SQL claim, then issue EVAL on that same connection; a lost SQL claim reply remains uncertain and never rearms creation. INITIAL observations leave the inapplicable account-fence cohort digest absent. R914 freshly passes all 79 selected cases (11 units and 68 PostgreSQL/Redis cases), including populated upgrade/history/row-version retention, incompatible upgrade and counter-only commit refusal, valid owner transitions, preflight failure followed by valid retry, lost-claim refusal and journal retention. Migration frontier, jOOQ generation, affected Checkstyle, formatting and documentation checks pass. R912 retains its two test-setup failures; R913 was stopped before executing tests, and neither is reported as successful. These are focused manually composed component results with controlled source and PKI inputs; the recovery, custody, registration and activation limits above remain. + +The final receiving correction checks protected INITIAL observation expiry after all SQL lock waits and source guards, and refuses Spring transaction/synchronization and caller-owned jOOQ transactions before acknowledgement external-source reads. Its codec preserves generations above the JSON exact-integer range. R917 freshly passes all 100 selected cases (15 units and 85 PostgreSQL/Redis cases), including both actual lock-wait expiry refusals, reconstructed ordinary-NEW progression with fresh acknowledgement readback, transaction-scope refusals, the whole 11-case physical-retirement class and populated live-control migration proof. The new retirement case uses a distinct retained layout domain rather than sharing another case's physical partition. Migration frontier, jOOQ generation, affected enabled main/integration static analysis, formatting and documentation checks pass on the reconciled parent. The earlier R916 broad aggregate retains its one fixture failure and one existing skip; its 2,732 units, 36 cross-service cases and 21 selected Account native cases passed at that preceding source. These results retain their source attribution and the existing custody, recovery, registration and activation limits. + The current local correction adds explicit recovery for a stale, uninstalled initial issuer-bootstrap candidate. Forward V1038.3 retains its original intent, cohort and issued work, captures the new actual inventory cut under monotonic fences, and atomically binds immutable supersession lineage to current control. A strictly newer trusted layout separates old physical work; installed anchors remain ineligible. Account CI selection and migration task inputs now cover its Game Session owner-composition dependency, and the native registration-image and lost-reply proofs use their actual SQL/Lua contracts. R827 passes 31 of 32 focused cases; its remaining failure is a test assertion against the transaction wrapper rather than the nested PostgreSQL refusal. R828 then passes that complete recovery case with affected integration static and formatting checks. Together they qualify 32 distinct current-source cases, including two actual Account abort compositions; frontier, jOOQ, affected static, formatting and documentation checks pass. The new recovery sequence uses controlled Account terminal input through the actual Game Session abort owner, separately from those two authenticated Account compositions. This is focused proof, not a full service-suite, live layout rotation, retained-key cleanup or production-authority claim. The local issuer owners now reject plans that exceed the executable 256-member-operation bound per partition, including retained `RELEASED` lineage independently of logical active capacity. A blocked plan retains its complete cohort and planned work; physical preparation refuses before allocating operation rows. Fresh ordinary NEW registration also checks the same nonretired local-operation set under the inventory lock before allocating new identities or rows, while exact retries retain their original operation at the bound. Both bootstrap owners use one strict Account issuer source-event verifier. R791 freshly passes the four PostgreSQL boundary cases: 256 allowed, both 257-reservation overflow forms blocked, and ordinary registration refusal/retry with unchanged durable state. R793 then freshly passes all 26 selected PostgreSQL cases across the plan, ordinary-operation and intent owners, plus affected production/integration static analysis, formatting and documentation checks. This is focused owner proof, not a complete service-suite or public admission result. Default registration, external source custody and admission limits remain unchanged. @@ -373,11 +381,11 @@ Account connect-token issuance retains its existing bootstrap and scope authenti | Capability | Implementation | Verification | Design | Implementation anchors | Proof anchors | Secondary handoffs | Gap or decision | | --- | --- | --- | --- | --- | --- | --- | --- | | `AA-1.1` Account and profile identity | `partial` | `drift-found` | [Authentication and authorization](../../architecture/system-architecture-authentication.md); [Account runtime and data](../../architecture/microservices/account-service/runtime-and-data.md); [ADR 0042](../../architecture/decisions/adr-0042-global-account-and-tenant-scoped-game-relationships.md); [ADR 0020](../../architecture/decisions/adr-0020-scoped-domain-and-operational-identifiers.md) | [AccountServiceImpl.java](../../../services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/impl/AccountServiceImpl.java); [AccountDto.java](../../../services/account-service/src/main/java/net/firedevops/firemud/accountservice/dto/AccountDto.java); [AccountMapper.java](../../../services/account-service/src/main/java/net/firedevops/firemud/accountservice/mapper/AccountMapper.java); [AccountController.java](../../../services/account-service/src/main/java/net/firedevops/firemud/accountservice/controller/AccountController.java); [ProfileController.java](../../../services/account-service/src/main/java/net/firedevops/firemud/accountservice/controller/ProfileController.java); [AccountGrpcService.java](../../../services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/impl/AccountGrpcService.java); [RuntimeAccountIdentityGrpcService.java](../../../services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/impl/RuntimeAccountIdentityGrpcService.java); [AccountRepository.java](../../../services/account-service/src/main/java/net/firedevops/firemud/accountservice/repository/AccountRepository.java); [account_service.proto](../../../protos/account/v1/account_service.proto); [openapi.yaml](../../../services/account-service/src/main/resources/openapi.yaml); [AccountIdentityProvenance.java](../../../services/account-service/src/main/java/net/firedevops/firemud/accountservice/entity/AccountIdentityProvenance.java); [V1__init.sql](../../../services/account-service/src/main/resources/db/migration/V1__init.sql); [V26__global_registration_join_evidence.sql](../../../services/account-service/src/main/resources/db/migration/V26__global_registration_join_evidence.sql); [V29__account_identity_uuid_bridge.sql](../../../services/account-service/src/main/resources/db/migration/V29__account_identity_uuid_bridge.sql) | [AccountServiceImplTest.java](../../../services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/service/impl/AccountServiceImplTest.java); [AccountControllerTest.java](../../../services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/controller/AccountControllerTest.java); [PublicBootstrapRoutesProdProfileTest.java](../../../services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/controller/PublicBootstrapRoutesProdProfileTest.java); [AccountGrpcServiceTest.java](../../../services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/service/impl/AccountGrpcServiceTest.java); [RuntimeAccountIdentityGrpcServiceTest.java](../../../services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/service/impl/RuntimeAccountIdentityGrpcServiceTest.java); [AccountApplicationIntegrationTest.java](../../../services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/AccountApplicationIntegrationTest.java); [AccountRepositoryIntegrationTest.java](../../../services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/repository/AccountRepositoryIntegrationTest.java); [ProfileControllerTest.java](../../../services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/controller/ProfileControllerTest.java) | [Shared Runtime](./shared-runtime-contracts-and-persistence.md) | Account V29 and `AccountRepository` persist/read back the non-nil Account UUID, recognized provenance, and unchanged numeric source-row identity required by ADR 0020. Registration REST/gRPC output and Account fields in the existing local exports now use that UUID; new registration audit records carry the same value, and the reverse DTO mapper is removed. `AccountDto` mapping rejects missing or contradictory UUID/provenance/source-row evidence. The focused unit/controller/gRPC suites executed 238 tests (174 AccountServiceImpl, 15 AccountController, 2 production-profile route, and 47 gRPC) with no failures, errors, or skips; the 5 PostgreSQL-backed Account application integration cases compiled but skipped because Docker is unavailable. Retained-row migration proof remains available but local PostgreSQL cases skip when Docker is disabled. Registration still creates global Account state plus its platform audit outbox row only, with no profile or tenant membership; caller-supplied tenant input is not authority. Authentication results and JWT subjects remain unchanged; profile/export profile identity fields and tenant IDs remain numeric and full portable export is not implemented. Current profile GET/PUT routes enforce exact caller-account subject binding and current tenant membership; tenant-qualified routes and membership-authority-generation validation remain gaps. Credential and email-OTP gameplay authentication remain global Account-identity operations that do not select a tenant or require current membership. `RuntimeAccountIdentityGrpcService` implements the authenticated Account-owner UUID/provenance read; its 31 focused unit cases, integration-source compilation, and formatting/documentation checks do not prove PostgreSQL execution or a live mTLS handshake, and do not enable UUID authentication or gameplay admission. Lifecycle-state retention remains tracked under AA-1.3. | -| `AA-1.2` Tenant membership, roles, and delegated access | `partial` | `drift-found` | [Multi-tenancy](../../architecture/system-architecture-multi-tenancy.md); [Authentication and authorization](../../architecture/system-architecture-authentication.md); [ADR 0025](../../architecture/decisions/adr-0025-explicit-open-enrollment-membership.md); [ADR 0042](../../architecture/decisions/adr-0042-global-account-and-tenant-scoped-game-relationships.md); [ADR 0138](../../architecture/decisions/adr-0138-expiring-playtest-grants-with-bounded-active-revocation.md) | [AccountServiceImpl.java](../../../services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/impl/AccountServiceImpl.java); [AccountJoinOperationRepository.java](../../../services/account-service/src/main/java/net/firedevops/firemud/accountservice/repository/AccountJoinOperationRepository.java); [AccountConnectScopeRepository.java](../../../services/account-service/src/main/java/net/firedevops/firemud/accountservice/repository/AccountConnectScopeRepository.java); [ExpiredConnectScopeCleanupJob.java](../../../services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/ExpiredConnectScopeCleanupJob.java); [AccountAuditOutboxRepository.java](../../../services/account-service/src/main/java/net/firedevops/firemud/accountservice/repository/AccountAuditOutboxRepository.java); [AccountCanonicalFirstJoinTerminalCoordinator.java](../../../services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/AccountCanonicalFirstJoinTerminalCoordinator.java); [AccountMembershipAuthorityEventProducer.java](../../../services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/AccountMembershipAuthorityEventProducer.java); [AccountAuthorityGenerationRepository.java](../../../services/account-service/src/main/java/net/firedevops/firemud/accountservice/repository/AccountAuthorityGenerationRepository.java); [AccountAuthoritySourceEvidenceRepository.java](../../../services/account-service/src/main/java/net/firedevops/firemud/accountservice/repository/AccountAuthoritySourceEvidenceRepository.java); [AccountTenantAuthorityEventRepository.java](../../../services/account-service/src/main/java/net/firedevops/firemud/accountservice/repository/AccountTenantAuthorityEventRepository.java); [AccountDemoTenantEntitlementRepository.java](../../../services/account-service/src/main/java/net/firedevops/firemud/accountservice/repository/AccountDemoTenantEntitlementRepository.java); [AccountTenantEntitlementOutboxRepository.java](../../../services/account-service/src/main/java/net/firedevops/firemud/accountservice/repository/AccountTenantEntitlementOutboxRepository.java); [AccountActorStagingEligibilityService.java](../../../services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/AccountActorStagingEligibilityService.java); [AccountActorStagingEligibilityGrpcService.java](../../../services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/impl/AccountActorStagingEligibilityGrpcService.java); [AccountActorStagingEligibilityRepository.java](../../../services/account-service/src/main/java/net/firedevops/firemud/accountservice/repository/AccountActorStagingEligibilityRepository.java); [AuthController.java](../../../services/account-service/src/main/java/net/firedevops/firemud/accountservice/controller/AuthController.java); [AccountTenantMembership.java](../../../services/account-service/src/main/java/net/firedevops/firemud/accountservice/entity/AccountTenantMembership.java); [AccountRealmAccessGrant.java](../../../services/account-service/src/main/java/net/firedevops/firemud/accountservice/entity/AccountRealmAccessGrant.java); [account_service.proto](../../../protos/account/v1/account_service.proto); [V26__global_registration_join_evidence.sql](../../../services/account-service/src/main/resources/db/migration/V26__global_registration_join_evidence.sql); [V27__retain_join_connect_scopes.sql](../../../services/account-service/src/main/resources/db/migration/V27__retain_join_connect_scopes.sql); [V30__approved_legacy_tenant_associations.sql](../../../services/account-service/src/main/resources/db/migration/V30__approved_legacy_tenant_associations.sql); [V31__subscription_authority_generation.sql](../../../services/account-service/src/main/resources/db/migration/V31__subscription_authority_generation.sql); [V32__realm_grant_currentness.sql](../../../services/account-service/src/main/resources/db/migration/V32__realm_grant_currentness.sql); [V33__fresh_tenant_identity_associations.sql](../../../services/account-service/src/main/resources/db/migration/V33__fresh_tenant_identity_associations.sql); [V34__account_membership_pair_authority.sql](../../../services/account-service/src/main/resources/db/migration/V34__account_membership_pair_authority.sql); [V35__canonical_uuid_membership_identity.sql](../../../services/account-service/src/main/resources/db/migration/V35__canonical_uuid_membership_identity.sql); [V36__account_auth_authority_generations.sql](../../../services/account-service/src/main/resources/db/migration/V36__account_auth_authority_generations.sql); [V37__canonical_first_join_scope_and_intent.sql](../../../services/account-service/src/main/resources/db/migration/V37__canonical_first_join_scope_and_intent.sql); [V38__account_first_join_authority_outbox_and_roles.sql](../../../services/account-service/src/main/resources/db/migration/V38__account_first_join_authority_outbox_and_roles.sql); [V39__canonical_first_join_terminal_receipt.sql](../../../services/account-service/src/main/resources/db/migration/V39__canonical_first_join_terminal_receipt.sql); [V40__account_authority_source_baselines.sql](../../../services/account-service/src/main/resources/db/migration/V40__account_authority_source_baselines.sql); [V53__account_protected_demo_entitlements.sql](../../../services/account-service/src/main/resources/db/migration/V53__account_protected_demo_entitlements.sql); [V73__account_tenant_authority_source_bridge.sql](../../../services/account-service/src/main/resources/db/migration/V73__account_tenant_authority_source_bridge.sql) | [AccountServiceImplTest.java](../../../services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/service/impl/AccountServiceImplTest.java); [AccountRepositoryIntegrationTest.java](../../../services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/repository/AccountRepositoryIntegrationTest.java); [AccountGrpcServiceTest.java](../../../services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/service/impl/AccountGrpcServiceTest.java); [AccountAuditDeliveryJobTest.java](../../../services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/service/AccountAuditDeliveryJobTest.java); [AuthControllerTest.java](../../../services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/controller/AuthControllerTest.java); [ExpiredConnectScopeCleanupJobTest.java](../../../services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/service/ExpiredConnectScopeCleanupJobTest.java); [AccountAuditOutboxRepositoryTest.java](../../../services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/repository/AccountAuditOutboxRepositoryTest.java); [AccountJoinDigestTest.java](../../../services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/dto/AccountJoinDigestTest.java); [AccountAuthoritySourceEvidencePersistenceIntegrationTest.java](../../../services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/repository/AccountAuthoritySourceEvidencePersistenceIntegrationTest.java); [AccountDemoTenantEntitlementPersistenceIntegrationTest.java](../../../services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/repository/AccountDemoTenantEntitlementPersistenceIntegrationTest.java); [AccountCanonicalFirstJoinEventIntegrationTest.java](../../../services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/service/AccountCanonicalFirstJoinEventIntegrationTest.java); [AccountCanonicalFirstJoinTerminalCoordinatorTest.java](../../../services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/service/AccountCanonicalFirstJoinTerminalCoordinatorTest.java); [AccountMembershipAuthorityEventProducerCanonicalJoinTest.java](../../../services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/service/AccountMembershipAuthorityEventProducerCanonicalJoinTest.java); [AccountAuthorityGenerationRepositoryTest.java](../../../services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/repository/AccountAuthorityGenerationRepositoryTest.java); [AccountTenantAuthorityEventRepositoryTest.java](../../../services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/repository/AccountTenantAuthorityEventRepositoryTest.java); [AccountActorStagingEligibilityServiceTest.java](../../../services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/service/AccountActorStagingEligibilityServiceTest.java); [AccountActorStagingEligibilityGrpcServiceTest.java](../../../services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/service/impl/AccountActorStagingEligibilityGrpcServiceTest.java) | [Realm Routing](./realm-routing-and-playable-state.md); [Shared Runtime](./shared-runtime-contracts-and-persistence.md) | Membership and Account-owned realm-grant records/readers are separate. `AccountTenantAuthorityEventRepository` appends the canonical tenant authority event during demo entitlement provisioning; `AccountMembershipAuthorityEventProducer` emits the first-JOIN membership event with its billing cutoff taken from that current tenant authority event, covered by [AccountCanonicalFirstJoinEventIntegrationTest](../../../services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/service/AccountCanonicalFirstJoinEventIntegrationTest.java); no entitlement caller wires it, and current PostgreSQL proof remains pending because the integration source compiled but was unrun locally. Current connect-token issuance returns `AUTH_UNAVAILABLE` before replay-cache or fresh pointer/visibility/membership reads while the canonical producer is unavailable; target current-authority and postcondition revalidation remain unproved. Current explicit `JoinPublicProductionMembership` validates a server-issued scope and caller binding, re-reads Game Session routing/catalog/pointer evidence before the Account transaction, and binds a v1 digest to verified caller/scope inputs; it does not guarantee that the exact target/catalog/pointer remains valid through Account commit. The strict ADR 0025 commit gate remains incomplete, and no durable Game Session-owned target fence is implemented or proved; transaction duration or timing thresholds alone would not prove it. The subscription authority query's `FOR UPDATE` locks only the subscription row, not its joined billing-owner Account; JOIN also locks the caller Account and operation record. Terminal-operation replay performs remote scope/target/entitlement checks outside its lock-holding transaction. Pending JOINs continue to receive fresh remote reads, while the Account transaction retains atomic membership, operation-outcome, and audit-outbox persistence. Focused unit proof verifies terminal replay revalidation occurs after commit or rollback without rewriting the stored outcome; the PostgreSQL row-lock regression compiles but skips locally without Docker. PostgreSQL runtime proof and direct text-client end-to-end proof are unclaimed. Global-only registration no longer creates an admitting membership. Expired unreferenced connect-scope rows are swept under their existing expiry; V27's restrictive scope FK preserves every scope referenced by a PENDING or terminal JOIN and fences racing intent inserts. JOIN recovery/reconciliation after an unknown database commit outcome remains a separate #2848 gap under the Overseer decision; do not mark ADR 0025 complete. The Gateway continues to block public JOIN exposure, and Game Session text JOIN/Join & Play dispatch remains #2898. `AccountActorStagingEligibilityGrpcService` is a read-only internal eligibility check disabled by default; it does not establish that a realm is public or preseeded and grants no gameplay admission. Membership authority generation in runtime admission, issuance grant validation, cached-success freshness/postcondition revalidation, and the target five-field grant codec with cross-service producer/consumer and admission-propagation proof remain incomplete. Current non-public discovery and supported text `PLAY` require admitting membership before the applicable realm grant; connect-token issuance fails closed before these checks and does not establish target grant validation. Transactional outboxes beyond the implemented registration/JOIN audit records, monotonic versioning, rate limits, tenant-scoped roles, and delegated management remain target gaps; see the [canonical Redis grant codec](../../architecture/system-architecture-redis.md#canonical-grant-authority-stream-scope-codec) and [identifier glossary](../../architecture/system-architecture-identifier-glossary.md#non-public-grant-identity). | +| `AA-1.2` Tenant membership, roles, and delegated access | `partial` | `drift-found` | [Multi-tenancy](../../architecture/system-architecture-multi-tenancy.md); [Authentication and authorization](../../architecture/system-architecture-authentication.md); [ADR 0025](../../architecture/decisions/adr-0025-explicit-open-enrollment-membership.md); [ADR 0042](../../architecture/decisions/adr-0042-global-account-and-tenant-scoped-game-relationships.md); [ADR 0138](../../architecture/decisions/adr-0138-expiring-playtest-grants-with-bounded-active-revocation.md) | [AccountServiceImpl.java](../../../services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/impl/AccountServiceImpl.java); [AccountJoinOperationRepository.java](../../../services/account-service/src/main/java/net/firedevops/firemud/accountservice/repository/AccountJoinOperationRepository.java); [AccountConnectScopeRepository.java](../../../services/account-service/src/main/java/net/firedevops/firemud/accountservice/repository/AccountConnectScopeRepository.java); [ExpiredConnectScopeCleanupJob.java](../../../services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/ExpiredConnectScopeCleanupJob.java); [AccountAuditOutboxRepository.java](../../../services/account-service/src/main/java/net/firedevops/firemud/accountservice/repository/AccountAuditOutboxRepository.java); [AccountCanonicalFirstJoinTerminalCoordinator.java](../../../services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/AccountCanonicalFirstJoinTerminalCoordinator.java); [AccountMembershipAuthorityEventProducer.java](../../../services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/AccountMembershipAuthorityEventProducer.java); [AccountAuthorityGenerationRepository.java](../../../services/account-service/src/main/java/net/firedevops/firemud/accountservice/repository/AccountAuthorityGenerationRepository.java); [AccountAuthoritySourceEvidenceRepository.java](../../../services/account-service/src/main/java/net/firedevops/firemud/accountservice/repository/AccountAuthoritySourceEvidenceRepository.java); [AccountTenantAuthorityEventRepository.java](../../../services/account-service/src/main/java/net/firedevops/firemud/accountservice/repository/AccountTenantAuthorityEventRepository.java); [AccountDemoTenantEntitlementRepository.java](../../../services/account-service/src/main/java/net/firedevops/firemud/accountservice/repository/AccountDemoTenantEntitlementRepository.java); [AccountTenantEntitlementOutboxRepository.java](../../../services/account-service/src/main/java/net/firedevops/firemud/accountservice/repository/AccountTenantEntitlementOutboxRepository.java); [AccountActorStagingEligibilityService.java](../../../services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/AccountActorStagingEligibilityService.java); [AccountActorStagingEligibilityGrpcService.java](../../../services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/impl/AccountActorStagingEligibilityGrpcService.java); [AccountActorStagingEligibilityRepository.java](../../../services/account-service/src/main/java/net/firedevops/firemud/accountservice/repository/AccountActorStagingEligibilityRepository.java); [AuthController.java](../../../services/account-service/src/main/java/net/firedevops/firemud/accountservice/controller/AuthController.java); [AccountTenantMembership.java](../../../services/account-service/src/main/java/net/firedevops/firemud/accountservice/entity/AccountTenantMembership.java); [AccountRealmAccessGrant.java](../../../services/account-service/src/main/java/net/firedevops/firemud/accountservice/entity/AccountRealmAccessGrant.java); [account_service.proto](../../../protos/account/v1/account_service.proto); [V26__global_registration_join_evidence.sql](../../../services/account-service/src/main/resources/db/migration/V26__global_registration_join_evidence.sql); [V27__retain_join_connect_scopes.sql](../../../services/account-service/src/main/resources/db/migration/V27__retain_join_connect_scopes.sql); [V30__approved_legacy_tenant_associations.sql](../../../services/account-service/src/main/resources/db/migration/V30__approved_legacy_tenant_associations.sql); [V31__subscription_authority_generation.sql](../../../services/account-service/src/main/resources/db/migration/V31__subscription_authority_generation.sql); [V32__realm_grant_currentness.sql](../../../services/account-service/src/main/resources/db/migration/V32__realm_grant_currentness.sql); [V33__fresh_tenant_identity_associations.sql](../../../services/account-service/src/main/resources/db/migration/V33__fresh_tenant_identity_associations.sql); [V34__account_membership_pair_authority.sql](../../../services/account-service/src/main/resources/db/migration/V34__account_membership_pair_authority.sql); [V35__canonical_uuid_membership_identity.sql](../../../services/account-service/src/main/resources/db/migration/V35__canonical_uuid_membership_identity.sql); [V36__account_auth_authority_generations.sql](../../../services/account-service/src/main/resources/db/migration/V36__account_auth_authority_generations.sql); [V37__canonical_first_join_scope_and_intent.sql](../../../services/account-service/src/main/resources/db/migration/V37__canonical_first_join_scope_and_intent.sql); [V38__account_first_join_authority_outbox_and_roles.sql](../../../services/account-service/src/main/resources/db/migration/V38__account_first_join_authority_outbox_and_roles.sql); [V39__canonical_first_join_terminal_receipt.sql](../../../services/account-service/src/main/resources/db/migration/V39__canonical_first_join_terminal_receipt.sql); [V40__account_authority_source_baselines.sql](../../../services/account-service/src/main/resources/db/migration/V40__account_authority_source_baselines.sql); [V53__account_protected_demo_entitlements.sql](../../../services/account-service/src/main/resources/db/migration/V53__account_protected_demo_entitlements.sql); [V73__account_tenant_authority_source_bridge.sql](../../../services/account-service/src/main/resources/db/migration/V73__account_tenant_authority_source_bridge.sql); [CanonicalGameplayAccountInitialBarrierInitializerRepository.java](../../../services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/repository/CanonicalGameplayAccountInitialBarrierInitializerRepository.java); [CanonicalGameplayAccountInitialBarrierRedisOwner.java](../../../services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/repository/CanonicalGameplayAccountInitialBarrierRedisOwner.java); [V1047__canonical_initial_account_admission_barrier.sql](../../../services/game-session-service/src/main/resources/db/migration/V1047__canonical_initial_account_admission_barrier.sql) | [AccountServiceImplTest.java](../../../services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/service/impl/AccountServiceImplTest.java); [AccountRepositoryIntegrationTest.java](../../../services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/repository/AccountRepositoryIntegrationTest.java); [AccountGrpcServiceTest.java](../../../services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/service/impl/AccountGrpcServiceTest.java); [AccountAuditDeliveryJobTest.java](../../../services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/service/AccountAuditDeliveryJobTest.java); [AuthControllerTest.java](../../../services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/controller/AuthControllerTest.java); [ExpiredConnectScopeCleanupJobTest.java](../../../services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/service/ExpiredConnectScopeCleanupJobTest.java); [AccountAuditOutboxRepositoryTest.java](../../../services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/repository/AccountAuditOutboxRepositoryTest.java); [AccountJoinDigestTest.java](../../../services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/dto/AccountJoinDigestTest.java); [AccountAuthoritySourceEvidencePersistenceIntegrationTest.java](../../../services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/repository/AccountAuthoritySourceEvidencePersistenceIntegrationTest.java); [AccountDemoTenantEntitlementPersistenceIntegrationTest.java](../../../services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/repository/AccountDemoTenantEntitlementPersistenceIntegrationTest.java); [AccountCanonicalFirstJoinEventIntegrationTest.java](../../../services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/service/AccountCanonicalFirstJoinEventIntegrationTest.java); [AccountCanonicalFirstJoinTerminalCoordinatorTest.java](../../../services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/service/AccountCanonicalFirstJoinTerminalCoordinatorTest.java); [AccountMembershipAuthorityEventProducerCanonicalJoinTest.java](../../../services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/service/AccountMembershipAuthorityEventProducerCanonicalJoinTest.java); [AccountAuthorityGenerationRepositoryTest.java](../../../services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/repository/AccountAuthorityGenerationRepositoryTest.java); [AccountTenantAuthorityEventRepositoryTest.java](../../../services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/repository/AccountTenantAuthorityEventRepositoryTest.java); [AccountActorStagingEligibilityServiceTest.java](../../../services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/service/AccountActorStagingEligibilityServiceTest.java); [AccountActorStagingEligibilityGrpcServiceTest.java](../../../services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/service/impl/AccountActorStagingEligibilityGrpcServiceTest.java); [CanonicalGameplayProtectedIncarnationReceiverPostgresIntegrationTest.java](../../../services/game-session-service/src/test/java/integration/net/firedevops/firemud/gamesession/repository/CanonicalGameplayProtectedIncarnationReceiverPostgresIntegrationTest.java); [CanonicalGameplayAccountInitialBarrierRedisScriptIntegrationTest.java](../../../services/game-session-service/src/test/java/integration/net/firedevops/firemud/gamesession/repository/CanonicalGameplayAccountInitialBarrierRedisScriptIntegrationTest.java); R849 partial execution, R855/R856 recovery, R867 and R902 focused execution have separate scopes and limits recorded above | [Realm Routing](./realm-routing-and-playable-state.md); [Shared Runtime](./shared-runtime-contracts-and-persistence.md) | Membership and Account-owned realm-grant records/readers are separate. `AccountTenantAuthorityEventRepository` appends the canonical tenant authority event during demo entitlement provisioning; `AccountMembershipAuthorityEventProducer` emits the first-JOIN membership event with its billing cutoff taken from that current tenant authority event, covered by [AccountCanonicalFirstJoinEventIntegrationTest](../../../services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/service/AccountCanonicalFirstJoinEventIntegrationTest.java); no entitlement caller wires it, and current PostgreSQL proof remains pending because the integration source compiled but was unrun locally. Current connect-token issuance returns `AUTH_UNAVAILABLE` before replay-cache or fresh pointer/visibility/membership reads while the canonical producer is unavailable; target current-authority and postcondition revalidation remain unproved. Current explicit `JoinPublicProductionMembership` validates a server-issued scope and caller binding, re-reads Game Session routing/catalog/pointer evidence before the Account transaction, and binds a v1 digest to verified caller/scope inputs; it does not guarantee that the exact target/catalog/pointer remains valid through Account commit. The strict ADR 0025 commit gate remains incomplete, and no durable Game Session-owned target fence is implemented or proved; transaction duration or timing thresholds alone would not prove it. The subscription authority query's `FOR UPDATE` locks only the subscription row, not its joined billing-owner Account; JOIN also locks the caller Account and operation record. Terminal-operation replay performs remote scope/target/entitlement checks outside its lock-holding transaction. Pending JOINs continue to receive fresh remote reads, while the Account transaction retains atomic membership, operation-outcome, and audit-outbox persistence. Focused unit proof verifies terminal replay revalidation occurs after commit or rollback without rewriting the stored outcome; the PostgreSQL row-lock regression compiles but skips locally without Docker. PostgreSQL runtime proof and direct text-client end-to-end proof are unclaimed. Global-only registration no longer creates an admitting membership. Expired unreferenced connect-scope rows are swept under their existing expiry; V27's restrictive scope FK preserves every scope referenced by a PENDING or terminal JOIN and fences racing intent inserts. JOIN recovery/reconciliation after an unknown database commit outcome remains a separate #2848 gap under the Overseer decision; do not mark ADR 0025 complete. The Gateway continues to block public JOIN exposure, and Game Session text JOIN/Join & Play dispatch remains #2898. `AccountActorStagingEligibilityGrpcService` is a read-only internal eligibility check disabled by default; it does not establish that a realm is public or preseeded and grants no gameplay admission. Membership authority generation in runtime admission, issuance grant validation, cached-success freshness/postcondition revalidation, and the target five-field grant codec with cross-service producer/consumer and admission-propagation proof remain incomplete. Current non-public discovery and supported text `PLAY` require admitting membership before the applicable realm grant; connect-token issuance fails closed before these checks and does not establish target grant validation. Transactional outboxes beyond the implemented registration/JOIN audit records, monotonic versioning, rate limits, tenant-scoped roles, and delegated management remain target gaps; see the [canonical Redis grant codec](../../architecture/system-architecture-redis.md#canonical-grant-authority-stream-scope-codec) and [identifier glossary](../../architecture/system-architecture-identifier-glossary.md#non-public-grant-identity). The unregistered INITIAL Account prerequisite preserves one original target and does not supply abandoned-target or account-wide fenced recovery, fresh Account authority, final admission or runtime activation; see the [readiness scope and proof](#canonical-new-admission-components). | | `AA-1.3` Authentication, recovery, security policy, and account data rights | `partial` | `drift-found` | [Authentication and authorization](../../architecture/system-architecture-authentication.md); [Security](../../architecture/system-architecture-security.md); [Account runtime and data](../../architecture/microservices/account-service/runtime-and-data.md); [Moderation Policies](../../architecture/microservices/logging-admin-service/moderation-policies.md); [Session behavior](../../architecture/system-architecture-session-behavior.md); [ADR 0034](../../architecture/decisions/adr-0034-layered-abuse-controls-without-attacker-triggered-account-locks.md); [ADR 0035](../../architecture/decisions/adr-0035-single-record-issued-token-registry.md); [ADR 0141](../../architecture/decisions/adr-0141-fixed-safety-restriction-categories-and-independent-lifecycles.md); [ADR 0142](../../architecture/decisions/adr-0142-bounded-moderation-appeal-cases.md); [ADR 0047](../../architecture/decisions/adr-0047-logging-admin-as-external-operator-write-ingress.md); [Account API Contracts](../../architecture/microservices/account-service/api-contracts.md#operator-authorization-references); [Logging & Admin API Contracts](../../architecture/microservices/logging-admin-service/api-contracts.md); [Game Session API Contracts](../../architecture/microservices/game-session-service/api-contracts.md) | [AuthController.java](../../../services/account-service/src/main/java/net/firedevops/firemud/accountservice/controller/AuthController.java); [AccountController.java](../../../services/account-service/src/main/java/net/firedevops/firemud/accountservice/controller/AccountController.java); [AccountServiceImpl.java](../../../services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/impl/AccountServiceImpl.java); [SessionServiceImpl.java](../../../services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/session/SessionServiceImpl.java); [JwksController.java](../../../services/account-service/src/main/java/net/firedevops/firemud/accountservice/controller/JwksController.java); [AccountAuthorityGenerationRepository.java](../../../services/account-service/src/main/java/net/firedevops/firemud/accountservice/repository/AccountAuthorityGenerationRepository.java); [AccountAuthoritySourceEvidenceRepository.java](../../../services/account-service/src/main/java/net/firedevops/firemud/accountservice/repository/AccountAuthoritySourceEvidenceRepository.java); [AccountJwtSignerDesiredStateRepository.java](../../../services/account-service/src/main/java/net/firedevops/firemud/accountservice/repository/AccountJwtSignerDesiredStateRepository.java); [AccountJwtReadinessProbeRepository.java](../../../services/account-service/src/main/java/net/firedevops/firemud/accountservice/repository/AccountJwtReadinessProbeRepository.java); [AccountControlUiIssuanceService.java](../../../services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/session/AccountControlUiIssuanceService.java); [AccountStartSessionOperatorAuthorizationService.java](../../../services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/session/AccountStartSessionOperatorAuthorizationService.java); [AccountJwtSignerMaterializationService.java](../../../services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/impl/AccountJwtSignerMaterializationService.java); [application-prod.yml](../../../services/account-service/src/main/resources/application-prod.yml); [V36__account_auth_authority_generations.sql](../../../services/account-service/src/main/resources/db/migration/V36__account_auth_authority_generations.sql); [V40__account_authority_source_baselines.sql](../../../services/account-service/src/main/resources/db/migration/V40__account_authority_source_baselines.sql); [V77 reset receipts](../../../services/account-service/src/main/resources/db/migration/V77__account_password_reset_operation_receipts.sql); [V89 pending reset intent](../../../services/account-service/src/main/resources/db/migration/V89__account_password_reset_pending_draft_source_changes.sql); [V99__account_jwt_signer_desired_state.sql](../../../services/account-service/src/main/resources/db/migration/V99__account_jwt_signer_desired_state.sql); [V123__account_jwt_readiness_per_pod_closure.sql](../../../services/account-service/src/main/resources/db/migration/V123__account_jwt_readiness_per_pod_closure.sql); [V125__account_jwt_signer_promotion_receipt_binding.sql](../../../services/account-service/src/main/resources/db/migration/V125__account_jwt_signer_promotion_receipt_binding.sql); [V126](../../../services/account-service/src/main/resources/db/migration/V126__start_session_operator_authorization.sql); [V126.1](../../../services/account-service/src/main/resources/db/migration/V126.1__start_session_operator_response_envelope_erasure.sql); [V126.2](../../../services/account-service/src/main/resources/db/migration/V126.2__account_control_ui_registry_cleanup_deadline.sql); [V126.3](../../../services/account-service/src/main/resources/db/migration/V126.3__start_session_response_envelope_bounds.sql); [AccountPlatformRestrictionOperationRepository.java](../../../services/account-service/src/main/java/net/firedevops/firemud/accountservice/repository/AccountPlatformRestrictionOperationRepository.java); [V137__account_platform_restriction_revision_receipts.sql](../../../services/account-service/src/main/resources/db/migration/V137__account_platform_restriction_revision_receipts.sql); [V137.1__account_platform_restriction_lifecycle_consistency.sql](../../../services/account-service/src/main/resources/db/migration/V137.1__account_platform_restriction_lifecycle_consistency.sql); [AccountPlatformRestrictionMutationRequest.java](../../../services/account-service/src/main/java/net/firedevops/firemud/accountservice/dto/AccountPlatformRestrictionMutationRequest.java); [AccountSecurityStateAuthorityEventV1Codec.java](../../../services/common-platform-core/src/main/java/net/firedevops/firemud/common/account/authority/AccountSecurityStateAuthorityEventV1Codec.java); [AccountAuthoritySourceEventReadback.java](../../../services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/AccountAuthoritySourceEventReadback.java); [AccountPasswordResetOperationRepository.java](../../../services/account-service/src/main/java/net/firedevops/firemud/accountservice/repository/AccountPasswordResetOperationRepository.java); [AccountPasswordResetDraftSourceChangeRepository.java](../../../services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/AccountPasswordResetDraftSourceChangeRepository.java); [PasswordResetTokenRepository.java](../../../services/account-service/src/main/java/net/firedevops/firemud/accountservice/repository/PasswordResetTokenRepository.java); [V140](../../../services/account-service/src/main/resources/db/migration/V140__account_gameplay_admission_lease_operations.sql); [V141](../../../services/account-service/src/main/resources/db/migration/V141__account_admission_unknown_decision_abort.sql); [V142](../../../services/account-service/src/main/resources/db/migration/V142__account_admission_durable_commit_confirmation.sql); [V143](../../../services/account-service/src/main/resources/db/migration/V143__account_global_pending_admission_fences.sql); [V144](../../../services/account-service/src/main/resources/db/migration/V144__account_admission_original_ack_receipt.sql); [V145](../../../services/account-service/src/main/resources/db/migration/V145__retire_experimental_admission_confirmation_writes.sql); [V146](../../../services/account-service/src/main/resources/db/migration/V146__account_original_ack_pg18_fresh_insert.sql); [AccountGameplayAdmissionLeaseRepository.java](../../../services/account-service/src/main/java/net/firedevops/firemud/accountservice/repository/AccountGameplayAdmissionLeaseRepository.java); [AccountGameplayAdmissionOriginalCommitExecutor.java](../../../services/account-service/src/main/java/net/firedevops/firemud/accountservice/repository/AccountGameplayAdmissionOriginalCommitExecutor.java); [AccountGameplayAdmissionOriginalAckReceiptRepository.java](../../../services/account-service/src/main/java/net/firedevops/firemud/accountservice/repository/AccountGameplayAdmissionOriginalAckReceiptRepository.java); [AccountGameplayAdmissionOriginalAckReceiptCommitExecutor.java](../../../services/account-service/src/main/java/net/firedevops/firemud/accountservice/repository/AccountGameplayAdmissionOriginalAckReceiptCommitExecutor.java); [V158](../../../services/account-service/src/main/resources/db/migration/V158__account_start_session_authority_captures.sql); [V159](../../../services/account-service/src/main/resources/db/migration/V159__start_session_world_participation.sql); [V160](../../../services/account-service/src/main/resources/db/migration/V160__start_session_world_original_attempt_evidence.sql); [AccountStartSessionAuthorityCaptureRepository](../../../services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/session/AccountStartSessionAuthorityCaptureRepository.java); [AccountStartSessionWorldParticipationRepository](../../../services/account-service/src/main/java/net/firedevops/firemud/accountservice/repository/AccountStartSessionWorldParticipationRepository.java); [AccountStartSessionWorldOriginalAttemptEvidenceRepository](../../../services/account-service/src/main/java/net/firedevops/firemud/accountservice/repository/AccountStartSessionWorldOriginalAttemptEvidenceRepository.java); [V160.1](../../../services/account-service/src/main/resources/db/migration/V160.1__start_session_operator_bundle_source_fence.sql); [AccountStartSessionWorldParticipationAcquisitionService.java](../../../services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/session/AccountStartSessionWorldParticipationAcquisitionService.java); [AccountStartSessionWorldParticipationHistoricalReadService.java](../../../services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/session/AccountStartSessionWorldParticipationHistoricalReadService.java); [AccountStartSessionWorldParticipationSettlementService.java](../../../services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/session/AccountStartSessionWorldParticipationSettlementService.java); [Logging StartSessionAuthorizationCoordinator.java](../../../services/logging-admin-service/src/main/java/net/firedevops/firemud/loggingadmin/operator/StartSessionAuthorizationCoordinator.java); [Logging StartSessionOperatorAuthorizationClient.java](../../../services/logging-admin-service/src/main/java/net/firedevops/firemud/loggingadmin/client/StartSessionOperatorAuthorizationClient.java); [Logging StartSessionPreAuthorizationReservationRepository.java](../../../services/logging-admin-service/src/main/java/net/firedevops/firemud/loggingadmin/repository/StartSessionPreAuthorizationReservationRepository.java); [Game Session StartSessionOperatorRedemptionClient.java](../../../services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/client/StartSessionOperatorRedemptionClient.java); [GameSessionStartSessionOperatorAttemptRepository.java](../../../services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/repository/GameSessionStartSessionOperatorAttemptRepository.java); [GameSessionCanonicalLaunchPreparationService.java](../../../services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/service/GameSessionCanonicalLaunchPreparationService.java); [CanonicalGameInstanceLaunchAssociationRepository.java](../../../services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/repository/CanonicalGameInstanceLaunchAssociationRepository.java); [V1003 original StartSession protections](../../../services/account-service/src/main/resources/db/migration/V1003__original_start_session_source_protections.sql); [V1004 activation settlement lifecycle integrity](../../../services/account-service/src/main/resources/db/migration/V1004__activation_settlement_lifecycle_integrity.sql); [V1004.1 monotonic lifecycle counters](../../../services/account-service/src/main/resources/db/migration/V1004.1__activation_settlement_monotonic_lifecycle_counters.sql); [V1004.2 retained lifecycle and canonical UUID integrity](../../../services/account-service/src/main/resources/db/migration/V1004.2__activation_settlement_retained_lifecycle_integrity.sql); [V1004.3 canonical activation acquisition carriers](../../../services/account-service/src/main/resources/db/migration/V1004.3__activation_acquisition_canonical_carriers.sql); [AccountStartSessionActivationProtectionRepository.java](../../../services/account-service/src/main/java/net/firedevops/firemud/accountservice/repository/AccountStartSessionActivationProtectionRepository.java); [V1006 World activation terminal digest alignment](../../../services/account-service/src/main/resources/db/migration/V1006__world_activation_terminal_digest_alignment.sql); [V1007 selected source reservations](../../../services/account-service/src/main/resources/db/migration/V1007__selected_owner_intake_source_reservations.sql); [AccountSelectedOwnerIntakeSourceReservationService.java](../../../services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/session/AccountSelectedOwnerIntakeSourceReservationService.java); [V1008 selected-owner intake final authorizations](../../../services/account-service/src/main/resources/db/migration/V1008__selected_owner_intake_final_authorizations.sql); [V1009 selected-owner intake terminal settlement](../../../services/account-service/src/main/resources/db/migration/V1009__selected_owner_intake_terminal_settlement.sql); [V1010 Entity selected-owner intake terminal settlement](../../../services/account-service/src/main/resources/db/migration/V1010__entity_selected_owner_intake_terminal_settlement.sql); [AccountSelectedOwnerIntakeSettlementService.java](../../../services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/session/AccountSelectedOwnerIntakeSettlementService.java); [AccountSelectedOwnerIntakeAuthorizationService.java](../../../services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/session/AccountSelectedOwnerIntakeAuthorizationService.java); [AccountSelectedOwnerIntakeWorldClosureAuthorizationReadService.java](../../../services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/session/AccountSelectedOwnerIntakeWorldClosureAuthorizationReadService.java); [AccountSelectedOwnerIntakeSettlementReceipt.java](../../../services/common-platform-core/src/main/java/net/firedevops/firemud/common/account/sourceintake/AccountSelectedOwnerIntakeSettlementReceipt.java); [AccountStartSessionAdmissionProtectionAcquisitionService.java](../../../services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/session/AccountStartSessionAdmissionProtectionAcquisitionService.java); [AccountStartSessionAdmissionProtectionSettlementService.java](../../../services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/session/AccountStartSessionAdmissionProtectionSettlementService.java); [AccountStartSessionAdmissionProtectionGrpcService.java](../../../services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/session/AccountStartSessionAdmissionProtectionGrpcService.java); [AccountStartSessionAdmissionProtectionRepository.java](../../../services/account-service/src/main/java/net/firedevops/firemud/accountservice/repository/AccountStartSessionAdmissionProtectionRepository.java); [GrpcAccountInitialAdmissionSettlementReadClient.java](../../../services/common-platform-core/src/main/java/net/firedevops/firemud/common/account/startsession/GrpcAccountInitialAdmissionSettlementReadClient.java) | [AuthControllerTest.java](../../../services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/controller/AuthControllerTest.java); [AccountServiceImplTest.java](../../../services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/service/impl/AccountServiceImplTest.java); [JwksControllerTest.java](../../../services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/controller/JwksControllerTest.java); [AuthTokenInterceptorTest.java](../../../services/common-security/src/test/java/unit/net/firedevops/firemud/common/security/AuthTokenInterceptorTest.java); [AccountAuthorityGenerationRepositoryTest.java](../../../services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/repository/AccountAuthorityGenerationRepositoryTest.java); [AccountAuthoritySourceEvidencePersistenceIntegrationTest.java](../../../services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/repository/AccountAuthoritySourceEvidencePersistenceIntegrationTest.java); [PasswordResetAuthorityProducerPostgresIntegrationTest.java](../../../services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/PasswordResetAuthorityProducerPostgresIntegrationTest.java); [AccountPasswordResetOperationRepositoryTest.java](../../../services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/repository/AccountPasswordResetOperationRepositoryTest.java); [AccountJwtSignerStoragePostgresIntegrationTest.java](../../../services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/repository/AccountJwtSignerStoragePostgresIntegrationTest.java); [AccountJwtReadinessStoragePostgresIntegrationTest.java](../../../services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/service/session/AccountJwtReadinessStoragePostgresIntegrationTest.java); [AccountStartSessionOperatorAuthorizationRepositoryIntegrationTest.java](../../../services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/repository/AccountStartSessionOperatorAuthorizationRepositoryIntegrationTest.java); [AccountControlUiIssuancePostgresIntegrationTest.java](../../../services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/service/session/AccountControlUiIssuancePostgresIntegrationTest.java); [AccountStartSessionOperatorAuthorizationConfigurationTest.java](../../../services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/config/AccountStartSessionOperatorAuthorizationConfigurationTest.java); [AccountJwtJwksTrustedSourceTest.java](../../../services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/service/session/AccountJwtJwksTrustedSourceTest.java); [AccountStartSessionOperatorAuthorizationServiceTest.java](../../../services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/service/session/AccountStartSessionOperatorAuthorizationServiceTest.java); [StartSessionOperatorAuthorizationGrpcServiceTest.java](../../../services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/service/impl/StartSessionOperatorAuthorizationGrpcServiceTest.java); [AccountJwtSignerMaterializationServiceTest.java](../../../services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/service/impl/AccountJwtSignerMaterializationServiceTest.java); [AccountPlatformRestrictionOperationPostgresIntegrationTest.java](../../../services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/repository/AccountPlatformRestrictionOperationPostgresIntegrationTest.java); [AccountPlatformRestrictionOperationRepositoryTest.java](../../../services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/repository/AccountPlatformRestrictionOperationRepositoryTest.java); [AccountAuthoritySourceEventReadbackTest.java](../../../services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/service/AccountAuthoritySourceEventReadbackTest.java); [AccountSecurityStateAuthorityEventV1CodecTest.java](../../../services/common-platform-core/src/test/java/net/firedevops/firemud/common/account/authority/AccountSecurityStateAuthorityEventV1CodecTest.java); [AccountGenerationProjectionRestrictionDispatchTest.java](../../../services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/service/AccountGenerationProjectionRestrictionDispatchTest.java); [RuntimeMembershipAuthorityEvidenceValidatorRestrictionDispatchTest.java](../../../services/common-platform-core/src/test/java/net/firedevops/firemud/common/account/authority/RuntimeMembershipAuthorityEvidenceValidatorRestrictionDispatchTest.java); [AccountGameplayAdmissionProtectedEntryPrototypeIntegrationTest.java](../../../services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/repository/AccountGameplayAdmissionProtectedEntryPrototypeIntegrationTest.java); [AccountStartSessionWorldParticipationPostgresIntegrationTest.java](../../../services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/repository/AccountStartSessionWorldParticipationPostgresIntegrationTest.java); [AccountStartSessionWorldOriginalAttemptEvidencePostgresIntegrationTest.java](../../../services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/repository/AccountStartSessionWorldOriginalAttemptEvidencePostgresIntegrationTest.java); [AccountStartSessionAuthorityCapturePostgresIntegrationTest.java](../../../services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/service/session/AccountStartSessionAuthorityCapturePostgresIntegrationTest.java); [HostedTermsDisclosureHandoffPostgresIntegrationTest.java](../../../services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/hostedterms/HostedTermsDisclosureHandoffPostgresIntegrationTest.java); [AccountStartSessionOperatorAuthorityBundleTest.java](../../../services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/service/session/AccountStartSessionOperatorAuthorityBundleTest.java); [Logging StartSessionOperatorAuthorizationClientTest.java](../../../services/logging-admin-service/src/test/java/unit/net/firedevops/firemud/loggingadmin/client/StartSessionOperatorAuthorizationClientTest.java); [Logging StartSessionAuthorizationCoordinatorTest.java](../../../services/logging-admin-service/src/test/java/unit/net/firedevops/firemud/loggingadmin/operator/StartSessionAuthorizationCoordinatorTest.java); [Logging reservation PostgreSQL test](../../../services/logging-admin-service/src/test/java/integration/net/firedevops/firemud/loggingadmin/StartSessionPreAuthorizationReservationPostgresIntegrationTest.java); [Game Session StartSessionOperatorRedemptionClientTest.java](../../../services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/client/StartSessionOperatorRedemptionClientTest.java); [Game Session operator-attempt storage test](../../../services/game-session-service/src/test/java/integration/net/firedevops/firemud/gamesession/repository/GameSessionStartSessionOperatorAttemptRepositoryIntegrationTest.java); [Game Session canonical launch preparation test](../../../services/game-session-service/src/test/java/integration/net/firedevops/firemud/gamesession/service/GameSessionCanonicalLaunchPreparationServiceIntegrationTest.java); [Admission protection PostgreSQL suite](../../../services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/repository/AccountStartSessionAdmissionProtectionPostgresIntegrationTest.java); [Activation protection PostgreSQL suite](../../../services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/repository/AccountStartSessionActivationProtectionPostgresIntegrationTest.java); [AccountSelectedOwnerIntakeSourceReservationPostgresIntegrationTest.java](../../../services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/service/session/AccountSelectedOwnerIntakeSourceReservationPostgresIntegrationTest.java); [SelectedOwnerSourceDisclosurePostgresIntegrationTest.java](../../../services/game-design-service/src/test/java/crossservice/net/firedevops/firemud/accountservice/service/session/SelectedOwnerSourceDisclosurePostgresIntegrationTest.java); [AccountSelectedOwnerIntakeAuthorizationPostgresIntegrationTest.java](../../../services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/service/session/AccountSelectedOwnerIntakeAuthorizationPostgresIntegrationTest.java); [AccountSelectedOwnerIntakeSettlementServiceTest.java](../../../services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/service/session/AccountSelectedOwnerIntakeSettlementServiceTest.java); [SelectedOwnerIntakeSettlementGrpcCodecTest.java](../../../services/common-platform-core/src/test/java/net/firedevops/firemud/common/account/sourceintake/SelectedOwnerIntakeSettlementGrpcCodecTest.java); [AccountStartSessionAdmissionProtectionAcquisitionPostgresIntegrationTest.java](../../../services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/service/session/AccountStartSessionAdmissionProtectionAcquisitionPostgresIntegrationTest.java); [AccountStartSessionAdmissionProtectionRepositoryPostgresIntegrationTest.java](../../../services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/service/session/AccountStartSessionAdmissionProtectionRepositoryPostgresIntegrationTest.java); [AccountStartSessionAdmissionProtectionServiceTest.java](../../../services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/service/session/AccountStartSessionAdmissionProtectionServiceTest.java); [AccountStartSessionAdmissionProtectionGrpcServiceTest.java](../../../services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/service/session/AccountStartSessionAdmissionProtectionGrpcServiceTest.java); [GrpcAccountInitialAdmissionSettlementReadClientTest.java](../../../services/common-platform-core/src/test/java/net/firedevops/firemud/common/account/startsession/GrpcAccountInitialAdmissionSettlementReadClientTest.java) | [Shared Runtime](./shared-runtime-contracts-and-persistence.md); [Platform Operations](./platform-operations-and-delivery.md) | Public password-reset, username-recovery, and email-verification initiation use normalized email selectors and return the same neutral HTTP success for known and unknown addresses, including when known-account post-commit SMTP errors are caught and logged; unknown addresses create no token or delivery attempt. However, SMTP delivery remains synchronous after commit and is a timing oracle; durable asynchronous delivery is absent, and focused service tests prove exception containment only, not timing resistance or durable delivery. Public verification accepts no numeric account selector. The login-factor `PUT` now fails closed with `501 NOT_IMPLEMENTED` because Account has no recent ordinary reauthentication evidence mechanism; implementing that Account-owned proof and enabling the mutation remain open under ADR 0045. The current Account restriction slice adds a closed restriction event variant, V137 immutable revision/current-result receipts, exact SQL source-head dispatch, and protective-category lifecycle sync; the owner mutation stays default-denied because no authoritative policy/intent and authenticated-caller proof receiver exists. V137.1 adds forward final-state protective-category consistency guards while preserving published V137 and retained V126.x bytes. The staged Java writer rejects protective restrictions on pending-deletion and deleted accounts before side effects; supported deletion/recovery producer sequencing remains a gap. V81 (source V88) `NONRESTRICTED` birth results remain historical predecessor evidence, not current absence; physical forward migration, contradiction rollback, concurrency, and readback proof remain pending, so no authorized admission or end-to-end enforcement is claimed. Separate complete bounded moderation appeal handoff, `/auth/logout` and `/auth/logout-all` revocation authority, TOTP, trusted source context, Account-owned graduated login throttles, and fail-closed limiter-outage behavior remain absent. Current token issuance still writes scope-duplicated account/tenant keys and downstream validators do not enforce the one-record issued-token registry from ADR 0035. `AUTH_ACCOUNT_LOCKED` remains reserved, while the current Game Session command limiter performs a Redis operation per command contrary to ADR 0034. Current `AccountServiceImpl.deleteAccount` fails closed by rejecting any retained JOIN operation first, then nonterminal subscriptions, and otherwise throwing `ACCOUNT_DELETE_UNAVAILABLE` before any repository deletion; retained-data lifecycle and deletion reconciliation remain unimplemented. Password-reset token consumption and exact source-fenced completion are implemented for Accounts with valid current source evidence; reset-driven revocation, other recovery workflows, and passing physical PostgreSQL proof remain incomplete. Export and JWKS foundations are live. Account signer lifecycle, current readiness, and validator-inventory storage remain passive V99–V125 evidence preparation; focused physical PostgreSQL 18 signer/readiness suites confirm bounded storage proof only with synthetic inventory/resource inputs, not live Kubernetes currentness, readiness activation, or signer activation; signer runtime/currentness remains inactive. V126/V126.1 separately add Account-owned StartSession authorization and signer-materialization source preparation: StartSession composition remains off by default, materializer trust remains off by default and denies every RPC when absent, and missing bootstrap-coordinator composition denies enrollment and promotion. These source adapters do not register a runtime issuer or promotion/consumer coordinator, establish operator lifecycle ownership under AA-1.3, or establish activation. The current AA-1.3 owner-source cut also includes V126.2 cleanup-deadline storage and V126.3 response-envelope size-guard migration. At exact source head `44bbd2a9fff1e1561816e16fd0deb9cc274ae251`, the Control-UI issuance PostgreSQL suite passed 5/5, including retained-V126.2 row preservation and denial; direct PostgreSQL proof that a newly recorded cleanup deadline cannot be changed remains a tracked gap. Bounded cleanup and late revocation remain incomplete. StartSession recovery accepts a 128 KiB authority bundle and 144 KiB binding/response within the 160 KiB envelope ceiling; the exact-head authorization repository suite passed 15/15 and covers fresh-install, ambiguous legacy-guard rejection, the 160 KiB storage edge, and retained maximum-size V126.2 ciphertext through V126.3 migration. This is bounded fixture proof and does not establish complete mTLS flow or runtime activation. Current receiving original-ACK PostgreSQL proof remains pending. The Account admission-protection acquisition, settlement, gRPC and repository sources are manually composed, but remain unregistered. Focused proof is recorded by the acquisition PostgreSQL, repository PostgreSQL, service unit and gRPC service unit suites linked above; this does not establish runtime registration, the downstream final-admission path, production authority or PKI, operational custody, or Entity placement and delivery. The World protected-activation consumer is also unregistered. The historical R9 report above records 13 Account PostgreSQL cases and four composed World/Account/Game Session cases, including exact authenticated World terminal settlement, with its missing tested-snapshot and original XML attribution stated explicitly. The separately source-bound receiving proof above qualifies only its named scope. These controlled upstream inputs establish no broader proof; runtime registration, genuine upstream authority, admission, Entity placement and delivery remain unproved. V1003 storage remains passive and V1004 lifecycle integrity checks do not authenticate World. V1004.1 and V1004.2 provide storage checks for nondecreasing lifecycle counters, retained PREPARING evidence, and canonical activation-request UUID spelling. V1004.3 requires canonical Base64 spellings for the tuple, projection, launch-read, and PREPARING lifecycle carriers at acquisition; its focused physical PostgreSQL and retained-row upgrade proof passes in the 25-case Account gate, including all 16 whitespace variants. These are controlled Account integrity checks; authenticated World production and runtime activation remain unproved. | | `AA-1.4` Commerce, subscriptions, purchases, donations, and platform fees | `partial` | `audited` | [Subscription management](../../architecture/microservices/account-service/subscription-management.md); [Stripe integration](../../architecture/microservices/account-service/stripe-integration.md); [Account runtime/data](../../architecture/microservices/account-service/runtime-and-data.md); [ADR 0143](../../architecture/decisions/adr-0143-stripe-v1-hosting-billing-and-deferred-creator-monetization.md) | [PaymentServiceImpl.java](../../../services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/impl/PaymentServiceImpl.java); [PurchaseWorkflowServiceImpl.java](../../../services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/impl/PurchaseWorkflowServiceImpl.java); [PaymentTransaction.java](../../../services/account-service/src/main/java/net/firedevops/firemud/accountservice/entity/PaymentTransaction.java); [Subscription.java](../../../services/account-service/src/main/java/net/firedevops/firemud/accountservice/entity/Subscription.java); [payment_service.proto](../../../protos/account/v1/payment_service.proto); [V2__payment_tables.sql](../../../services/account-service/src/main/resources/db/migration/V2__payment_tables.sql); [application.yml](../../../services/account-service/src/main/resources/application.yml) | [PaymentServiceImplTest.java](../../../services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/service/impl/PaymentServiceImplTest.java); [PaymentGrpcServiceTest.java](../../../services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/service/impl/PaymentGrpcServiceTest.java); [PurchaseWorkflowServiceImplTest.java](../../../services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/service/impl/PurchaseWorkflowServiceImplTest.java) | [Shared Runtime](./shared-runtime-contracts-and-persistence.md) | Incomplete subscription creation now fails closed before mutation instead of persisting a caller-selected locally active entitlement row. The target caller-bound billing-owner, stable request/digest, instrument, outbox, provider lifecycle/reconciliation, billing-safe owner transfer/deletion guards, and complete subscription-to-entitlement follow-through remain absent. Before first subscription creation can be enabled, Account must define the authoritative initial billing-owner source and consent/assignment workflow with a version/generation fence; no such source is selected, and caller-supplied account ID, tenant role, Creator Party, or payment-instrument ownership must not be inferred as that authority. The generic `CreatePaymentIntent`, `CreateDonation`, and `RefundPayment` RPCs fail closed with `FAILED_PRECONDITION` before `PaymentService` or provider invocation; the generic service/provider substrate remains unsupported. Creator/player purchases, donations, fees/shares, payouts, and settlement are deferred and not supported by current code. | | `AA-1.5` Entitlements, quotas, and hosting eligibility | `partial` | `drift-found` | [Subscription management](../../architecture/microservices/account-service/subscription-management.md); [Multi-tenancy](../../architecture/system-architecture-multi-tenancy.md); [Versioning and runtime](../../architecture/system-architecture-versioning-runtime.md); [ADR 0028](../../architecture/decisions/adr-0028-differentiated-entitlement-freshness.md) | [AccountServiceImpl.java](../../../services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/impl/AccountServiceImpl.java); [RuntimeEntitlementsDto.java](../../../services/account-service/src/main/java/net/firedevops/firemud/accountservice/dto/RuntimeEntitlementsDto.java); [Subscription.java](../../../services/account-service/src/main/java/net/firedevops/firemud/accountservice/entity/Subscription.java); [account_service.proto](../../../protos/account/v1/account_service.proto); [application.yml](../../../services/account-service/src/main/resources/application.yml) | [AccountServiceImplTest.java](../../../services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/service/impl/AccountServiceImplTest.java); [AccountGrpcServiceTest.java](../../../services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/service/impl/AccountGrpcServiceTest.java); [PublicBootstrapRoutesProdProfileTest.java](../../../services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/controller/PublicBootstrapRoutesProdProfileTest.java) | [Realm Routing](./realm-routing-and-playable-state.md); [Game Authoring](./game-authoring-publishing-and-activation.md) | The producer returns retryable `ENTITLEMENT_UNAVAILABLE` for zero or multiple tenant subscription rows and projects status only from exactly one explicit row; gRPC carries the unavailable outcome in its error field and HTTP bootstrap routes map it to 503. Focused Account proofs cover zero rows, conflicting active/canceled rows, gRPC classification, and connect-token retry after recovery without caching an unavailable receipt. Explicit free/trial row creation and authoritative current-row selection/constraint/history remain absent. The runtime response still lacks committed status and the full explicit entitlement/freshness evidence; its row-ID-derived version/sequence and newly stamped evaluation time, quotas, real sequencing/source freshness, caching/events, strict new-commitment enforcement, five-minute continuity, and instance lifecycle enforcement remain open. The target handoff between fresh connect-token reissuance and eligible exact-binding entitlement-only reconnect continuity is unresolved: token expiry can block that continuity before Account's resume lease, and no fallback reissuance path is authorized pending owner decision. Current `past_due` handling remains gameplay-available and public-join-eligible only when the sole explicit row is `past_due`. | -| `AA-2.1` Gameplay login, character selection, and session binding | `partial` | `drift-found` | [Authentication and authorization](../../architecture/system-architecture-authentication.md); [Session behavior](../../architecture/system-architecture-session-behavior.md); [ADR 0021](../../architecture/decisions/adr-0021-staged-player-authentication-and-gameplay-binding.md); [ADR 0122](../../architecture/decisions/adr-0122-stable-playable-state-namespaces-for-runtime-replacement.md); [ADR 0132](../../architecture/decisions/adr-0132-namespace-scoped-single-character-controller.md); [ADR 0140](../../architecture/decisions/adr-0140-realm-authored-controllable-actor-entry.md); [JWT and Token Contracts](../../architecture/system-architecture-jwt-and-token-contracts.md#game-session-original-attempt-coordination); [Gateway Architecture](../../architecture/system-architecture-gateway.md#gameplay-websocket-route) | [SessionAuthenticationService.java](../../../services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/service/SessionAuthenticationService.java); [PlayCommandHandler.java](../../../services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/command/text/PlayCommandHandler.java); [CanonicalGameplayMigrationDriverMain.java](../../../services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/repository/CanonicalGameplayMigrationDriverMain.java); [CanonicalGameplayMigrationDriverProtocol.java](../../../services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/repository/CanonicalGameplayMigrationDriverProtocol.java); [CanonicalGameplayMigrationDriverLauncher.java](../../../services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/repository/CanonicalGameplayMigrationDriverLauncher.java); [game-session-service build](../../../services/game-session-service/build.gradle.kts); [AccountGameplayCanonicalLoginOwner.java](../../../services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/session/AccountGameplayCanonicalLoginOwner.java); [AccountGameplayDelegationIssuanceRepository.java](../../../services/account-service/src/main/java/net/firedevops/firemud/accountservice/repository/AccountGameplayDelegationIssuanceRepository.java); [V147__account_gameplay_delegation_issuance.sql](../../../services/account-service/src/main/resources/db/migration/V147__account_gameplay_delegation_issuance.sql); [V157.1__account_gameplay_token_fence_truncate_guard.sql](../../../services/account-service/src/main/resources/db/migration/V157.1__account_gameplay_token_fence_truncate_guard.sql); [CanonicalGameplayRosterSelectionService.java](../../../services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/service/CanonicalGameplayRosterSelectionService.java); [AccountServiceImpl.java](../../../services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/impl/AccountServiceImpl.java); [GatewayFirstPartyConnectContextEnvelope.java](../../../services/common-security/src/main/java/net/firedevops/firemud/common/security/GatewayFirstPartyConnectContextEnvelope.java); [FirstPartyConnectContext.java](../../../services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/service/FirstPartyConnectContext.java); [FirstPartyConnectContextService.java](../../../services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/service/FirstPartyConnectContextService.java); [FirstPartyConnectContextRegistry.java](../../../services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/service/FirstPartyConnectContextRegistry.java); [FirstPartyConnectContextResolution.java](../../../services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/service/FirstPartyConnectContextResolution.java); [RedisFirstPartyConnectContextRegistry.java](../../../services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/service/impl/RedisFirstPartyConnectContextRegistry.java); [GameSessionWebSocketHandshakeInterceptor.java](../../../services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/websocket/GameSessionWebSocketHandshakeInterceptor.java); [GameSessionWebSocketHandler.java](../../../services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/websocket/GameSessionWebSocketHandler.java); [SessionRoutingNormalizationService.java](../../../services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/service/SessionRoutingNormalizationService.java); [InitialGameplayLoginOwner.java](../../../services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/service/InitialGameplayLoginOwner.java); [CanonicalGameplayLoginAccountClient.java](../../../services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/client/CanonicalGameplayLoginAccountClient.java); [CanonicalGameplayLoginResult.java](../../../services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/dto/CanonicalGameplayLoginResult.java); [GameplayHandshakeFilter.java](../../../services/spring-cloud-gateway/src/main/java/net/firedevops/firemud/springcloudgateway/filter/GameplayHandshakeFilter.java); [GameplayRouteReadinessHealthIndicator.java](../../../services/spring-cloud-gateway/src/main/java/net/firedevops/firemud/springcloudgateway/health/GameplayRouteReadinessHealthIndicator.java); [FirstPartyConnectContextConfig.java](../../../services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/config/FirstPartyConnectContextConfig.java); [FirstPartyConnectContextProperties.java](../../../services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/config/FirstPartyConnectContextProperties.java); [CanonicalPlayerRouteReadService.java](../../../services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/service/CanonicalPlayerRouteReadService.java); [SessionContext.java](../../../services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/service/SessionContext.java); [RedisSessionContextService.java](../../../services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/service/impl/RedisSessionContextService.java); [ActiveTransportSessionRegistry.java](../../../services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/service/ActiveTransportSessionRegistry.java); [InMemoryActiveTransportSessionRegistry.java](../../../services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/service/impl/InMemoryActiveTransportSessionRegistry.java); [CommunicationRecipientDeliveryService.java](../../../services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/service/CommunicationRecipientDeliveryService.java); [PlayerOutputDeliveryService.java](../../../services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/service/PlayerOutputDeliveryService.java) | [SessionResumptionFlowTest.java](../../../services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/command/text/SessionResumptionFlowTest.java); [CanonicalGameplayMigrationDriverMainTest.java](../../../services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/repository/CanonicalGameplayMigrationDriverMainTest.java); [CanonicalGameplayMigrationDriverProtocolTest.java](../../../services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/repository/CanonicalGameplayMigrationDriverProtocolTest.java); [CanonicalGameplayMigrationDriverStdoutTest.java](../../../services/game-session-service/src/test/java/net/firedevops/firemud/gamesession/repository/CanonicalGameplayMigrationDriverStdoutTest.java); [migration-driver image contract](../../../dev-tools/tests/game-session-migration-driver-image-contract.sh); [V34.3 PostgreSQL fixture](../../../services/game-session-service/src/test/java/integration/net/firedevops/firemud/gamesession/repository/CanonicalGameplayInitialAdmissionIntentRequestIdMigrationIntegrationTest.java); [AccountGameplayCanonicalLoginOwnerTest.java](../../../services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/service/session/AccountGameplayCanonicalLoginOwnerTest.java); [AccountGameplayDelegationIssuancePersistenceIntegrationTest.java](../../../services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/repository/AccountGameplayDelegationIssuancePersistenceIntegrationTest.java); [CanonicalGameplayRosterSelectionServiceTest.java](../../../services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/service/CanonicalGameplayRosterSelectionServiceTest.java); [GatewayFirstPartyConnectContextEnvelopeTest.java](../../../services/common-security/src/test/java/unit/net/firedevops/firemud/common/security/GatewayFirstPartyConnectContextEnvelopeTest.java); [AccountServiceImplTest.java](../../../services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/service/impl/AccountServiceImplTest.java); [AuthControllerTest.java](../../../services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/controller/AuthControllerTest.java); [FirstPartyConnectContextServiceTest.java](../../../services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/service/FirstPartyConnectContextServiceTest.java); [FirstPartyConnectContextResolutionTest.java](../../../services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/service/FirstPartyConnectContextResolutionTest.java); [RedisFirstPartyConnectContextRegistryTest.java](../../../services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/service/impl/RedisFirstPartyConnectContextRegistryTest.java); [GameSessionWebSocketHandshakeInterceptorTest.java](../../../services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/websocket/GameSessionWebSocketHandshakeInterceptorTest.java); [GameSessionWebSocketHandlerTest.java](../../../services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/websocket/GameSessionWebSocketHandlerTest.java); [InitialGameplayLoginOwnerTest.java](../../../services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/service/InitialGameplayLoginOwnerTest.java); [InitialGameplayLoginContextRedisIntegrationTest.java](../../../services/game-session-service/src/test/java/integration/net/firedevops/firemud/gamesession/service/InitialGameplayLoginContextRedisIntegrationTest.java); [CanonicalGameplayLoginAccountClientTest.java](../../../services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/client/CanonicalGameplayLoginAccountClientTest.java); [CanonicalGameplayLoginResultTest.java](../../../services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/dto/CanonicalGameplayLoginResultTest.java); [GameplayHandshakeFilterTest.java](../../../services/spring-cloud-gateway/src/test/java/unit/net/firedevops/firemud/springcloudgateway/filter/GameplayHandshakeFilterTest.java); [GameplayRouteReadinessHealthIndicatorTest.java](../../../services/spring-cloud-gateway/src/test/java/unit/net/firedevops/firemud/springcloudgateway/health/GameplayRouteReadinessHealthIndicatorTest.java); [CanonicalPlayerRouteReadServiceTest.java](../../../services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/service/CanonicalPlayerRouteReadServiceTest.java); [RedisSessionContextServiceTest.java](../../../services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/service/impl/RedisSessionContextServiceTest.java); [SessionContextTest.java](../../../services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/service/SessionContextTest.java); [InitialGameplayLoginCoordinationJournalRepositoryIntegrationTest.java](../../../services/game-session-service/src/test/java/integration/net/firedevops/firemud/gamesession/repository/InitialGameplayLoginCoordinationJournalRepositoryIntegrationTest.java); [InMemoryActiveTransportSessionRegistryTest.java](../../../services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/service/impl/InMemoryActiveTransportSessionRegistryTest.java); [CommunicationRecipientDeliveryServiceTest.java](../../../services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/service/CommunicationRecipientDeliveryServiceTest.java); [PlayerOutputDeliveryServiceTest.java](../../../services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/service/PlayerOutputDeliveryServiceTest.java) | [Realm Routing](./realm-routing-and-playable-state.md); [Player Experience](./player-experience-commands-and-communication.md) | Gameplay admission and binding remain partial. Exact-head execution scope and fixture results, including the V34.3 fixture pass, are recorded in the [consolidated proof record](#consolidated-exact-head-and-historical-proof). This verifies the tested migration fixture, not namespace-aware atomic takeover: that remains incomplete, as do issuer-index and region reconciliation and retained-binding inventory/conversion. Final immutable image build and authority, trusted bootstrap/execution, and live playable proof remain unproved. Current `/auth/connect-token` validates existing bootstrap and scope, then returns `AUTH_UNAVAILABLE` before cached-success replay, token minting, or replay/session mutation. The canonical Account producer, shared replay fence, dedicated Gateway signing keys, and deployment qualification remain unavailable. Game Session retains complete signed-context, canonical-route/private-handle, and retention sources, but public first-party bare `LOGIN`/`PLAY` deny before legacy Account, Entity, or binding effects; partial selectors never provide fallback. Generic credential LOGIN/PLAY and retained-edge rebind remain separate behavior, and earlier first-party happy-handshake/reconnect proofs are historical. Synthetic actor fallback, descriptor/template resolution, and fork-local identity proof remain gaps under [ADR 0140](../../architecture/decisions/adr-0140-realm-authored-controllable-actor-entry.md) and the [Game Session persisted-actor boundary](../../architecture/microservices/game-session-service/runtime-and-data.md#persisted-actor-admission-boundary). Deployment/mTLS and fresh-image proof for gameplay admission remain incomplete; gameplay completion under #2967/#2898 remains open. Live no-key disposal remains fail-closed pending the protected retained binding-history/restore-continuity producer tracked with `PO-3.4` in [Platform Operations](./platform-operations-and-delivery.md#capability-status). The initial private gameplay LOGIN now has local unregistered composition source; runtime caller registration and authentication, deployed ACL/TLS and signer custody, missing-Account decoy timing parity, and singleton source-fence allocator throughput remain open (see [source-intake status](#initial-private-gameplay-login-issuance-source-intake)). The default-off roster selection source has no player-command caller; `PLAY`/`LOOK` activation and live owner-RPC execution remain unproved, so `AA-2.1` stays partial. | +| `AA-2.1` Gameplay login, character selection, and session binding | `partial` | `drift-found` | [Authentication and authorization](../../architecture/system-architecture-authentication.md); [Session behavior](../../architecture/system-architecture-session-behavior.md); [ADR 0021](../../architecture/decisions/adr-0021-staged-player-authentication-and-gameplay-binding.md); [ADR 0122](../../architecture/decisions/adr-0122-stable-playable-state-namespaces-for-runtime-replacement.md); [ADR 0132](../../architecture/decisions/adr-0132-namespace-scoped-single-character-controller.md); [ADR 0140](../../architecture/decisions/adr-0140-realm-authored-controllable-actor-entry.md); [JWT and Token Contracts](../../architecture/system-architecture-jwt-and-token-contracts.md#game-session-original-attempt-coordination); [Gateway Architecture](../../architecture/system-architecture-gateway.md#gameplay-websocket-route) | [SessionAuthenticationService.java](../../../services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/service/SessionAuthenticationService.java); [PlayCommandHandler.java](../../../services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/command/text/PlayCommandHandler.java); [CanonicalGameplayMigrationDriverMain.java](../../../services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/repository/CanonicalGameplayMigrationDriverMain.java); [CanonicalGameplayMigrationDriverProtocol.java](../../../services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/repository/CanonicalGameplayMigrationDriverProtocol.java); [CanonicalGameplayMigrationDriverLauncher.java](../../../services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/repository/CanonicalGameplayMigrationDriverLauncher.java); [game-session-service build](../../../services/game-session-service/build.gradle.kts); [AccountGameplayCanonicalLoginOwner.java](../../../services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/session/AccountGameplayCanonicalLoginOwner.java); [AccountGameplayDelegationIssuanceRepository.java](../../../services/account-service/src/main/java/net/firedevops/firemud/accountservice/repository/AccountGameplayDelegationIssuanceRepository.java); [V147__account_gameplay_delegation_issuance.sql](../../../services/account-service/src/main/resources/db/migration/V147__account_gameplay_delegation_issuance.sql); [V157.1__account_gameplay_token_fence_truncate_guard.sql](../../../services/account-service/src/main/resources/db/migration/V157.1__account_gameplay_token_fence_truncate_guard.sql); [CanonicalGameplayRosterSelectionService.java](../../../services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/service/CanonicalGameplayRosterSelectionService.java); [AccountServiceImpl.java](../../../services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/impl/AccountServiceImpl.java); [GatewayFirstPartyConnectContextEnvelope.java](../../../services/common-security/src/main/java/net/firedevops/firemud/common/security/GatewayFirstPartyConnectContextEnvelope.java); [FirstPartyConnectContext.java](../../../services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/service/FirstPartyConnectContext.java); [FirstPartyConnectContextService.java](../../../services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/service/FirstPartyConnectContextService.java); [FirstPartyConnectContextRegistry.java](../../../services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/service/FirstPartyConnectContextRegistry.java); [FirstPartyConnectContextResolution.java](../../../services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/service/FirstPartyConnectContextResolution.java); [RedisFirstPartyConnectContextRegistry.java](../../../services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/service/impl/RedisFirstPartyConnectContextRegistry.java); [GameSessionWebSocketHandshakeInterceptor.java](../../../services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/websocket/GameSessionWebSocketHandshakeInterceptor.java); [GameSessionWebSocketHandler.java](../../../services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/websocket/GameSessionWebSocketHandler.java); [SessionRoutingNormalizationService.java](../../../services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/service/SessionRoutingNormalizationService.java); [InitialGameplayLoginOwner.java](../../../services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/service/InitialGameplayLoginOwner.java); [CanonicalGameplayLoginAccountClient.java](../../../services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/client/CanonicalGameplayLoginAccountClient.java); [CanonicalGameplayLoginResult.java](../../../services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/dto/CanonicalGameplayLoginResult.java); [GameplayHandshakeFilter.java](../../../services/spring-cloud-gateway/src/main/java/net/firedevops/firemud/springcloudgateway/filter/GameplayHandshakeFilter.java); [GameplayRouteReadinessHealthIndicator.java](../../../services/spring-cloud-gateway/src/main/java/net/firedevops/firemud/springcloudgateway/health/GameplayRouteReadinessHealthIndicator.java); [FirstPartyConnectContextConfig.java](../../../services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/config/FirstPartyConnectContextConfig.java); [FirstPartyConnectContextProperties.java](../../../services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/config/FirstPartyConnectContextProperties.java); [CanonicalPlayerRouteReadService.java](../../../services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/service/CanonicalPlayerRouteReadService.java); [SessionContext.java](../../../services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/service/SessionContext.java); [RedisSessionContextService.java](../../../services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/service/impl/RedisSessionContextService.java); [ActiveTransportSessionRegistry.java](../../../services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/service/ActiveTransportSessionRegistry.java); [InMemoryActiveTransportSessionRegistry.java](../../../services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/service/impl/InMemoryActiveTransportSessionRegistry.java); [CommunicationRecipientDeliveryService.java](../../../services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/service/CommunicationRecipientDeliveryService.java); [PlayerOutputDeliveryService.java](../../../services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/service/PlayerOutputDeliveryService.java); [CanonicalGameplayIssuerAdmissionControlRepository.java](../../../services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/repository/CanonicalGameplayIssuerAdmissionControlRepository.java); [CanonicalGameplayIssuerAdmissionBarrierRepository.java](../../../services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/repository/CanonicalGameplayIssuerAdmissionBarrierRepository.java); [CanonicalGameplayIssuerBindingLocalAcknowledgementRepository.java](../../../services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/repository/CanonicalGameplayIssuerBindingLocalAcknowledgementRepository.java); [V1045__canonical_issuer_binding_local_acknowledgement.sql](../../../services/game-session-service/src/main/resources/db/migration/V1045__canonical_issuer_binding_local_acknowledgement.sql); [V1046__canonical_issuer_live_admission_control.sql](../../../services/game-session-service/src/main/resources/db/migration/V1046__canonical_issuer_live_admission_control.sql) | [SessionResumptionFlowTest.java](../../../services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/command/text/SessionResumptionFlowTest.java); [CanonicalGameplayMigrationDriverMainTest.java](../../../services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/repository/CanonicalGameplayMigrationDriverMainTest.java); [CanonicalGameplayMigrationDriverProtocolTest.java](../../../services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/repository/CanonicalGameplayMigrationDriverProtocolTest.java); [CanonicalGameplayMigrationDriverStdoutTest.java](../../../services/game-session-service/src/test/java/net/firedevops/firemud/gamesession/repository/CanonicalGameplayMigrationDriverStdoutTest.java); [migration-driver image contract](../../../dev-tools/tests/game-session-migration-driver-image-contract.sh); [V34.3 PostgreSQL fixture](../../../services/game-session-service/src/test/java/integration/net/firedevops/firemud/gamesession/repository/CanonicalGameplayInitialAdmissionIntentRequestIdMigrationIntegrationTest.java); [AccountGameplayCanonicalLoginOwnerTest.java](../../../services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/service/session/AccountGameplayCanonicalLoginOwnerTest.java); [AccountGameplayDelegationIssuancePersistenceIntegrationTest.java](../../../services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/repository/AccountGameplayDelegationIssuancePersistenceIntegrationTest.java); [CanonicalGameplayRosterSelectionServiceTest.java](../../../services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/service/CanonicalGameplayRosterSelectionServiceTest.java); [GatewayFirstPartyConnectContextEnvelopeTest.java](../../../services/common-security/src/test/java/unit/net/firedevops/firemud/common/security/GatewayFirstPartyConnectContextEnvelopeTest.java); [AccountServiceImplTest.java](../../../services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/service/impl/AccountServiceImplTest.java); [AuthControllerTest.java](../../../services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/controller/AuthControllerTest.java); [FirstPartyConnectContextServiceTest.java](../../../services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/service/FirstPartyConnectContextServiceTest.java); [FirstPartyConnectContextResolutionTest.java](../../../services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/service/FirstPartyConnectContextResolutionTest.java); [RedisFirstPartyConnectContextRegistryTest.java](../../../services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/service/impl/RedisFirstPartyConnectContextRegistryTest.java); [GameSessionWebSocketHandshakeInterceptorTest.java](../../../services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/websocket/GameSessionWebSocketHandshakeInterceptorTest.java); [GameSessionWebSocketHandlerTest.java](../../../services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/websocket/GameSessionWebSocketHandlerTest.java); [InitialGameplayLoginOwnerTest.java](../../../services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/service/InitialGameplayLoginOwnerTest.java); [InitialGameplayLoginContextRedisIntegrationTest.java](../../../services/game-session-service/src/test/java/integration/net/firedevops/firemud/gamesession/service/InitialGameplayLoginContextRedisIntegrationTest.java); [CanonicalGameplayLoginAccountClientTest.java](../../../services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/client/CanonicalGameplayLoginAccountClientTest.java); [CanonicalGameplayLoginResultTest.java](../../../services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/dto/CanonicalGameplayLoginResultTest.java); [GameplayHandshakeFilterTest.java](../../../services/spring-cloud-gateway/src/test/java/unit/net/firedevops/firemud/springcloudgateway/filter/GameplayHandshakeFilterTest.java); [GameplayRouteReadinessHealthIndicatorTest.java](../../../services/spring-cloud-gateway/src/test/java/unit/net/firedevops/firemud/springcloudgateway/health/GameplayRouteReadinessHealthIndicatorTest.java); [CanonicalPlayerRouteReadServiceTest.java](../../../services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/service/CanonicalPlayerRouteReadServiceTest.java); [RedisSessionContextServiceTest.java](../../../services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/service/impl/RedisSessionContextServiceTest.java); [SessionContextTest.java](../../../services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/service/SessionContextTest.java); [InitialGameplayLoginCoordinationJournalRepositoryIntegrationTest.java](../../../services/game-session-service/src/test/java/integration/net/firedevops/firemud/gamesession/repository/InitialGameplayLoginCoordinationJournalRepositoryIntegrationTest.java); [InMemoryActiveTransportSessionRegistryTest.java](../../../services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/service/impl/InMemoryActiveTransportSessionRegistryTest.java); [CommunicationRecipientDeliveryServiceTest.java](../../../services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/service/CommunicationRecipientDeliveryServiceTest.java); [PlayerOutputDeliveryServiceTest.java](../../../services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/service/PlayerOutputDeliveryServiceTest.java); [CanonicalGameplayIssuerAdmissionBarrierRepositoryIntegrationTest.java](../../../services/game-session-service/src/test/java/integration/net/firedevops/firemud/gamesession/repository/CanonicalGameplayIssuerAdmissionBarrierRepositoryIntegrationTest.java); [CanonicalGameplayIssuerBindingLocalRedisOwnerIntegrationTest.java](../../../services/game-session-service/src/test/java/integration/net/firedevops/firemud/gamesession/repository/CanonicalGameplayIssuerBindingLocalRedisOwnerIntegrationTest.java); R849 partial execution, R855/R856 recovery, R867 and R902 focused execution have separate scopes and limits recorded above | [Realm Routing](./realm-routing-and-playable-state.md); [Player Experience](./player-experience-commands-and-communication.md) | Gameplay admission and binding remain partial. Exact-head execution scope and fixture results, including the V34.3 fixture pass, are recorded in the [consolidated proof record](#consolidated-exact-head-and-historical-proof). This verifies the tested migration fixture, not namespace-aware atomic takeover: that remains incomplete, as do issuer-index and region reconciliation and retained-binding inventory/conversion. Final immutable image build and authority, trusted bootstrap/execution, and live playable proof remain unproved. Current `/auth/connect-token` validates existing bootstrap and scope, then returns `AUTH_UNAVAILABLE` before cached-success replay, token minting, or replay/session mutation. The canonical Account producer, shared replay fence, dedicated Gateway signing keys, and deployment qualification remain unavailable. Game Session retains complete signed-context, canonical-route/private-handle, and retention sources, but public first-party bare `LOGIN`/`PLAY` deny before legacy Account, Entity, or binding effects; partial selectors never provide fallback. Generic credential LOGIN/PLAY and retained-edge rebind remain separate behavior, and earlier first-party happy-handshake/reconnect proofs are historical. Synthetic actor fallback, descriptor/template resolution, and fork-local identity proof remain gaps under [ADR 0140](../../architecture/decisions/adr-0140-realm-authored-controllable-actor-entry.md) and the [Game Session persisted-actor boundary](../../architecture/microservices/game-session-service/runtime-and-data.md#persisted-actor-admission-boundary). Deployment/mTLS and fresh-image proof for gameplay admission remain incomplete; gameplay completion under #2967/#2898 remains open. Live no-key disposal remains fail-closed pending the protected retained binding-history/restore-continuity producer tracked with `PO-3.4` in [Platform Operations](./platform-operations-and-delivery.md#capability-status). The initial private gameplay LOGIN now has local unregistered composition source; runtime caller registration and authentication, deployed ACL/TLS and signer custody, missing-Account decoy timing parity, and singleton source-fence allocator throughput remain open (see [source-intake status](#initial-private-gameplay-login-issuance-source-intake)). The default-off roster selection source has no player-command caller; `PLAY`/`LOOK` activation and live owner-RPC execution remain unproved, so `AA-2.1` stays partial. Issuer LIVE/OPEN/cutoff and INITIAL Account components are manually composed prerequisites, not complete original NEW or playable admission; custody, default registration, final admission and activation remain unqualified as recorded in the [readiness scope and proof](#canonical-new-admission-components). | | `AA-2.2` Reconnect, resume eligibility, and cross-device continuity | `partial` | `drift-found` | [Reconnection](../../architecture/system-architecture-reconnection.md); [Session behavior](../../architecture/system-architecture-session-behavior.md); [Redis architecture](../../architecture/system-architecture-redis.md); [ADR 0019](../../architecture/decisions/adr-0019-separate-active-session-resume-and-transcript-lifetimes.md); [ADR 0132](../../architecture/decisions/adr-0132-namespace-scoped-single-character-controller.md); [ADR 0133](../../architecture/decisions/adr-0133-fresh-edge-reconnect-without-client-input-replay.md); [ADR 0134](../../architecture/decisions/adr-0134-bounded-durable-semantic-reconnect-context.md) | [SessionAuthenticationService.java](../../../services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/service/SessionAuthenticationService.java); [RedisSessionContextService.java](../../../services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/service/impl/RedisSessionContextService.java); [DurableScreenBufferService.java](../../../services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/service/DurableScreenBufferService.java); [GameplayWebSocketBridgeHandler.java](../../../services/spring-cloud-gateway/src/main/java/net/firedevops/firemud/springcloudgateway/websocket/GameplayWebSocketBridgeHandler.java); [FirstPartyConnectContextService.java](../../../services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/service/FirstPartyConnectContextService.java); [EffectiveReconnectionSettingsResolver.java](../../../services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/config/EffectiveReconnectionSettingsResolver.java) | [SessionResumptionFlowTest.java](../../../services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/command/text/SessionResumptionFlowTest.java); [LookWebSocketCrossServiceTest.java](../../../services/game-session-service/src/test/java/crossservice/net/firedevops/firemud/gamesession/LookWebSocketCrossServiceTest.java); [GameSessionWebSocketHandlerIntegrationTest.java](../../../services/game-session-service/src/test/java/integration/net/firedevops/firemud/gamesession/websocket/GameSessionWebSocketHandlerIntegrationTest.java); [Telnet cross-service test](../../../services/tcp-proxy-service/src/test/java/crossservice/net/firedevops/firemud/tcpproxy/TelnetGatewayGameSessionAccountCrossServiceIntegrationTest.java) | [Player Experience](./player-experience-commands-and-communication.md); [Shared Runtime](./shared-runtime-contracts-and-persistence.md); [Platform Operations](./platform-operations-and-delivery.md) | Generic resume, bounded semantic context, and edge rebind exist, but the effective disconnected-resume window is resolved without `PLAY` enforcement; namespace-aware binding/transfer, complete authenticated real-service replacement, lifecycle/presence/stalled-input outcomes, first-party post-logout replay suppression, and proof of fresh-edge `LOOK`/prompt behavior are not complete or proved. The earlier first-party post-logout replay defect is historical: current first-party `LOGIN` and `PLAY` deny before legacy effects while the genuine context consumers remain unavailable. Successful post-logout replay suppression and a complete playable flow remain unproved. Fresh edge reconnect must not replay client input/bytes/frames and must end with fresh `LOOK` plus exactly one reconnect prompt when both effective reconnect-prompt settings are enabled, or zero reconnect prompts when either is disabled. Full token refresh, membership-version and membership-authority-generation persistence, revocation, and non-edge restart continuity remain. See AA-2.1 for the finite namespace controller-index migration-driver prefix, its implementation and proof anchors, and the unproved physical PostgreSQL/Redis, final-image, and trusted-bootstrap/execution gates. | | `AA-2.3` Takeover, logout, idle expiry, and revocation | `partial` | `drift-found` | [Session behavior](../../architecture/system-architecture-session-behavior.md); [Reconnection](../../architecture/system-architecture-reconnection.md); [ADR 0132](../../architecture/decisions/adr-0132-namespace-scoped-single-character-controller.md) | [PlayCommandHandler.java](../../../services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/command/text/PlayCommandHandler.java); [LogoutCommandHandler.java](../../../services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/command/text/LogoutCommandHandler.java); [RedisSessionContextService.java](../../../services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/service/impl/RedisSessionContextService.java); [TelnetServerHandler.java](../../../services/tcp-proxy-service/src/main/java/net/firedevops/firemud/tcpproxy/telnet/TelnetServerHandler.java); [application.yml](../../../services/game-session-service/src/main/resources/application.yml) | [SessionResumptionFlowTest.java](../../../services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/command/text/SessionResumptionFlowTest.java); [LogoutCommandHandlerTest.java](../../../services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/command/text/LogoutCommandHandlerTest.java); [LookWebSocketCrossServiceTest.java](../../../services/game-session-service/src/test/java/crossservice/net/firedevops/firemud/gamesession/LookWebSocketCrossServiceTest.java) | [Player Experience](./player-experience-commands-and-communication.md); [World Runtime](./world-runtime-and-movement.md); [Gameplay Rules](./gameplay-rules-entities-and-effects.md); [Shared Runtime](./shared-runtime-contracts-and-persistence.md) | Gameplay takeover/LOGOUT and transport idle-close handling exist; target takeover requires namespace-scoped atomic monotonic `bindingGeneration`, old-input fencing, and preservation of already-admitted work as defined by [ADR 0132](../../architecture/decisions/adr-0132-namespace-scoped-single-character-controller.md), while Account control-plane logout/authority-generation workflows, full idle/session expiry convergence, and first-party post-logout replay cleanup are absent. | diff --git a/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/repository/CanonicalGameplayAccountAdmissionBarrierRepository.java b/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/repository/CanonicalGameplayAccountAdmissionBarrierRepository.java index 805d6cf439..00e8e8da2f 100644 --- a/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/repository/CanonicalGameplayAccountAdmissionBarrierRepository.java +++ b/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/repository/CanonicalGameplayAccountAdmissionBarrierRepository.java @@ -627,6 +627,27 @@ private static List capt + " ON i.binding_ref = t.candidate_binding_ref" + " WHERE o.account_id = ? ORDER BY o.operation_id", accountId); + appendRows( + rows, + transaction, + CanonicalGameplayAccountAdmissionFenceIntent.CohortKind.INITIALIZER, + "SELECT i.original_request_id::text AS source_key, t.tenant_id," + + " t.playable_state_namespace_id, to_jsonb(i)::text AS source_record_json" + + " FROM game_session_canonical_initial_account_barrier_initializer i" + + " JOIN game_session_canonical_initial_account_barrier_target t" + + " ON t.initializer_id = i.initializer_id" + + " AND t.original_request_id = i.original_request_id" + + " WHERE i.account_id = ? ORDER BY i.original_request_id", + accountId); + appendRows( + rows, + transaction, + CanonicalGameplayAccountAdmissionFenceIntent.CohortKind.INITIAL_TARGET, + "SELECT t.initializer_id::text || ':' || t.target_ordinal::text AS source_key," + + " t.tenant_id, t.playable_state_namespace_id, to_jsonb(t)::text AS source_record_json" + + " FROM game_session_canonical_initial_account_barrier_target t" + + " WHERE t.account_id = ? ORDER BY t.initializer_id, t.target_ordinal", + accountId); return List.copyOf(rows); } @@ -693,6 +714,9 @@ private static void appendRows( + " LEFT JOIN game_session_canonical_gameplay_binding_inventory i" + " ON i.binding_ref = t.candidate_binding_ref" + " WHERE o.account_id = ?" + + " UNION ALL SELECT t.tenant_id, t.playable_state_namespace_id" + + " FROM game_session_canonical_initial_account_barrier_target t" + + " WHERE t.account_id = ?" + ") account_scopes" + " ORDER BY tenant_id, playable_state_namespace_id", accountId, @@ -701,6 +725,7 @@ private static void appendRows( accountId, accountId, accountId, + accountId, accountId); var targets = new ArrayList(); for (Record row : rows) { diff --git a/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/repository/CanonicalGameplayAccountAdmissionFenceIntent.java b/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/repository/CanonicalGameplayAccountAdmissionFenceIntent.java index 8d805921c8..e3a0286ce1 100644 --- a/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/repository/CanonicalGameplayAccountAdmissionFenceIntent.java +++ b/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/repository/CanonicalGameplayAccountAdmissionFenceIntent.java @@ -22,7 +22,9 @@ public enum CohortKind { ISSUER_OBLIGATION, REGION_OBLIGATION, MEMBER_REPAIR_CONTROL, - MEMBER_REPAIR_OPERATION + MEMBER_REPAIR_OPERATION, + INITIALIZER, + INITIAL_TARGET } private final UUID operationId; diff --git a/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/repository/CanonicalGameplayAccountInitialBarrierInitializerRepository.java b/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/repository/CanonicalGameplayAccountInitialBarrierInitializerRepository.java new file mode 100644 index 0000000000..ed4281cef3 --- /dev/null +++ b/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/repository/CanonicalGameplayAccountInitialBarrierInitializerRepository.java @@ -0,0 +1,982 @@ +package net.firedevops.firemud.gamesession.repository; + +import java.math.BigDecimal; +import java.math.BigInteger; +import java.security.MessageDigest; +import java.security.NoSuchAlgorithmException; +import java.time.Clock; +import java.util.HexFormat; +import java.util.LinkedHashMap; +import java.util.Map; +import java.util.Objects; +import java.util.UUID; +import net.firedevops.firemud.gamesession.dto.CanonicalGameplayLoginResult; +import net.firedevops.firemud.gamesession.dto.InitialGameplayLoginAttemptCoordinates; +import org.jooq.DSLContext; +import org.jooq.Record; +import org.jooq.impl.DSL; +import org.springframework.transaction.support.TransactionSynchronizationManager; +import tools.jackson.databind.json.JsonMapper; + +/** + * Unregistered SQL owner for a single original-attempt INITIAL account barrier target. + * + *

This owner serializes with account-wide acquisition through inventory-clock then existing + * account-control locks. It never inserts missing account control and never changes Account token, + * admission-lease, or finalization authority. + */ +final class CanonicalGameplayAccountInitialBarrierInitializerRepository { + private static final String CONTROL = "game_session_canonical_account_coverage_control"; + private static final String INVENTORY_CLOCK = "game_session_canonical_binding_inventory_clock"; + private static final String ORIGINAL = "game_session_initial_gameplay_login_journal"; + private static final String INITIALIZER = + "game_session_canonical_initial_account_barrier_initializer"; + private static final String TARGET = "game_session_canonical_initial_account_barrier_target"; + private static final String NO_ACTIVE = "NO_ACTIVE_ACCOUNT_WIDE_FLOW"; + private static final JsonMapper JSON = JsonMapper.builder().build(); + + private final DSLContext dsl; + private final Clock clock; + + CanonicalGameplayAccountInitialBarrierInitializerRepository(DSLContext dsl) { + this(dsl, Clock.systemUTC()); + } + + CanonicalGameplayAccountInitialBarrierInitializerRepository(DSLContext dsl, Clock clock) { + this.dsl = Objects.requireNonNull(dsl, "dsl"); + this.clock = Objects.requireNonNull(clock, "clock"); + } + + /** + * Captures one exact initial target under the same inventory-clock then account-control order + * used by account-wide acquisition. The Account account id is taken from the authenticated + * result. + */ + InitializerSnapshot beginOrRead( + InitialGameplayLoginAttemptCoordinates original, + CanonicalGameplayLoginResult accountLogin, + UUID tenantId, + UUID playableStateNamespaceId) { + Objects.requireNonNull(original, "original attempt"); + Objects.requireNonNull(accountLogin, "authenticated Account LOGIN result"); + requireNonNil(tenantId, "tenantId"); + requireNonNil(playableStateNamespaceId, "playableStateNamespaceId"); + requireNoAmbientTransaction(); + CanonicalGameplayLoginResult.NonSecretEvidence accountEvidence = accountLogin.evidence(); + requireOriginalEvidence(original, accountEvidence); + String accountEvidenceDigest = digestAccountEvidence(accountEvidence); + + return dsl.transactionResult( + configuration -> { + DSLContext transaction = DSL.using(configuration); + BigInteger inventoryRevision = lockInventoryRevision(transaction); + Record control = lockExistingControl(transaction, accountEvidence.accountId()); + AccountControlSource source = readNoActiveControl(control, accountEvidence.accountId()); + if (inventoryRevision.signum() <= 0) { + throw conflict( + "Initial account barrier requires positive canonical inventory revision"); + } + requireExactOriginalLogin(transaction, original, accountEvidence); + + Record prior = readInitializer(transaction, original.requestId(), true); + if (prior != null) { + InitializerSnapshot snapshot = toSnapshot(prior); + requireSameOriginalTarget( + snapshot, + original, + accountEvidence.accountId(), + tenantId, + playableStateNamespaceId, + accountEvidenceDigest); + requireSameCurrentSource(snapshot, source); + return snapshot; + } + + UUID initializerId = randomNonNilUuid(); + while (initializerId.equals(original.requestId()) + || initializerId.equals(original.callerContextId()) + || initializerId.equals(accountEvidence.accountId())) { + initializerId = randomNonNilUuid(); + } + transaction.execute( + "INSERT INTO " + + INITIALIZER + + " (initializer_id, original_request_id, original_caller_context_id," + + " original_attempt_fence, account_id, account_login_evidence_digest," + + " source_control_state, source_control_epoch, inventory_snapshot_revision," + + " source_control_digest) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?)", + initializerId, + original.requestId(), + original.callerContextId(), + original.expectedAttemptFence(), + accountEvidence.accountId(), + accountEvidenceDigest, + NO_ACTIVE, + new BigDecimal(source.epoch()), + new BigDecimal(inventoryRevision), + source.digest()); + transaction.execute( + "INSERT INTO " + + TARGET + + " (initializer_id, original_request_id, account_id, target_ordinal, tenant_id," + + " playable_state_namespace_id, target_state)" + + " VALUES (?, ?, ?, 0, ?, ?, 'NEVER_DISPATCHED')", + initializerId, + original.requestId(), + accountEvidence.accountId(), + tenantId, + playableStateNamespaceId); + Record created = readInitializer(transaction, original.requestId(), true); + if (created == null) throw conflict("Initial account barrier target readback is missing"); + InitializerSnapshot snapshot = toSnapshot(created); + requireSameOriginalTarget( + snapshot, + original, + accountEvidence.accountId(), + tenantId, + playableStateNamespaceId, + accountEvidenceDigest); + requireSameCurrentSource(snapshot, source); + return snapshot; + }); + } + + /** Reads the exact live owner context for protected INITIAL incarnation observation. */ + InitialObservationContext readCurrentObservationContext(UUID originalRequestId) { + requireNonNil(originalRequestId, "originalRequestId"); + requireNoAmbientTransaction(); + return dsl.transactionResult( + configuration -> { + DSLContext transaction = DSL.using(configuration); + transaction.execute("SET TRANSACTION ISOLATION LEVEL REPEATABLE READ READ ONLY"); + Record row = readInitializer(transaction, originalRequestId, false); + if (row == null) throw conflict("Exact original INITIAL account target is missing"); + InitializerSnapshot snapshot = toSnapshot(row); + AccountControlSource current = + readCurrentNoActiveControl(transaction, snapshot.accountId()); + requireSameCurrentSource(snapshot, current); + if (snapshot.state() != State.OPEN_INSTALLED) { + requireOriginalJournalStillCurrent(transaction, snapshot); + } + return InitialObservationContext.from(snapshot); + }); + } + + InitializerSnapshot readCurrent(UUID originalRequestId) { + requireNonNil(originalRequestId, "originalRequestId"); + requireNoAmbientTransaction(); + return dsl.transactionResult( + configuration -> { + DSLContext transaction = DSL.using(configuration); + transaction.execute("SET TRANSACTION ISOLATION LEVEL REPEATABLE READ READ ONLY"); + InitializerSnapshot snapshot = readRequiredCurrent(transaction, originalRequestId, false); + AccountControlSource current = + readCurrentNoActiveControl(transaction, snapshot.accountId()); + requireSameCurrentSource(snapshot, current); + if (snapshot.state() != State.OPEN_INSTALLED) { + requireOriginalJournalStillCurrent(transaction, snapshot); + } + return snapshot; + }); + } + + /** + * Resolves exactly one retained installed INITIAL target by its physical account scope. The + * lookup is read-only and checks the target's captured positive NO_ACTIVE control tuple; it does + * not use original LOGIN liveness as storage authority or create a replacement target. + */ + InitializerSnapshot readInstalledOpenForTarget( + UUID accountId, UUID tenantId, UUID playableStateNamespaceId) { + requireNonNil(accountId, "accountId"); + requireNonNil(tenantId, "tenantId"); + requireNonNil(playableStateNamespaceId, "playableStateNamespaceId"); + requireNoAmbientTransaction(); + return dsl.transactionResult( + configuration -> { + DSLContext transaction = DSL.using(configuration); + transaction.execute("SET TRANSACTION ISOLATION LEVEL REPEATABLE READ READ ONLY"); + var rows = + transaction.fetch( + "SELECT i.initializer_id, i.original_request_id, i.original_caller_context_id," + + " i.original_attempt_fence, i.account_id, i.account_login_evidence_digest," + + " i.source_control_state, i.source_control_epoch," + + " i.inventory_snapshot_revision, i.source_control_digest, t.tenant_id," + + " t.playable_state_namespace_id, t.target_state," + + " t.before_accepted_attestation_digest, t.before_incarnation_digest," + + " t.before_source_payload_digest," + + " t.before_observation_issued_at_epoch_millis," + + " t.before_observation_observed_at_epoch_millis," + + " t.before_observation_expires_at_epoch_millis, t.installed_fields_digest" + + " FROM " + + INITIALIZER + + " i JOIN " + + TARGET + + " t ON t.initializer_id = i.initializer_id" + + " AND t.original_request_id = i.original_request_id" + + " WHERE i.account_id = ? AND t.account_id = ? AND t.tenant_id = ?" + + " AND t.playable_state_namespace_id = ?" + + " AND t.target_state = 'OPEN_INSTALLED'" + + " ORDER BY i.initializer_id, t.target_ordinal", + accountId, + accountId, + tenantId, + playableStateNamespaceId); + if (rows.size() != 1) { + throw conflict( + rows.isEmpty() + ? "No retained installed INITIAL OPEN target matches the exact account scope" + : "Multiple retained installed INITIAL OPEN targets match the exact account scope"); + } + InitializerSnapshot snapshot = toSnapshot(rows.get(0)); + if (snapshot.state() != State.OPEN_INSTALLED + || !accountId.equals(snapshot.accountId()) + || !tenantId.equals(snapshot.tenantId()) + || !playableStateNamespaceId.equals(snapshot.playableStateNamespaceId())) { + throw conflict("Retained INITIAL OPEN target differs from the exact account scope"); + } + AccountControlSource current = readCurrentNoActiveControl(transaction, accountId); + requireSameCurrentSource(snapshot, current); + return snapshot; + }); + } + + /** + * Commits the one-time remote-attempt state and its qualified pre-dispatch source before Redis is + * called. No subsequent path can receive another create permission. + */ + InitializerSnapshot recordDispatchPossible( + UUID originalRequestId, + CanonicalGameplayProtectedIncarnationReceiver.VerifiedIncarnation beforeIncarnation) { + requireNonNil(originalRequestId, "originalRequestId"); + Objects.requireNonNull(beforeIncarnation, "beforeIncarnation"); + requireNoAmbientTransaction(); + return dsl.transactionResult( + configuration -> { + DSLContext transaction = DSL.using(configuration); + lockInventoryRevision(transaction); + Record locator = readInitializer(transaction, originalRequestId, false); + if (locator == null) throw conflict("Exact original INITIAL account target is missing"); + InitializerSnapshot located = toSnapshot(locator); + Record control = lockExistingControl(transaction, located.accountId()); + AccountControlSource source = readNoActiveControl(control, located.accountId()); + InitializerSnapshot current = readRequiredCurrent(transaction, originalRequestId, true); + requireSameCurrentSource(current, source); + requireOriginalJournalStillCurrent(transaction, current); + requireInitialObservationMatches(current, beforeIncarnation); + if (current.state() != State.NEVER_DISPATCHED) { + throw conflict("INITIAL remote attempt was already possible and cannot be reissued"); + } + int updated = + transaction.execute( + "UPDATE " + + TARGET + + " SET target_state = 'DISPATCH_POSSIBLE'," + + " before_accepted_attestation_digest = ?, before_incarnation_digest = ?," + + " before_source_payload_digest = ?," + + " before_observation_issued_at_epoch_millis = ?," + + " before_observation_observed_at_epoch_millis = ?," + + " before_observation_expires_at_epoch_millis = ?" + + " WHERE initializer_id = ? AND target_ordinal = 0" + + " AND target_state = 'NEVER_DISPATCHED'", + beforeIncarnation.acceptedAttestationDigest(), + beforeIncarnation.incarnationDigest(), + beforeIncarnation.payloadDigest(), + beforeIncarnation.issuedAtEpochMillis(), + beforeIncarnation.observedAtEpochMillis(), + beforeIncarnation.expiresAtEpochMillis(), + current.initializerId()); + requireOne(updated, "INITIAL one-time remote dispatch claim was lost"); + InitializerSnapshot saved = readRequiredCurrent(transaction, originalRequestId, true); + if (saved.state() != State.DISPATCH_POSSIBLE + || !saved.beforeIncarnationDigest().equals(beforeIncarnation.incarnationDigest()) + || !saved.beforeSourcePayloadDigest().equals(beforeIncarnation.payloadDigest())) { + throw conflict("INITIAL remote dispatch state did not read back exactly"); + } + requireSameCurrentSource(saved, source); + return saved; + }); + } + + /** + * Accepts exact physical OPEN readback only while the positively read source control still has + * its captured NO_ACTIVE control epoch. This receipt is current SQL evidence, not a later + * admission decision. + */ + InitializerSnapshot acceptOpenReadback( + UUID originalRequestId, CanonicalGameplayAccountInitialBarrierRedisOwner.Readback readback) { + requireNonNil(originalRequestId, "originalRequestId"); + Objects.requireNonNull(readback, "readback"); + requireNoAmbientTransaction(); + if (!originalRequestId.equals(readback.originalRequestId())) { + throw conflict("INITIAL readback belongs to a different original request"); + } + requireReadback(readback); + String fieldsDigest = digestFields(readback.value().fields()); + + return dsl.transactionResult( + configuration -> { + DSLContext transaction = DSL.using(configuration); + lockInventoryRevision(transaction); + Record locator = readInitializer(transaction, originalRequestId, false); + if (locator == null) throw conflict("Exact original INITIAL account target is missing"); + InitializerSnapshot located = toSnapshot(locator); + Record control = lockExistingControl(transaction, located.accountId()); + AccountControlSource source = readNoActiveControl(control, located.accountId()); + InitializerSnapshot current = readRequiredCurrent(transaction, originalRequestId, true); + requireSameCurrentSource(current, source); + requireOriginalJournalStillCurrent(transaction, current); + requireSameReadbackContext(current, readback); + long now = clock.millis(); + if (now <= 0 + || now < readback.beforeIncarnation().issuedAtEpochMillis() + || now >= readback.beforeIncarnation().expiresAtEpochMillis() + || now < readback.afterIncarnation().issuedAtEpochMillis() + || now >= readback.afterIncarnation().expiresAtEpochMillis()) { + throw conflict( + "INITIAL protected incarnation observation expired before SQL completion"); + } + if (current.state() == State.OPEN_INSTALLED) { + if (!fieldsDigest.equals(current.installedFieldsDigest())) { + throw conflict("An installed INITIAL OPEN value cannot be replaced"); + } + return current; + } + if (current.state() != State.DISPATCH_POSSIBLE) { + throw conflict("INITIAL OPEN readback has no persisted possible-dispatch state"); + } + int updated = + transaction.execute( + "UPDATE " + + TARGET + + " SET target_state = 'OPEN_INSTALLED', installed_fields_digest = ?," + + " completed_at = CURRENT_TIMESTAMP" + + " WHERE initializer_id = ? AND target_ordinal = 0" + + " AND target_state = 'DISPATCH_POSSIBLE'" + + " AND before_incarnation_digest = ?" + + " AND before_accepted_attestation_digest = ?", + fieldsDigest, + current.initializerId(), + readback.beforeIncarnation().incarnationDigest(), + readback.beforeIncarnation().acceptedAttestationDigest()); + requireOne(updated, "INITIAL OPEN completion lost its exact original SQL target"); + InitializerSnapshot saved = readRequiredCurrent(transaction, originalRequestId, true); + if (saved.state() != State.OPEN_INSTALLED + || !fieldsDigest.equals(saved.installedFieldsDigest())) { + throw conflict("INITIAL OPEN completion readback differs from its exact SQL postimage"); + } + requireSameCurrentSource(saved, source); + return saved; + }); + } + + void requireNoAmbientTransaction() { + if (TransactionSynchronizationManager.isActualTransactionActive() + || TransactionSynchronizationManager.isSynchronizationActive()) { + throw conflict("INITIAL account barrier phases require no ambient SQL transaction"); + } + try { + dsl.connectionResult( + connection -> { + if (!connection.getAutoCommit()) { + throw conflict("INITIAL account barrier phases cannot join a jOOQ transaction"); + } + return Boolean.TRUE; + }); + } catch (RuntimeException failure) { + if (failure instanceof CanonicalGameplayBindingInventoryConflictException) throw failure; + throw conflict("INITIAL account barrier SQL connection state is unavailable"); + } + } + + private static void requireReadback( + CanonicalGameplayAccountInitialBarrierRedisOwner.Readback readback) { + CanonicalGameplayProtectedIncarnationReceiver.VerifiedIncarnation before = + readback.beforeIncarnation(); + CanonicalGameplayProtectedIncarnationReceiver.VerifiedIncarnation after = + readback.afterIncarnation(); + if (!readback.value().fields().equals(readback.barrierFields()) + || !CanonicalGameplayAccountInitialBarrierValue.FIELDS.equals( + readback.barrierFields().keySet()) + || !"OPEN".equals(readback.barrierFields().get("state")) + || !readback + .beforeIncarnation() + .sourceControlEpoch() + .equals(readback.barrierFields().get("ownerFenceEpoch")) + || !readback + .afterIncarnation() + .sourceControlEpoch() + .equals(readback.barrierFields().get("ownerFenceEpoch")) + || !before.incarnationDigest().equals(after.incarnationDigest()) + || !before.acceptedAttestationDigest().equals(after.acceptedAttestationDigest()) + || after.issuedAtEpochMillis() < before.issuedAtEpochMillis() + || after.observedAtEpochMillis() < before.observedAtEpochMillis()) { + throw conflict("Physical INITIAL OPEN readback or protected source tuple is not exact"); + } + } + + private static void requireSameReadbackContext( + InitializerSnapshot current, + CanonicalGameplayAccountInitialBarrierRedisOwner.Readback readback) { + requireInitialObservationMatches(current, readback.beforeIncarnation()); + requireInitialObservationMatches(current, readback.afterIncarnation()); + if (!current.initializerId().equals(readback.initializerId()) + || !current.originalRequestId().equals(readback.originalRequestId()) + || !current.accountId().equals(readback.accountId()) + || !current.tenantId().equals(readback.tenantId()) + || !current.playableStateNamespaceId().equals(readback.playableStateNamespaceId()) + || !current.accountLoginEvidenceDigest().equals(readback.accountLoginEvidenceDigest()) + || !current.sourceControlDigest().equals(readback.sourceControlDigest()) + || !current.inventorySnapshotRevision().equals(readback.inventorySnapshotRevision()) + || !readback + .key() + .equals( + CanonicalGameplayAccountInitialBarrierKey.forTarget( + readback.assignment(), current.initializerId(), current.originalRequestId()))) { + throw conflict("Physical INITIAL OPEN readback differs from the original SQL initializer"); + } + Map fields = readback.barrierFields(); + if (!current.initializerId().toString().equals(fields.get("ownerOperationId")) + || !current.accountId().toString().equals(fields.get("accountId")) + || !current.sourceControlEpoch().toString().equals(fields.get("ownerFenceEpoch")) + || !current.tenantId().toString().equals(fields.get("tenantId")) + || !current + .playableStateNamespaceId() + .toString() + .equals(fields.get("playableStateNamespaceId")) + || !readback.assignment().tenantGameplayTag().equals(fields.get("tenantGameplayTag"))) { + throw conflict("Physical INITIAL OPEN fields differ from the exact original target"); + } + } + + private static void requireInitialObservationMatches( + InitializerSnapshot snapshot, + CanonicalGameplayProtectedIncarnationReceiver.VerifiedIncarnation observation) { + if (observation.ownerKind() + != CanonicalGameplayProtectedIncarnationReceiver.OwnerKind.INITIAL_ACCOUNT_BARRIER + || !snapshot.initializerId().equals(observation.operationId()) + || !snapshot.originalRequestId().equals(observation.requestId()) + || !snapshot.originalCallerContextId().equals(observation.originalCallerContextId()) + || snapshot.originalAttemptFence() != observation.originalAttemptFence() + || !snapshot.accountId().equals(observation.accountId()) + || !snapshot.tenantId().equals(observation.tenantId()) + || !snapshot.playableStateNamespaceId().equals(observation.playableStateNamespaceId()) + || !NO_ACTIVE.equals(observation.sourceControlState()) + || !snapshot.sourceControlEpoch().toString().equals(observation.sourceControlEpoch()) + || !snapshot + .inventorySnapshotRevision() + .toString() + .equals(observation.inventorySnapshotRevision()) + || !snapshot.accountLoginEvidenceDigest().equals(observation.accountLoginEvidenceDigest()) + || !snapshot.sourceControlDigest().equals(observation.sourceControlDigest()) + || !snapshot.targetDigest().equals(observation.barrierTargetDigest())) { + throw conflict("Protected INITIAL observation differs from original SQL source context"); + } + } + + private static void requireOriginalEvidence( + InitialGameplayLoginAttemptCoordinates original, + CanonicalGameplayLoginResult.NonSecretEvidence evidence) { + if (evidence == null + || !original.requestId().equals(evidence.requestId()) + || !original.callerContextId().equals(evidence.callerContextId()) + || original.expectedAttemptFence() <= 0L + || !net.firedevops.firemud.common.security.GameSessionAccountDelegationProfile.PROFILE + .equals(evidence.tokenProfile()) + || evidence.accountId() == null + || evidence.tokenJti() == null + || evidence.tokenSha256() == null + || !evidence.tokenSha256().matches("[0-9a-f]{64}") + || !positiveDecimal(evidence.tokenGeneration()) + || !positiveDecimal(evidence.issuanceFence())) { + throw conflict("Authenticated Account LOGIN result differs from the exact original attempt"); + } + } + + private static void requireExactOriginalLogin( + DSLContext transaction, + InitialGameplayLoginAttemptCoordinates original, + CanonicalGameplayLoginResult.NonSecretEvidence evidence) { + Record row = + transaction.fetchOne( + "SELECT caller_context_id, expected_attempt_fence, abandoned, verified_token_jti," + + " verified_token_sha256, verified_token_generation, verified_issuance_fence" + + " FROM " + + ORIGINAL + + " WHERE request_id = ? FOR UPDATE", + original.requestId()); + if (row == null + || !original.callerContextId().equals(row.get("caller_context_id", UUID.class)) + || !Long.valueOf(original.expectedAttemptFence()) + .equals(row.get("expected_attempt_fence", Long.class)) + || !Boolean.FALSE.equals(row.get("abandoned", Boolean.class)) + || !evidence.tokenJti().equals(row.get("verified_token_jti", UUID.class)) + || !evidence.tokenSha256().equals(row.get("verified_token_sha256", String.class)) + || !Long.valueOf(Long.parseLong(evidence.tokenGeneration())) + .equals(row.get("verified_token_generation", Long.class)) + || !Long.valueOf(Long.parseLong(evidence.issuanceFence())) + .equals(row.get("verified_issuance_fence", Long.class))) { + throw conflict("Original Account COMMITTED evidence is not retained by the LOGIN journal"); + } + } + + private static void requireOriginalJournalStillCurrent( + DSLContext transaction, InitializerSnapshot snapshot) { + Record row = + transaction.fetchOne( + "SELECT caller_context_id, expected_attempt_fence, abandoned" + + " FROM " + + ORIGINAL + + " WHERE request_id = ?", + snapshot.originalRequestId()); + if (row == null + || !snapshot.originalCallerContextId().equals(row.get("caller_context_id", UUID.class)) + || !Long.valueOf(snapshot.originalAttemptFence()) + .equals(row.get("expected_attempt_fence", Long.class)) + || !Boolean.FALSE.equals(row.get("abandoned", Boolean.class))) { + throw conflict("Original INITIAL LOGIN was abandoned or its coordinates changed"); + } + } + + private static void requireSameOriginalTarget( + InitializerSnapshot snapshot, + InitialGameplayLoginAttemptCoordinates original, + UUID accountId, + UUID tenantId, + UUID namespaceId, + String accountEvidenceDigest) { + if (!snapshot.originalRequestId().equals(original.requestId()) + || !snapshot.originalCallerContextId().equals(original.callerContextId()) + || snapshot.originalAttemptFence() != original.expectedAttemptFence() + || !snapshot.accountId().equals(accountId) + || !snapshot.tenantId().equals(tenantId) + || !snapshot.playableStateNamespaceId().equals(namespaceId) + || !snapshot.accountLoginEvidenceDigest().equals(accountEvidenceDigest)) { + throw conflict("INITIAL original request was reused for a different Account or target"); + } + } + + private static void requireSameCurrentSource( + InitializerSnapshot snapshot, AccountControlSource current) { + if (!NO_ACTIVE.equals(snapshot.sourceControlState()) + || snapshot.sourceControlEpoch().signum() < 0 + || !snapshot.sourceControlEpoch().equals(current.epoch()) + || !snapshot.sourceControlDigest().equals(current.digest()) + || !snapshot.accountId().equals(current.accountId())) { + throw conflict("INITIAL source-control tuple is no longer the exact positive NO_ACTIVE row"); + } + } + + private static InitialObservationContext context(InitializerSnapshot snapshot) { + return InitialObservationContext.from(snapshot); + } + + private static BigInteger lockInventoryRevision(DSLContext transaction) { + Record row = + transaction.fetchOne( + "SELECT inventory_revision FROM " + + INVENTORY_CLOCK + + " WHERE singleton_id = 1 FOR UPDATE"); + if (row == null) throw conflict("Canonical binding inventory clock is missing"); + BigInteger revision = readBigInteger(row, "inventory_revision"); + if (revision.signum() <= 0) + throw conflict("Initial account barrier inventory revision is not positive"); + return revision; + } + + private static Record lockExistingControl(DSLContext transaction, UUID accountId) { + Record row = + transaction.fetchOne( + "SELECT * FROM " + CONTROL + " WHERE account_id = ? FOR UPDATE", accountId); + if (row == null) + throw conflict("Account coverage control row is missing; absence is not source"); + return row; + } + + private static AccountControlSource readCurrentNoActiveControl( + DSLContext transaction, UUID accountId) { + Record row = + transaction.fetchOne("SELECT * FROM " + CONTROL + " WHERE account_id = ?", accountId); + if (row == null) + throw conflict("Account coverage control row is missing; absence is not source"); + return readNoActiveControl(row, accountId); + } + + private static AccountControlSource readNoActiveControl(Record row, UUID accountId) { + if (!accountId.equals(row.get("account_id", UUID.class)) + || !NO_ACTIVE.equals(row.get("state", String.class)) + || row.get("current_operation_id", UUID.class) != null + || row.get("current_fence_intent_id", UUID.class) != null + || row.get("current_operation_fence") != null + || row.get("account_admission_fence", UUID.class) != null + || row.get("historical_account_admission_fence", UUID.class) != null + || row.get("coverage_fence", UUID.class) != null + || row.get("inventory_snapshot_revision") != null + || row.get("coverage_generation") != null) { + throw conflict("INITIAL source requires the complete SQL NO_ACTIVE account-control arm"); + } + BigInteger epoch = readBigInteger(row, "last_operation_fence"); + if (epoch.signum() < 0 || epoch.toString().length() > 256) { + throw conflict( + "INITIAL source requires a bounded nonnegative positive-row account-control epoch"); + } + return new AccountControlSource(accountId, NO_ACTIVE, epoch, digestControl(row)); + } + + private static String digestControl(Record row) { + Map fields = new LinkedHashMap<>(); + fields.put("accountId", row.get("account_id", UUID.class).toString()); + fields.put("state", row.get("state", String.class)); + fields.put("lastOperationFence", readBigInteger(row, "last_operation_fence").toString()); + fields.put("currentOperationId", uuidText(row, "current_operation_id")); + fields.put("currentFenceIntentId", uuidText(row, "current_fence_intent_id")); + fields.put("currentOperationFence", nullableInteger(row, "current_operation_fence")); + fields.put("accountAdmissionFence", uuidText(row, "account_admission_fence")); + fields.put( + "historicalAccountAdmissionFence", uuidText(row, "historical_account_admission_fence")); + fields.put("coverageFence", uuidText(row, "coverage_fence")); + fields.put("inventorySnapshotRevision", nullableInteger(row, "inventory_snapshot_revision")); + fields.put("coverageGeneration", nullableInteger(row, "coverage_generation")); + try { + return digest( + net.firedevops.firemud.common.json.Rfc8785CanonicalJson.canonicalizeUtf8( + JSON.writeValueAsString(fields))); + } catch (Exception invalid) { + throw conflict("Account control source digest could not be computed"); + } + } + + private static String digestAccountEvidence(CanonicalGameplayLoginResult.NonSecretEvidence e) { + Map fields = new LinkedHashMap<>(); + fields.put("accountId", e.accountId().toString()); + fields.put("requestId", e.requestId().toString()); + fields.put("callerContextId", e.callerContextId().toString()); + fields.put("tokenJti", e.tokenJti().toString()); + fields.put("tokenSha256", e.tokenSha256()); + fields.put("tokenProfile", e.tokenProfile()); + fields.put("issuedAtEpochSecond", e.issuedAtEpochSecond()); + fields.put("notBeforeEpochSecond", e.notBeforeEpochSecond()); + fields.put("expiresAtEpochSecond", e.expiresAtEpochSecond()); + fields.put("tokenGeneration", e.tokenGeneration()); + fields.put("issuanceFence", e.issuanceFence()); + fields.put("authorityTupleCanonicalJson", e.authorityTupleCanonicalJson().toStringUtf8()); + fields.put("outboxCheckpointsCanonicalJson", e.outboxCheckpointsCanonicalJson().toStringUtf8()); + fields.put( + "outboxSourceEventEvidenceCanonicalJson", + e.outboxSourceEventEvidenceCanonicalJson().toStringUtf8()); + try { + return digest( + net.firedevops.firemud.common.json.Rfc8785CanonicalJson.canonicalizeUtf8( + JSON.writeValueAsString(fields))); + } catch (Exception invalid) { + throw conflict("Authenticated Account response evidence digest could not be computed"); + } + } + + private static String digestTarget(InitializerSnapshot snapshot) { + Map fields = new LinkedHashMap<>(); + fields.put("initializerId", snapshot.initializerId().toString()); + fields.put("originalRequestId", snapshot.originalRequestId().toString()); + fields.put("originalCallerContextId", snapshot.originalCallerContextId().toString()); + fields.put("originalAttemptFence", snapshot.originalAttemptFence()); + fields.put("accountId", snapshot.accountId().toString()); + fields.put("tenantId", snapshot.tenantId().toString()); + fields.put("playableStateNamespaceId", snapshot.playableStateNamespaceId().toString()); + fields.put("accountLoginEvidenceDigest", snapshot.accountLoginEvidenceDigest()); + fields.put("sourceControlState", snapshot.sourceControlState()); + fields.put("sourceControlEpoch", snapshot.sourceControlEpoch().toString()); + fields.put("sourceControlDigest", snapshot.sourceControlDigest()); + fields.put("inventorySnapshotRevision", snapshot.inventorySnapshotRevision().toString()); + return digestUnchecked(fields); + } + + private static String digestFields(Map fields) { + return digestUnchecked(new java.util.TreeMap<>(fields)); + } + + private static String digestUnchecked(Object fields) { + try { + return digest( + net.firedevops.firemud.common.json.Rfc8785CanonicalJson.canonicalizeUtf8( + JSON.writeValueAsString(fields))); + } catch (Exception invalid) { + throw conflict("Canonical INITIAL source digest could not be computed"); + } + } + + private static String digest(byte[] bytes) { + try { + return "sha256:" + + HexFormat.of().formatHex(MessageDigest.getInstance("SHA-256").digest(bytes)); + } catch (NoSuchAlgorithmException impossible) { + throw new IllegalStateException("SHA-256 is unavailable", impossible); + } + } + + private static String uuidText(Record row, String name) { + UUID value = row.get(name, UUID.class); + return value == null ? null : value.toString(); + } + + private static String nullableInteger(Record row, String name) { + BigDecimal value = row.get(name, BigDecimal.class); + return value == null ? null : value.toBigIntegerExact().toString(); + } + + private static Record readInitializer(DSLContext transaction, UUID requestId, boolean forUpdate) { + return transaction.fetchOne( + "SELECT i.initializer_id, i.original_request_id, i.original_caller_context_id," + + " i.original_attempt_fence, i.account_id, i.account_login_evidence_digest," + + " i.source_control_state, i.source_control_epoch, i.inventory_snapshot_revision," + + " i.source_control_digest, t.tenant_id, t.playable_state_namespace_id," + + " t.target_state, t.before_accepted_attestation_digest, t.before_incarnation_digest," + + " t.before_source_payload_digest, t.before_observation_issued_at_epoch_millis," + + " t.before_observation_observed_at_epoch_millis," + + " t.before_observation_expires_at_epoch_millis, t.installed_fields_digest" + + " FROM " + + INITIALIZER + + " i JOIN " + + TARGET + + " t ON t.initializer_id = i.initializer_id AND t.original_request_id = i.original_request_id" + + " WHERE i.original_request_id = ?" + + (forUpdate ? " FOR UPDATE OF i, t" : ""), + requestId); + } + + private static InitializerSnapshot readRequiredCurrent( + DSLContext transaction, UUID requestId, boolean forUpdate) { + Record row = readInitializer(transaction, requestId, forUpdate); + if (row == null) throw conflict("Exact original INITIAL account target is missing"); + return toSnapshot(row); + } + + private static InitializerSnapshot toSnapshot(Record row) { + UUID requestId = row.get("original_request_id", UUID.class); + UUID callerContextId = row.get("original_caller_context_id", UUID.class); + UUID accountId = row.get("account_id", UUID.class); + UUID tenantId = row.get("tenant_id", UUID.class); + UUID namespaceId = row.get("playable_state_namespace_id", UUID.class); + BigInteger controlEpoch = readBigInteger(row, "source_control_epoch"); + BigInteger inventoryRevision = readBigInteger(row, "inventory_snapshot_revision"); + State state; + try { + state = State.valueOf(row.get("target_state", String.class)); + } catch (RuntimeException malformed) { + throw conflict("Initial account barrier target state is malformed"); + } + InitializerSnapshot snapshot = + new InitializerSnapshot( + row.get("initializer_id", UUID.class), + requestId, + callerContextId, + row.get("original_attempt_fence", Long.class), + accountId, + tenantId, + namespaceId, + row.get("account_login_evidence_digest", String.class), + row.get("source_control_state", String.class), + controlEpoch, + inventoryRevision, + row.get("source_control_digest", String.class), + state, + row.get("before_accepted_attestation_digest", String.class), + row.get("before_incarnation_digest", String.class), + row.get("before_source_payload_digest", String.class), + nullableLong(row, "before_observation_issued_at_epoch_millis"), + nullableLong(row, "before_observation_observed_at_epoch_millis"), + nullableLong(row, "before_observation_expires_at_epoch_millis"), + row.get("installed_fields_digest", String.class)); + if (snapshot.initializerId() == null + || snapshot.originalRequestId() == null + || snapshot.originalCallerContextId() == null + || snapshot.originalAttemptFence() <= 0L + || snapshot.accountId() == null + || snapshot.tenantId() == null + || snapshot.playableStateNamespaceId() == null + || !NO_ACTIVE.equals(snapshot.sourceControlState()) + || controlEpoch.signum() < 0 + || controlEpoch.toString().length() > 256 + || inventoryRevision.signum() <= 0 + || !isDigest(snapshot.accountLoginEvidenceDigest()) + || !isDigest(snapshot.sourceControlDigest())) { + throw conflict("Persisted INITIAL account barrier identity or source is malformed"); + } + return snapshot.withTargetDigest(digestTarget(snapshot)); + } + + private static long nullableLong(Record row, String name) { + Long value = row.get(name, Long.class); + return value == null ? 0L : value; + } + + private static BigInteger readBigInteger(Record row, String name) { + BigDecimal value = row.get(name, BigDecimal.class); + if (value == null) throw conflict("Persisted INITIAL account field is missing: " + name); + try { + return value.toBigIntegerExact(); + } catch (ArithmeticException malformed) { + throw conflict("Persisted INITIAL account field is not integral: " + name); + } + } + + private static boolean positiveDecimal(String value) { + return value != null && value.matches("[1-9][0-9]{0,38}"); + } + + private static boolean isDigest(String value) { + return value != null && value.matches("sha256:[0-9a-f]{64}"); + } + + private static UUID randomNonNilUuid() { + UUID value = UUID.randomUUID(); + if (value.equals(new UUID(0L, 0L))) throw conflict("UUID source returned nil identity"); + return value; + } + + private static void requireNonNil(UUID value, String name) { + Objects.requireNonNull(value, name); + if (value.equals(new UUID(0L, 0L))) + throw new IllegalArgumentException(name + " must not be nil"); + } + + private static void requireOne(int actual, String message) { + if (actual != 1) throw conflict(message); + } + + private static CanonicalGameplayBindingInventoryConflictException conflict(String message) { + return new CanonicalGameplayBindingInventoryConflictException(message); + } + + enum State { + NEVER_DISPATCHED, + DISPATCH_POSSIBLE, + OPEN_INSTALLED + } + + record InitialObservationContext( + UUID initializerId, + UUID originalRequestId, + UUID originalCallerContextId, + long originalAttemptFence, + UUID accountId, + UUID tenantId, + UUID playableStateNamespaceId, + String sourceControlState, + BigInteger sourceControlEpoch, + BigInteger inventorySnapshotRevision, + String accountLoginEvidenceDigest, + String sourceControlDigest, + String targetDigest) { + private static InitialObservationContext from(InitializerSnapshot snapshot) { + return new InitialObservationContext( + snapshot.initializerId(), + snapshot.originalRequestId(), + snapshot.originalCallerContextId(), + snapshot.originalAttemptFence(), + snapshot.accountId(), + snapshot.tenantId(), + snapshot.playableStateNamespaceId(), + snapshot.sourceControlState(), + snapshot.sourceControlEpoch(), + snapshot.inventorySnapshotRevision(), + snapshot.accountLoginEvidenceDigest(), + snapshot.sourceControlDigest(), + snapshot.targetDigest()); + } + } + + record InitializerSnapshot( + UUID initializerId, + UUID originalRequestId, + UUID originalCallerContextId, + long originalAttemptFence, + UUID accountId, + UUID tenantId, + UUID playableStateNamespaceId, + String accountLoginEvidenceDigest, + String sourceControlState, + BigInteger sourceControlEpoch, + BigInteger inventorySnapshotRevision, + String sourceControlDigest, + State state, + String beforeAcceptedAttestationDigest, + String beforeIncarnationDigest, + String beforeSourcePayloadDigest, + long beforeIssuedAtEpochMillis, + long beforeObservedAtEpochMillis, + long beforeExpiresAtEpochMillis, + String installedFieldsDigest, + String targetDigest) { + private InitializerSnapshot( + UUID initializerId, + UUID originalRequestId, + UUID originalCallerContextId, + long originalAttemptFence, + UUID accountId, + UUID tenantId, + UUID playableStateNamespaceId, + String accountLoginEvidenceDigest, + String sourceControlState, + BigInteger sourceControlEpoch, + BigInteger inventorySnapshotRevision, + String sourceControlDigest, + State state, + String beforeAcceptedAttestationDigest, + String beforeIncarnationDigest, + String beforeSourcePayloadDigest, + long beforeIssuedAtEpochMillis, + long beforeObservedAtEpochMillis, + long beforeExpiresAtEpochMillis, + String installedFieldsDigest) { + this( + initializerId, + originalRequestId, + originalCallerContextId, + originalAttemptFence, + accountId, + tenantId, + playableStateNamespaceId, + accountLoginEvidenceDigest, + sourceControlState, + sourceControlEpoch, + inventorySnapshotRevision, + sourceControlDigest, + state, + beforeAcceptedAttestationDigest, + beforeIncarnationDigest, + beforeSourcePayloadDigest, + beforeIssuedAtEpochMillis, + beforeObservedAtEpochMillis, + beforeExpiresAtEpochMillis, + installedFieldsDigest, + null); + } + + InitializerSnapshot withTargetDigest(String value) { + return new InitializerSnapshot( + initializerId, + originalRequestId, + originalCallerContextId, + originalAttemptFence, + accountId, + tenantId, + playableStateNamespaceId, + accountLoginEvidenceDigest, + sourceControlState, + sourceControlEpoch, + inventorySnapshotRevision, + sourceControlDigest, + state, + beforeAcceptedAttestationDigest, + beforeIncarnationDigest, + beforeSourcePayloadDigest, + beforeIssuedAtEpochMillis, + beforeObservedAtEpochMillis, + beforeExpiresAtEpochMillis, + installedFieldsDigest, + value); + } + } + + private record AccountControlSource( + UUID accountId, String state, BigInteger epoch, String digest) {} +} diff --git a/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/repository/CanonicalGameplayAccountInitialBarrierKey.java b/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/repository/CanonicalGameplayAccountInitialBarrierKey.java new file mode 100644 index 0000000000..46a0014dfc --- /dev/null +++ b/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/repository/CanonicalGameplayAccountInitialBarrierKey.java @@ -0,0 +1,18 @@ +package net.firedevops.firemud.gamesession.repository; + +import java.util.Objects; +import java.util.UUID; + +/** Key for the original-attempt INITIAL OPEN operation on one tenant gameplay slot. */ +final class CanonicalGameplayAccountInitialBarrierKey { + private CanonicalGameplayAccountInitialBarrierKey() {} + + static String forTarget( + CanonicalGameplayTenantGameplayTagRepository.Assignment assignment, + UUID initializerId, + UUID originalRequestId) { + Objects.requireNonNull(assignment, "persisted initial target assignment"); + return CanonicalGameplaySessionRedisKeys.initialAccountAdmissionBarrier( + assignment, initializerId, originalRequestId); + } +} diff --git a/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/repository/CanonicalGameplayAccountInitialBarrierRedisOwner.java b/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/repository/CanonicalGameplayAccountInitialBarrierRedisOwner.java new file mode 100644 index 0000000000..97b0fb1d8e --- /dev/null +++ b/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/repository/CanonicalGameplayAccountInitialBarrierRedisOwner.java @@ -0,0 +1,613 @@ +package net.firedevops.firemud.gamesession.repository; + +import io.lettuce.core.RedisFuture; +import io.lettuce.core.ScriptOutputType; +import io.lettuce.core.api.StatefulRedisConnection; +import io.lettuce.core.api.async.RedisAsyncCommands; +import io.lettuce.core.codec.ByteArrayCodec; +import java.io.IOException; +import java.io.InputStream; +import java.math.BigInteger; +import java.nio.charset.StandardCharsets; +import java.security.MessageDigest; +import java.util.HashMap; +import java.util.HexFormat; +import java.util.List; +import java.util.Map; +import java.util.Objects; +import java.util.UUID; +import java.util.concurrent.ExecutionException; +import java.util.concurrent.TimeUnit; +import java.util.concurrent.TimeoutException; +import net.firedevops.firemud.common.redis.contracts.RedisScriptCatalog; +import net.firedevops.firemud.common.redis.contracts.RedisScriptDescriptor; +import net.firedevops.firemud.gamesession.dto.CanonicalGameplayLoginResult; +import net.firedevops.firemud.gamesession.dto.InitialGameplayLoginAttemptCoordinates; +import net.firedevops.firemud.gamesession.service.CanonicalGameplayAccountInitialBarrierRedisScriptContribution; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; + +/** Explicit manual owner for a create-once INITIAL OPEN barrier and exact current readback. */ +final class CanonicalGameplayAccountInitialBarrierRedisOwner { + private static final Logger logger = + LoggerFactory.getLogger(CanonicalGameplayAccountInitialBarrierRedisOwner.class); + private static final String PRINCIPAL = "gamesession_coord_app"; + private static final String KEY_PREFIX = "session:game:account-admission:"; + private static final int MAX_SCRIPT_BYTES = 32 * 1024; + private static final long COMMAND_TIMEOUT_MILLIS = 5_000; + private static final List FIELDS = + List.of( + "schema", + "accountId", + "tenantId", + "playableStateNamespaceId", + "tenantGameplayTag", + "ownerOperationId", + "ownerFenceEpoch", + "incarnationDigest", + "state"); + private static final List SCRIPT_ARGUMENTS = + List.of( + new RedisScriptDescriptor.ArgumentSpec("schema"), + new RedisScriptDescriptor.ArgumentSpec("accountId"), + new RedisScriptDescriptor.ArgumentSpec("tenantId"), + new RedisScriptDescriptor.ArgumentSpec("playableStateNamespaceId"), + new RedisScriptDescriptor.ArgumentSpec("tenantGameplayTag"), + new RedisScriptDescriptor.ArgumentSpec("initializerId"), + new RedisScriptDescriptor.ArgumentSpec("ownerFenceEpoch"), + new RedisScriptDescriptor.ArgumentSpec("incarnationDigest"), + new RedisScriptDescriptor.ArgumentSpec("state")); + private static final List SCRIPT_OUTCOMES = + List.of( + outcome( + "OPEN_CREATED", + RedisScriptDescriptor.OutcomeCategory.SUCCESS, + RedisScriptDescriptor.MutationEffect.MUTATING), + outcome( + "TARGET_ALREADY_PRESENT", + RedisScriptDescriptor.OutcomeCategory.STALE, + RedisScriptDescriptor.MutationEffect.NON_MUTATING), + outcome( + "INVALID_ARGUMENTS", + RedisScriptDescriptor.OutcomeCategory.VALIDATION_FAILURE, + RedisScriptDescriptor.MutationEffect.NON_MUTATING)); + + private final io.lettuce.core.RedisClient redisClient; + private final RedisScriptCatalog catalog; + private final CanonicalGameplayAccountInitialBarrierInitializerRepository repository; + private final CanonicalGameplayTenantGameplayTagRepository tenantTags; + private final CanonicalGameplayProtectedIncarnationReceiver incarnationReceiver; + + CanonicalGameplayAccountInitialBarrierRedisOwner( + io.lettuce.core.RedisClient redisClient, + RedisScriptCatalog catalog, + CanonicalGameplayAccountInitialBarrierInitializerRepository repository, + CanonicalGameplayTenantGameplayTagRepository tenantTags, + CanonicalGameplayProtectedIncarnationReceiver incarnationReceiver) { + this.redisClient = Objects.requireNonNull(redisClient, "Configured Redis client is required"); + this.catalog = Objects.requireNonNull(catalog, "Manual Redis script catalog is required"); + this.repository = Objects.requireNonNull(repository, "Exact SQL initializer is required"); + this.tenantTags = Objects.requireNonNull(tenantTags, "Persisted target resolver is required"); + this.incarnationReceiver = + Objects.requireNonNull(incarnationReceiver, "Protected observation verifier is required"); + } + + /** + * Starts one original-attempt target or performs read-only same-original verification. The SQL + * DISPATCH_POSSIBLE state commits before the only Redis write call; every later path is + * read-only. + */ + CanonicalGameplayAccountInitialOpenProof initializeOnce( + InitialGameplayLoginAttemptCoordinates original, + CanonicalGameplayLoginResult accountLogin, + UUID tenantId, + UUID playableStateNamespaceId) { + Objects.requireNonNull(original, "original attempt"); + Objects.requireNonNull(accountLogin, "authenticated Account LOGIN result"); + CanonicalGameplayAccountInitialBarrierInitializerRepository.InitializerSnapshot snapshot; + try { + requireNoAmbientTransaction(); + snapshot = repository.beginOrRead(original, accountLogin, tenantId, playableStateNamespaceId); + } catch (RuntimeException unavailable) { + return refused(CanonicalGameplayAccountInitialOpenProof.Reason.SOURCE_CONTROL_UNAVAILABLE); + } + if (snapshot.state() + != CanonicalGameplayAccountInitialBarrierInitializerRepository.State.NEVER_DISPATCHED) { + return verifyCurrentOpen(snapshot.originalRequestId()); + } + + try { + CanonicalGameplayTenantGameplayTagRepository.Assignment assignment = + requireInitialAssignment(snapshot.originalRequestId(), snapshot); + CanonicalGameplayProtectedIncarnationReceiver.VerifiedIncarnation before = + incarnationReceiver.observeForInitialAccountBarrier(snapshot.originalRequestId()); + requireObservation(snapshot, before); + PreparedWrite prepared = prepareWrite(snapshot, assignment, before); + requireNoAmbientTransaction(); + try (StatefulRedisConnection connection = + redisClient.connect(ByteArrayCodec.INSTANCE)) { + RedisAsyncCommands commands = requireCommands(connection); + requirePrincipal(await(commands.aclWhoami())); + byte[] script = ascii(prepared.script()); + String sha = await(commands.scriptLoad(script)); + if (!digest("SHA-1", script).equals(sha)) throw unavailable(); + repository.recordDispatchPossible(snapshot.originalRequestId(), before); + // The claim commits before EVAL on this same preflighted connection. A lost SQL + // commit reply is still uncertain and must never authorize another create attempt. + tryCreateOnce(prepared, commands, sha); + } + } catch (RuntimeException possibleDispatchOrSourceFailure) { + logger.warn( + "Initial Account OPEN create attempt did not complete originalRequestId={} initializerId={} failureType={}", + snapshot.originalRequestId(), + snapshot.initializerId(), + possibleDispatchOrSourceFailure.getClass().getName()); + // Never create a replacement initializer or repeat a possibly dispatched write. A positive + // exact readback can still finish the original receipt; absence remains explicit uncertainty. + } + return verifyCurrentOpen(snapshot.originalRequestId()); + } + + /** Typed read-only current-OPEN proof or refusal; it cannot authorize final admission. */ + CanonicalGameplayAccountInitialOpenProof verifyCurrentOpen(UUID originalRequestId) { + if (originalRequestId == null) { + return refused(CanonicalGameplayAccountInitialOpenProof.Reason.ORIGINAL_ATTEMPT_MISMATCH); + } + CanonicalGameplayAccountInitialBarrierInitializerRepository.InitializerSnapshot snapshot; + try { + requireNoAmbientTransaction(); + snapshot = repository.readCurrent(originalRequestId); + } catch (RuntimeException unavailable) { + return refused(CanonicalGameplayAccountInitialOpenProof.Reason.SOURCE_CONTROL_UNAVAILABLE); + } + if (snapshot.state() + == CanonicalGameplayAccountInitialBarrierInitializerRepository.State.NEVER_DISPATCHED) { + return refused(CanonicalGameplayAccountInitialOpenProof.Reason.TARGET_NEVER_DISPATCHED); + } + if (snapshot.state() + == CanonicalGameplayAccountInitialBarrierInitializerRepository.State.DISPATCH_POSSIBLE + && snapshot.beforeIncarnationDigest() == null) { + return refused(CanonicalGameplayAccountInitialOpenProof.Reason.REMOTE_OUTCOME_UNCERTAIN); + } + + try { + CanonicalGameplayTenantGameplayTagRepository.Assignment assignment = + requireInitialAssignment(originalRequestId, snapshot); + CanonicalGameplayProtectedIncarnationReceiver.VerifiedIncarnation before = + incarnationReceiver.observeForInitialAccountBarrier(originalRequestId); + requireObservation(snapshot, before); + if (!before.incarnationDigest().equals(snapshot.beforeIncarnationDigest()) + || !before + .acceptedAttestationDigest() + .equals(snapshot.beforeAcceptedAttestationDigest())) { + return refused( + CanonicalGameplayAccountInitialOpenProof.Reason.PROTECTED_OBSERVATION_UNAVAILABLE); + } + CanonicalGameplayAccountInitialBarrierValue value = + CanonicalGameplayAccountInitialBarrierValue.open( + snapshot.accountId(), + snapshot.tenantId(), + snapshot.playableStateNamespaceId(), + assignment.tenantGameplayTag(), + snapshot.initializerId(), + snapshot.sourceControlEpoch(), + snapshot.beforeIncarnationDigest()); + String key = + CanonicalGameplayAccountInitialBarrierKey.forTarget( + assignment, snapshot.initializerId(), originalRequestId); + Map physical = readExactPhysicalState(key, value); + CanonicalGameplayProtectedIncarnationReceiver.VerifiedIncarnation after = + incarnationReceiver.observeForInitialAccountBarrier(originalRequestId); + requireObservation(snapshot, after); + if (!before.incarnationDigest().equals(after.incarnationDigest()) + || !before.acceptedAttestationDigest().equals(after.acceptedAttestationDigest()) + || after.issuedAtEpochMillis() < before.issuedAtEpochMillis() + || after.observedAtEpochMillis() < before.observedAtEpochMillis()) { + return refused( + CanonicalGameplayAccountInitialOpenProof.Reason.PROTECTED_OBSERVATION_UNAVAILABLE); + } + + Readback readback = + new Readback(snapshot, assignment, key, value, physical, before, after, 0L); + if (snapshot.state() + == CanonicalGameplayAccountInitialBarrierInitializerRepository.State.OPEN_INSTALLED) { + var current = repository.readCurrent(originalRequestId); + if (current.state() + != CanonicalGameplayAccountInitialBarrierInitializerRepository.State.OPEN_INSTALLED) { + return refused(CanonicalGameplayAccountInitialOpenProof.Reason.CURRENT_CONTROL_CHANGED); + } + return currentProof(current, key, value.fields(), after); + } + var accepted = repository.acceptOpenReadback(originalRequestId, readback); + if (accepted.state() + != CanonicalGameplayAccountInitialBarrierInitializerRepository.State.OPEN_INSTALLED) { + return refused(CanonicalGameplayAccountInitialOpenProof.Reason.REMOTE_OUTCOME_UNCERTAIN); + } + return currentProof(accepted, key, value.fields(), after); + } catch (RuntimeException unavailable) { + return refused(classifyRefusal(snapshot)); + } + } + + /** + * Resolves and verifies a retained installed INITIAL OPEN for its exact account scope. These + * coordinates select storage evidence only; the returned proof is not fresh caller or Account + * admission authority. + */ + CanonicalGameplayAccountInitialOpenProof verifyCurrentOpenForTarget( + UUID accountId, UUID tenantId, UUID playableStateNamespaceId) { + if (isNil(accountId) || isNil(tenantId) || isNil(playableStateNamespaceId)) { + return refused(CanonicalGameplayAccountInitialOpenProof.Reason.ORIGINAL_ATTEMPT_MISMATCH); + } + CanonicalGameplayAccountInitialBarrierInitializerRepository.InitializerSnapshot snapshot; + try { + requireNoAmbientTransaction(); + snapshot = + repository.readInstalledOpenForTarget(accountId, tenantId, playableStateNamespaceId); + } catch (RuntimeException unavailable) { + return refused(CanonicalGameplayAccountInitialOpenProof.Reason.SOURCE_CONTROL_UNAVAILABLE); + } + if (snapshot == null + || !accountId.equals(snapshot.accountId()) + || !tenantId.equals(snapshot.tenantId()) + || !playableStateNamespaceId.equals(snapshot.playableStateNamespaceId())) { + return refused(CanonicalGameplayAccountInitialOpenProof.Reason.ORIGINAL_ATTEMPT_MISMATCH); + } + if (snapshot.state() + == CanonicalGameplayAccountInitialBarrierInitializerRepository.State.NEVER_DISPATCHED) { + return refused(CanonicalGameplayAccountInitialOpenProof.Reason.TARGET_NEVER_DISPATCHED); + } + if (snapshot.state() + == CanonicalGameplayAccountInitialBarrierInitializerRepository.State.DISPATCH_POSSIBLE) { + return refused(CanonicalGameplayAccountInitialOpenProof.Reason.REMOTE_OUTCOME_UNCERTAIN); + } + if (snapshot.state() + != CanonicalGameplayAccountInitialBarrierInitializerRepository.State.OPEN_INSTALLED) { + return refused(CanonicalGameplayAccountInitialOpenProof.Reason.ORIGINAL_ATTEMPT_MISMATCH); + } + return verifyCurrentOpen(snapshot.originalRequestId()); + } + + private PreparedWrite prepareWrite( + CanonicalGameplayAccountInitialBarrierInitializerRepository.InitializerSnapshot snapshot, + CanonicalGameplayTenantGameplayTagRepository.Assignment assignment, + CanonicalGameplayProtectedIncarnationReceiver.VerifiedIncarnation before) { + RedisScriptDescriptor descriptor = requireDescriptor(); + byte[] script = scriptSource(descriptor); + CanonicalGameplayAccountInitialBarrierValue value = + CanonicalGameplayAccountInitialBarrierValue.open( + snapshot.accountId(), + snapshot.tenantId(), + snapshot.playableStateNamespaceId(), + assignment.tenantGameplayTag(), + snapshot.initializerId(), + snapshot.sourceControlEpoch(), + before.incarnationDigest()); + String key = + CanonicalGameplayAccountInitialBarrierKey.forTarget( + assignment, snapshot.initializerId(), snapshot.originalRequestId()); + List arguments = FIELDS.stream().map(value.fields()::get).toList(); + // Validate every local byte conversion before the durable possible-dispatch claim. + ascii(key); + arguments.forEach(CanonicalGameplayAccountInitialBarrierRedisOwner::ascii); + return new PreparedWrite(asciiString(script), key, arguments); + } + + private void tryCreateOnce( + PreparedWrite prepared, RedisAsyncCommands commands, String sha) { + requireNoAmbientTransaction(); + Long outcome = + await( + commands.evalsha( + sha, + ScriptOutputType.INTEGER, + new byte[][] {ascii(prepared.key())}, + prepared.arguments().stream() + .map(CanonicalGameplayAccountInitialBarrierRedisOwner::ascii) + .toArray(byte[][]::new))); + if (outcome == null || outcome < 0 || outcome > 1) throw unavailable(); + } + + private record PreparedWrite(String script, String key, List arguments) {} + + private CanonicalGameplayTenantGameplayTagRepository.Assignment requireInitialAssignment( + UUID originalRequestId, + CanonicalGameplayAccountInitialBarrierInitializerRepository.InitializerSnapshot snapshot) { + CanonicalGameplayTenantGameplayTagRepository.Assignment assignment = + tenantTags.assignmentForInitialBarrierTarget(originalRequestId); + if (!assignment.isInitialBarrierTarget() + || !snapshot.initializerId().equals(assignment.initialBarrierInitializerId()) + || !snapshot.originalRequestId().equals(assignment.initialBarrierOriginalRequestId()) + || !snapshot.accountId().equals(assignment.accountId()) + || !snapshot.tenantId().equals(assignment.tenantId()) + || !snapshot.playableStateNamespaceId().equals(assignment.playableStateNamespaceId())) { + throw unavailable(); + } + return assignment; + } + + private static void requireObservation( + CanonicalGameplayAccountInitialBarrierInitializerRepository.InitializerSnapshot snapshot, + CanonicalGameplayProtectedIncarnationReceiver.VerifiedIncarnation observation) { + if (observation.ownerKind() + != CanonicalGameplayProtectedIncarnationReceiver.OwnerKind.INITIAL_ACCOUNT_BARRIER + || !snapshot.initializerId().equals(observation.operationId()) + || !snapshot.originalRequestId().equals(observation.requestId()) + || !snapshot.originalCallerContextId().equals(observation.originalCallerContextId()) + || snapshot.originalAttemptFence() != observation.originalAttemptFence() + || !snapshot.accountId().equals(observation.accountId()) + || !snapshot.tenantId().equals(observation.tenantId()) + || !snapshot.playableStateNamespaceId().equals(observation.playableStateNamespaceId()) + || !"NO_ACTIVE_ACCOUNT_WIDE_FLOW".equals(observation.sourceControlState()) + || !snapshot.sourceControlEpoch().toString().equals(observation.sourceControlEpoch()) + || !snapshot + .inventorySnapshotRevision() + .toString() + .equals(observation.inventorySnapshotRevision()) + || !snapshot.accountLoginEvidenceDigest().equals(observation.accountLoginEvidenceDigest()) + || !snapshot.sourceControlDigest().equals(observation.sourceControlDigest()) + || !snapshot.targetDigest().equals(observation.barrierTargetDigest())) { + throw unavailable(); + } + } + + private Map readExactPhysicalState( + String key, CanonicalGameplayAccountInitialBarrierValue expected) { + requireNoAmbientTransaction(); + byte[] keyBytes = ascii(key); + try (StatefulRedisConnection connection = + redisClient.connect(ByteArrayCodec.INSTANCE)) { + RedisAsyncCommands commands = requireCommands(connection); + requirePrincipal(await(commands.aclWhoami())); + if (!"hash".equals(await(commands.type(keyBytes))) + || !Long.valueOf(-1L).equals(await(commands.pttl(keyBytes)))) throw unavailable(); + Long length = await(commands.hlen(keyBytes)); + if (length == null || length != FIELDS.size()) throw unavailable(); + Map raw = await(commands.hgetall(keyBytes)); + if (raw == null || raw.size() != FIELDS.size()) throw unavailable(); + Map actual = new HashMap<>(); + for (Map.Entry entry : raw.entrySet()) { + String field = asciiString(entry.getKey()); + String value = asciiString(Objects.requireNonNull(entry.getValue())); + if (!FIELDS.contains(field) || actual.putIfAbsent(field, value) != null) + throw unavailable(); + } + if (!expected.fields().equals(actual)) throw unavailable(); + return Map.copyOf(actual); + } catch (RuntimeException failure) { + throw unavailable(failure); + } + } + + private RedisScriptDescriptor requireDescriptor() { + String scriptId = CanonicalGameplayAccountInitialBarrierRedisScriptContribution.SCRIPT_ID; + String resourcePath = + CanonicalGameplayAccountInitialBarrierRedisScriptContribution.RESOURCE_PATH; + try { + RedisScriptDescriptor descriptor = catalog.require(scriptId); + if (!scriptId.equals(descriptor.scriptId()) + || !resourcePath.equals(descriptor.resourcePath()) + || !"game-session-service".equals(descriptor.owner()) + || !PRINCIPAL.equals(descriptor.principal()) + || descriptor.role() != RedisScriptDescriptor.RedisRole.COORDINATION + || !List.of( + new RedisScriptDescriptor.KeySpec( + "accountAdmissionBarrier", + KEY_PREFIX, + RedisScriptDescriptor.HashTagDeclaration.REQUIRED)) + .equals(descriptor.keys()) + || !SCRIPT_ARGUMENTS.equals(descriptor.arguments()) + || descriptor.category() != RedisScriptDescriptor.ScriptCategory.SESSION_CAS + || !SCRIPT_OUTCOMES.equals(descriptor.outcomes()) + || descriptor.resetSensitivity() != RedisScriptDescriptor.ResetSensitivity.CLUSTER + || descriptor.lossClass() + != RedisScriptDescriptor.LossClass.EMPTY_REDIS_COLD_START_OR_RESET + || descriptor.compatibilityLevel() + != RedisScriptDescriptor.CompatibilityLevel.REQUIRES_CLUSTER_RESET + || !descriptor + .supportedCoexistence() + .equals(List.of(new RedisScriptDescriptor.SupportedCoexistence("v1", "none"))) + || descriptor.legacyPayloadShape() != null) throw unavailable(); + return descriptor; + } catch (RuntimeException failure) { + throw unavailable(failure); + } + } + + private static byte[] scriptSource(RedisScriptDescriptor descriptor) { + try (InputStream input = + CanonicalGameplayAccountInitialBarrierRedisOwner.class + .getClassLoader() + .getResourceAsStream(descriptor.resourcePath())) { + if (input == null) throw unavailable(); + byte[] bytes = input.readNBytes(MAX_SCRIPT_BYTES + 1); + if (bytes.length == 0 + || bytes.length > MAX_SCRIPT_BYTES + || !descriptor.sha256().equals(digest("SHA-256", bytes))) throw unavailable(); + return bytes; + } catch (IOException | RuntimeException failure) { + throw unavailable(failure); + } + } + + private static CanonicalGameplayAccountInitialOpenProof currentProof( + CanonicalGameplayAccountInitialBarrierInitializerRepository.InitializerSnapshot snapshot, + String key, + Map fields, + CanonicalGameplayProtectedIncarnationReceiver.VerifiedIncarnation currentObservation) { + return new CanonicalGameplayAccountInitialOpenProof.CurrentOpen( + snapshot.initializerId(), + snapshot.originalRequestId(), + snapshot.originalCallerContextId(), + snapshot.originalAttemptFence(), + snapshot.accountId(), + snapshot.tenantId(), + snapshot.playableStateNamespaceId(), + key, + snapshot.sourceControlEpoch(), + snapshot.inventorySnapshotRevision(), + snapshot.accountLoginEvidenceDigest(), + snapshot.sourceControlDigest(), + snapshot.beforeIncarnationDigest(), + currentObservation.issuedAtEpochMillis(), + currentObservation.expiresAtEpochMillis(), + fields); + } + + private static CanonicalGameplayAccountInitialOpenProof refused( + CanonicalGameplayAccountInitialOpenProof.Reason reason) { + return new CanonicalGameplayAccountInitialOpenProof.Refused(reason); + } + + private static CanonicalGameplayAccountInitialOpenProof.Reason classifyRefusal( + CanonicalGameplayAccountInitialBarrierInitializerRepository.InitializerSnapshot snapshot) { + return snapshot.state() + == CanonicalGameplayAccountInitialBarrierInitializerRepository.State.DISPATCH_POSSIBLE + ? CanonicalGameplayAccountInitialOpenProof.Reason.REMOTE_OUTCOME_UNCERTAIN + : CanonicalGameplayAccountInitialOpenProof.Reason.PHYSICAL_VALUE_MISSING_OR_CONFLICTING; + } + + private static RedisAsyncCommands requireCommands( + StatefulRedisConnection connection) { + if (connection == null || !connection.isOpen()) throw unavailable(); + RedisAsyncCommands commands = connection.async(); + if (commands == null) throw unavailable(); + return commands; + } + + private static void requirePrincipal(String principal) { + if (!PRINCIPAL.equals(principal)) throw unavailable(); + } + + private static byte[] ascii(String value) { + Objects.requireNonNull(value, "ASCII value"); + for (int index = 0; index < value.length(); index++) { + if (value.charAt(index) > 0x7f) throw unavailable(); + } + return value.getBytes(StandardCharsets.US_ASCII); + } + + private static String asciiString(byte[] value) { + Objects.requireNonNull(value, "Redis field"); + for (byte character : value) if ((character & 0x80) != 0) throw unavailable(); + return new String(value, StandardCharsets.US_ASCII); + } + + private static String digest(String algorithm, byte[] bytes) { + try { + return HexFormat.of().formatHex(MessageDigest.getInstance(algorithm).digest(bytes)); + } catch (Exception failure) { + throw unavailable(failure); + } + } + + private static T await(RedisFuture future) { + if (future == null) throw unavailable(); + try { + return future.get(COMMAND_TIMEOUT_MILLIS, TimeUnit.MILLISECONDS); + } catch (InterruptedException interrupted) { + Thread.currentThread().interrupt(); + throw unavailable(interrupted); + } catch (ExecutionException | TimeoutException failure) { + throw unavailable(failure); + } + } + + private void requireNoAmbientTransaction() { + repository.requireNoAmbientTransaction(); + } + + private static RedisScriptDescriptor.OutcomeSpec outcome( + String code, + RedisScriptDescriptor.OutcomeCategory category, + RedisScriptDescriptor.MutationEffect effect) { + return new RedisScriptDescriptor.OutcomeSpec(code, category, effect); + } + + private static IllegalStateException unavailable() { + return new IllegalStateException("INITIAL account barrier is unavailable"); + } + + private static IllegalStateException unavailable(Throwable cause) { + return new IllegalStateException("INITIAL account barrier is unavailable", cause); + } + + private static boolean isNil(UUID value) { + return value == null || value.equals(new UUID(0L, 0L)); + } + + record Readback( + UUID initializerId, + UUID originalRequestId, + UUID accountId, + UUID tenantId, + UUID playableStateNamespaceId, + String accountLoginEvidenceDigest, + String sourceControlDigest, + BigInteger inventorySnapshotRevision, + String key, + CanonicalGameplayTenantGameplayTagRepository.Assignment assignment, + CanonicalGameplayAccountInitialBarrierValue value, + Map barrierFields, + CanonicalGameplayProtectedIncarnationReceiver.VerifiedIncarnation beforeIncarnation, + CanonicalGameplayProtectedIncarnationReceiver.VerifiedIncarnation afterIncarnation, + long scriptOutcome) { + Readback( + CanonicalGameplayAccountInitialBarrierInitializerRepository.InitializerSnapshot snapshot, + CanonicalGameplayTenantGameplayTagRepository.Assignment assignment, + String key, + CanonicalGameplayAccountInitialBarrierValue value, + Map barrierFields, + CanonicalGameplayProtectedIncarnationReceiver.VerifiedIncarnation beforeIncarnation, + CanonicalGameplayProtectedIncarnationReceiver.VerifiedIncarnation afterIncarnation, + long scriptOutcome) { + this( + snapshot.initializerId(), + snapshot.originalRequestId(), + snapshot.accountId(), + snapshot.tenantId(), + snapshot.playableStateNamespaceId(), + snapshot.accountLoginEvidenceDigest(), + snapshot.sourceControlDigest(), + snapshot.inventorySnapshotRevision(), + key, + assignment, + value, + barrierFields, + beforeIncarnation, + afterIncarnation, + scriptOutcome); + } + + Readback { + Objects.requireNonNull(initializerId, "initializerId"); + Objects.requireNonNull(originalRequestId, "originalRequestId"); + Objects.requireNonNull(accountId, "accountId"); + Objects.requireNonNull(tenantId, "tenantId"); + Objects.requireNonNull(playableStateNamespaceId, "playableStateNamespaceId"); + Objects.requireNonNull(accountLoginEvidenceDigest, "accountLoginEvidenceDigest"); + Objects.requireNonNull(sourceControlDigest, "sourceControlDigest"); + Objects.requireNonNull(inventorySnapshotRevision, "inventorySnapshotRevision"); + Objects.requireNonNull(key, "key"); + Objects.requireNonNull(assignment, "assignment"); + Objects.requireNonNull(value, "value"); + barrierFields = Map.copyOf(Objects.requireNonNull(barrierFields, "barrierFields")); + Objects.requireNonNull(beforeIncarnation, "beforeIncarnation"); + Objects.requireNonNull(afterIncarnation, "afterIncarnation"); + if (scriptOutcome < 0 + || scriptOutcome > 1 + || !CanonicalGameplayAccountInitialBarrierValue.FIELDS.equals(barrierFields.keySet()) + || !value.fields().equals(barrierFields) + || !CanonicalGameplayAccountInitialBarrierKey.forTarget( + assignment, initializerId, originalRequestId) + .equals(key) + || !initializerId.equals(assignment.initialBarrierInitializerId()) + || !originalRequestId.equals(assignment.initialBarrierOriginalRequestId()) + || !accountId.equals(assignment.accountId()) + || !tenantId.equals(assignment.tenantId()) + || !playableStateNamespaceId.equals(assignment.playableStateNamespaceId())) { + throw unavailable(); + } + } + } +} diff --git a/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/repository/CanonicalGameplayAccountInitialBarrierValue.java b/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/repository/CanonicalGameplayAccountInitialBarrierValue.java new file mode 100644 index 0000000000..e387d9bdfd --- /dev/null +++ b/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/repository/CanonicalGameplayAccountInitialBarrierValue.java @@ -0,0 +1,81 @@ +package net.firedevops.firemud.gamesession.repository; + +import java.math.BigInteger; +import java.util.LinkedHashMap; +import java.util.Map; +import java.util.Objects; +import java.util.Set; +import java.util.UUID; + +/** + * Exact nine-field physical INITIAL OPEN value; it carries no later Account or issuer authority. + */ +final class CanonicalGameplayAccountInitialBarrierValue { + static final String SCHEMA = "gs_account_admission_barrier/v1"; + static final String OPEN = "OPEN"; + static final Set FIELDS = + Set.of( + "schema", + "accountId", + "tenantId", + "playableStateNamespaceId", + "tenantGameplayTag", + "ownerOperationId", + "ownerFenceEpoch", + "incarnationDigest", + "state"); + + private final Map fields; + + private CanonicalGameplayAccountInitialBarrierValue(Map fields) { + if (!FIELDS.equals(fields.keySet())) { + throw new IllegalArgumentException("INITIAL barrier fields are not exact"); + } + this.fields = Map.copyOf(fields); + } + + static CanonicalGameplayAccountInitialBarrierValue open( + UUID accountId, + UUID tenantId, + UUID namespaceId, + String tenantGameplayTag, + UUID initializerId, + BigInteger ownerFenceEpoch, + String incarnationDigest) { + requireNonNil(accountId, "account id"); + requireNonNil(tenantId, "tenant id"); + requireNonNil(namespaceId, "namespace id"); + requireNonNil(initializerId, "initializer id"); + if (tenantGameplayTag == null + || !tenantGameplayTag.matches("g[1-9][0-9]{0,9}-[0-9a-f]{32}") + || ownerFenceEpoch == null + || ownerFenceEpoch.signum() < 0 + || ownerFenceEpoch.toString().length() > 256 + || incarnationDigest == null + || !incarnationDigest.matches("sha256:[0-9a-f]{64}")) { + throw new IllegalArgumentException("INITIAL barrier target or incarnation is invalid"); + } + Map fields = new LinkedHashMap<>(); + fields.put("schema", SCHEMA); + fields.put("accountId", accountId.toString()); + fields.put("tenantId", tenantId.toString()); + fields.put("playableStateNamespaceId", namespaceId.toString()); + fields.put("tenantGameplayTag", tenantGameplayTag); + fields.put("ownerOperationId", initializerId.toString()); + fields.put("ownerFenceEpoch", ownerFenceEpoch.toString()); + fields.put("incarnationDigest", incarnationDigest); + fields.put("state", OPEN); + return new CanonicalGameplayAccountInitialBarrierValue(fields); + } + + Map fields() { + return fields; + } + + private static void requireNonNil(UUID value, String name) { + Objects.requireNonNull(value, name); + if (value.equals(new UUID(0L, 0L))) { + throw new IllegalArgumentException(name + " must not be nil"); + } + } +} diff --git a/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/repository/CanonicalGameplayAccountInitialOpenProof.java b/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/repository/CanonicalGameplayAccountInitialOpenProof.java new file mode 100644 index 0000000000..91366a7cdc --- /dev/null +++ b/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/repository/CanonicalGameplayAccountInitialOpenProof.java @@ -0,0 +1,88 @@ +package net.firedevops.firemud.gamesession.repository; + +import java.math.BigInteger; +import java.util.Map; +import java.util.Objects; +import java.util.UUID; + +/** + * Owner-issued current OPEN proof, or a typed refusal that cannot be used as admission evidence. + */ +sealed interface CanonicalGameplayAccountInitialOpenProof + permits CanonicalGameplayAccountInitialOpenProof.CurrentOpen, + CanonicalGameplayAccountInitialOpenProof.Refused { + record CurrentOpen( + UUID initializerId, + UUID originalRequestId, + UUID originalCallerContextId, + long originalAttemptFence, + UUID accountId, + UUID tenantId, + UUID playableStateNamespaceId, + String key, + BigInteger sourceControlEpoch, + BigInteger inventorySnapshotRevision, + String accountLoginEvidenceDigest, + String sourceControlDigest, + String incarnationDigest, + long issuedAtEpochMillis, + long expiresAtEpochMillis, + Map exactFields) + implements CanonicalGameplayAccountInitialOpenProof { + public CurrentOpen { + Objects.requireNonNull(initializerId, "initializerId"); + Objects.requireNonNull(originalRequestId, "originalRequestId"); + Objects.requireNonNull(originalCallerContextId, "originalCallerContextId"); + Objects.requireNonNull(accountId, "accountId"); + Objects.requireNonNull(tenantId, "tenantId"); + Objects.requireNonNull(playableStateNamespaceId, "playableStateNamespaceId"); + Objects.requireNonNull(key, "key"); + Objects.requireNonNull(sourceControlEpoch, "sourceControlEpoch"); + Objects.requireNonNull(inventorySnapshotRevision, "inventorySnapshotRevision"); + requireDigest(accountLoginEvidenceDigest, "accountLoginEvidenceDigest"); + requireDigest(sourceControlDigest, "sourceControlDigest"); + requireDigest(incarnationDigest, "incarnationDigest"); + exactFields = Map.copyOf(Objects.requireNonNull(exactFields, "exactFields")); + if (originalAttemptFence <= 0L + || sourceControlEpoch.signum() < 0 + || sourceControlEpoch.toString().length() > 256 + || inventorySnapshotRevision.signum() <= 0 + || issuedAtEpochMillis <= 0 + || expiresAtEpochMillis <= issuedAtEpochMillis + || !CanonicalGameplayAccountInitialBarrierValue.FIELDS.equals(exactFields.keySet()) + || !"OPEN".equals(exactFields.get("state")) + || !sourceControlEpoch.toString().equals(exactFields.get("ownerFenceEpoch")) + || !initializerId.toString().equals(exactFields.get("ownerOperationId")) + || !accountId.toString().equals(exactFields.get("accountId")) + || !tenantId.toString().equals(exactFields.get("tenantId")) + || !playableStateNamespaceId + .toString() + .equals(exactFields.get("playableStateNamespaceId")) + || !incarnationDigest.equals(exactFields.get("incarnationDigest"))) { + throw new IllegalArgumentException("Current INITIAL OPEN proof is malformed"); + } + } + } + + record Refused(Reason reason) implements CanonicalGameplayAccountInitialOpenProof { + public Refused { + Objects.requireNonNull(reason, "reason"); + } + } + + enum Reason { + ORIGINAL_ATTEMPT_MISMATCH, + SOURCE_CONTROL_UNAVAILABLE, + TARGET_NEVER_DISPATCHED, + REMOTE_OUTCOME_UNCERTAIN, + PHYSICAL_VALUE_MISSING_OR_CONFLICTING, + PROTECTED_OBSERVATION_UNAVAILABLE, + CURRENT_CONTROL_CHANGED + } + + private static void requireDigest(String value, String name) { + if (value == null || !value.matches("sha256:[0-9a-f]{64}")) { + throw new IllegalArgumentException(name + " must be canonical SHA-256"); + } + } +} diff --git a/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/repository/CanonicalGameplayBindingInventoryRepository.java b/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/repository/CanonicalGameplayBindingInventoryRepository.java index a4c7780413..4037b68a77 100644 --- a/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/repository/CanonicalGameplayBindingInventoryRepository.java +++ b/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/repository/CanonicalGameplayBindingInventoryRepository.java @@ -105,6 +105,8 @@ CanonicalGameplayBindingTransitionSnapshot prepareAfterInstalledIssuerAnchor( CanonicalGameplayIssuerBootstrapCoverageRepository .readInstalledAnchorForBindingPreparationInTransaction( transaction, currentIssuerState); + CanonicalGameplayIssuerAdmissionControlRepository.requireOpenInTransaction( + transaction, actualAnchor, currentIssuerState); InstalledAnchorPreparationContext context = new InstalledAnchorPreparationContext(revision, actualAnchor, currentIssuerState); CanonicalGameplayBindingTransitionRequest request = diff --git a/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/repository/CanonicalGameplayIssuerAdmissionBarrierKey.java b/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/repository/CanonicalGameplayIssuerAdmissionBarrierKey.java new file mode 100644 index 0000000000..9a0a8c66a5 --- /dev/null +++ b/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/repository/CanonicalGameplayIssuerAdmissionBarrierKey.java @@ -0,0 +1,39 @@ +package net.firedevops.firemud.gamesession.repository; + +import java.util.Objects; +import java.util.UUID; +import net.firedevops.firemud.gamesession.repository.CanonicalGameplayTenantGameplayTagRepository.Assignment; + +/** Builds the one tenant-slot issuer barrier key from persisted tenant placement evidence. */ +final class CanonicalGameplayIssuerAdmissionBarrierKey { + private CanonicalGameplayIssuerAdmissionBarrierKey() {} + + static String forTarget(String issuerId, Assignment assignment) { + Objects.requireNonNull(assignment, "assignment"); + return forTarget( + issuerId, + assignment.tenantId(), + assignment.playableStateNamespaceId(), + assignment.tenantGameplayTag()); + } + + static String forTarget(String issuerId, UUID tenantId, UUID namespaceId, String tag) { + Objects.requireNonNull(tenantId, "tenantId"); + Objects.requireNonNull(namespaceId, "playableStateNamespaceId"); + Objects.requireNonNull(tag, "tenantGameplayTag"); + if (!net.firedevops.firemud.common.security.GameSessionAccountDelegationProfile.ISSUER.equals( + issuerId) + || !tag.matches("g[1-9][0-9]{0,9}-[0-9a-f]{32}")) { + throw new IllegalArgumentException( + "Issuer barrier key requires exact Account issuer placement"); + } + return "session:game:issuer-admission:{" + + tag + + "}:" + + issuerId + + ":" + + tenantId + + ":" + + namespaceId; + } +} diff --git a/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/repository/CanonicalGameplayIssuerAdmissionBarrierRedisOwner.java b/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/repository/CanonicalGameplayIssuerAdmissionBarrierRedisOwner.java new file mode 100644 index 0000000000..048235e95f --- /dev/null +++ b/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/repository/CanonicalGameplayIssuerAdmissionBarrierRedisOwner.java @@ -0,0 +1,600 @@ +package net.firedevops.firemud.gamesession.repository; + +import io.lettuce.core.RedisFuture; +import io.lettuce.core.ScriptOutputType; +import io.lettuce.core.api.StatefulRedisConnection; +import io.lettuce.core.api.async.RedisAsyncCommands; +import io.lettuce.core.codec.ByteArrayCodec; +import java.io.IOException; +import java.io.InputStream; +import java.nio.charset.StandardCharsets; +import java.security.MessageDigest; +import java.util.Arrays; +import java.util.HashMap; +import java.util.HexFormat; +import java.util.List; +import java.util.Map; +import java.util.Objects; +import java.util.UUID; +import java.util.concurrent.ExecutionException; +import java.util.concurrent.TimeUnit; +import java.util.concurrent.TimeoutException; +import net.firedevops.firemud.common.redis.contracts.RedisScriptCatalog; +import net.firedevops.firemud.common.redis.contracts.RedisScriptDescriptor; +import net.firedevops.firemud.gamesession.service.CanonicalGameplayIssuerAdmissionBarrierRedisScriptContribution; +import org.springframework.transaction.support.TransactionSynchronizationManager; + +/** Explicit manual owner for exact one-key issuer tenant barrier projection and readback. */ +final class CanonicalGameplayIssuerAdmissionBarrierRedisOwner { + private static final String PRINCIPAL = "gamesession_coord_app"; + private static final String KEY_PREFIX = "session:game:issuer-admission:"; + private static final int MAX_SCRIPT_BYTES = 32 * 1024; + private static final long COMMAND_TIMEOUT_MILLIS = 5_000; + private static final List FIELDS = + List.of( + "schema", + "issuerId", + "tenantId", + "playableStateNamespaceId", + "tenantGameplayTag", + "state", + "admissionEpoch", + "ownerOperationId", + "initializerOperationId", + "initializerEpoch", + "initializerDigest", + "payloadDigest", + "payload"); + + private final io.lettuce.core.RedisClient redisClient; + private final RedisScriptCatalog catalog; + private final ProjectionRepository repository; + private final CanonicalGameplayIssuerBootstrapPartitionRedisOwner.CurrentIssuerStateSource + currentStateSource; + + CanonicalGameplayIssuerAdmissionBarrierRedisOwner( + io.lettuce.core.RedisClient redisClient, + RedisScriptCatalog catalog, + ProjectionRepository repository, + CanonicalGameplayIssuerBootstrapPartitionRedisOwner.CurrentIssuerStateSource + currentStateSource) { + this.redisClient = Objects.requireNonNull(redisClient, "Configured Redis client is required"); + this.catalog = Objects.requireNonNull(catalog, "Manual Redis script catalog is required"); + this.repository = + Objects.requireNonNull(repository, "Actual SQL projection repository is required"); + this.currentStateSource = + Objects.requireNonNull(currentStateSource, "Fresh issuer source is required"); + } + + /** Writes and independently reads back one exact original initializer's OPEN payload. */ + Readback initializeAndRead(UUID operationId) { + Objects.requireNonNull(operationId, "operationId"); + try { + requireNoAmbientTransaction(); + PreparedInitializer prepared = repository.readPreparedInitializer(operationId); + requireCurrentState(prepared.value().initializer()); + repository.requireStillCurrent(prepared); + RedisScriptDescriptor descriptor = + requireDescriptor( + CanonicalGameplayIssuerAdmissionBarrierRedisScriptContribution.OPEN_SCRIPT_ID, + CanonicalGameplayIssuerAdmissionBarrierRedisScriptContribution.OPEN_RESOURCE_PATH, + OPEN_ARGUMENTS, + OPEN_OUTCOMES); + byte[] script = scriptSource(descriptor); + CanonicalGameplayIssuerAdmissionBarrierValue value = prepared.value(); + byte[] payload = value.exactBytes(); + byte[] key = ascii(prepared.key()); + byte[][] arguments = { + ascii(value.issuerId()), + ascii(value.tenantId().toString()), + ascii(value.playableStateNamespaceId().toString()), + ascii(value.tenantGameplayTag()), + ascii(value.ownerOperationId().toString()), + ascii(value.admissionEpoch().toString()), + ascii(value.initializer().exactDigest()), + ascii(value.exactDigest()), + payload, + ascii(value.state().name()), + ascii("REPLAY_ONLY") + }; + byte[] createOnce = ascii("CREATE_ONCE"); + long result; + requireNoAmbientTransaction(); + try (StatefulRedisConnection connection = + redisClient.connect(ByteArrayCodec.INSTANCE)) { + RedisAsyncCommands commands = requireCommands(connection); + requirePrincipal(await(commands.aclWhoami())); + String sha = await(commands.scriptLoad(script)); + if (!digest("SHA-1", script).equals(sha)) throw unavailable(); + requireNoAmbientTransaction(); + if (repository.claimFirstCreatePermit(prepared)) arguments[10] = createOnce; + // The claim commits before EVAL on this same preflighted connection. A lost SQL + // commit reply remains uncertain; later attempts retain replay-only behavior. + requireNoAmbientTransaction(); + Long reply = + await(commands.evalsha(sha, ScriptOutputType.INTEGER, new byte[][] {key}, arguments)); + if (reply == null) throw unavailable(); + result = reply; + } + if (result < 1 || result > 2) throw unavailable(); + byte[] observed = readExactPhysicalState(prepared.key(), value); + requireCurrentState(value.initializer()); + repository.requireStillCurrent(prepared); + Readback readback = new Readback(value, result, observed); + repository.recordOpenReadback(prepared, readback); + return readback; + } catch (RuntimeException failure) { + if (isUnavailable(failure)) throw failure; + throw unavailable(failure); + } + } + + /** Closes one exact captured cutoff target and independently reads back its CLOSED payload. */ + Readback closeAndRead(UUID operationId, UUID tenantId, UUID namespaceId) { + Objects.requireNonNull(operationId, "operationId"); + Objects.requireNonNull(tenantId, "tenantId"); + Objects.requireNonNull(namespaceId, "namespaceId"); + try { + requireNoAmbientTransaction(); + PreparedCutoffTarget prepared = + repository.readPreparedCutoffTarget(operationId, tenantId, namespaceId); + repository.requireStillCurrent(prepared); + RedisScriptDescriptor descriptor = + requireDescriptor( + CanonicalGameplayIssuerAdmissionBarrierRedisScriptContribution.CLOSE_SCRIPT_ID, + CanonicalGameplayIssuerAdmissionBarrierRedisScriptContribution.CLOSE_RESOURCE_PATH, + CLOSE_ARGUMENTS, + CLOSE_OUTCOMES); + byte[] script = scriptSource(descriptor); + CanonicalGameplayIssuerAdmissionBarrierValue closed = prepared.closedValue(); + CanonicalGameplayIssuerAdmissionBarrierValue.Initializer initializer = closed.initializer(); + CanonicalGameplayIssuerAdmissionBarrierValue expectedOpen = prepared.expectedOpenValue(); + byte[] payload = closed.exactBytes(); + long result = + writeOneKey( + script, + prepared.key(), + ascii(closed.issuerId()), + ascii(closed.tenantId().toString()), + ascii(closed.playableStateNamespaceId().toString()), + ascii(closed.tenantGameplayTag()), + ascii(closed.ownerOperationId().toString()), + ascii(closed.admissionEpoch().toString()), + ascii(closed.exactDigest()), + payload, + ascii(initializer == null ? "none" : initializer.operationId().toString()), + ascii(initializer == null ? "0" : initializer.admissionEpoch().toString()), + ascii(initializer == null ? "none" : initializer.exactDigest()), + ascii(expectedOpen == null ? "none" : expectedOpen.exactDigest()), + expectedOpen == null ? new byte[0] : expectedOpen.exactBytes(), + ascii(closed.state().name())); + if (result < 1 || result > 3) throw unavailable(); + byte[] observed = readExactPhysicalState(prepared.key(), closed); + repository.requireStillCurrent(prepared); + Readback readback = new Readback(closed, result, observed); + repository.recordClosedReadback(prepared, readback); + return readback; + } catch (RuntimeException failure) { + if (isUnavailable(failure)) throw failure; + throw unavailable(failure); + } + } + + private void requireCurrentState( + CanonicalGameplayIssuerAdmissionBarrierValue.Initializer initializer) { + requireNoAmbientTransaction(); + CanonicalGameplayIssuerBootstrapPartitionRedisOwner.CurrentIssuerState current; + try { + current = currentStateSource.readFreshCurrentState(); + } catch (RuntimeException failure) { + throw unavailable(failure); + } + if (current == null || !initializer.matchesCurrentIssuerState(current)) throw unavailable(); + } + + private byte[] readExactPhysicalState( + String key, CanonicalGameplayIssuerAdmissionBarrierValue expected) { + requireNoAmbientTransaction(); + byte[] keyBytes = ascii(key); + try (StatefulRedisConnection connection = + redisClient.connect(ByteArrayCodec.INSTANCE)) { + RedisAsyncCommands commands = requireCommands(connection); + requirePrincipal(await(commands.aclWhoami())); + if (!"hash".equals(await(commands.type(keyBytes))) + || !Long.valueOf(-1L).equals(await(commands.pttl(keyBytes)))) throw unavailable(); + Long length = await(commands.hlen(keyBytes)); + if (length == null || length != FIELDS.size()) throw unavailable(); + Map raw = await(commands.hgetall(keyBytes)); + if (raw == null || raw.size() != FIELDS.size()) throw unavailable(); + Map actual = new HashMap<>(); + for (Map.Entry entry : raw.entrySet()) { + String field = asciiString(entry.getKey()); + if (!FIELDS.contains(field) + || actual.putIfAbsent(field, Objects.requireNonNull(entry.getValue()).clone()) + != null) { + throw unavailable(); + } + } + Map wanted = physicalFields(expected); + if (actual.size() != wanted.size()) throw unavailable(); + for (Map.Entry entry : wanted.entrySet()) { + if (!Arrays.equals(actual.get(entry.getKey()), entry.getValue())) throw unavailable(); + } + byte[] payload = actual.get("payload"); + CanonicalGameplayIssuerAdmissionBarrierValue decoded = + CanonicalGameplayIssuerAdmissionBarrierValue.decode(payload); + if (!Arrays.equals(decoded.exactBytes(), expected.exactBytes()) + || !decoded.exactDigest().equals(expected.exactDigest())) throw unavailable(); + return payload.clone(); + } catch (RuntimeException failure) { + throw unavailable(failure); + } + } + + private long writeOneKey(byte[] script, String key, byte[]... arguments) { + return writeOneKey(script, ascii(key), arguments); + } + + private long writeOneKey(byte[] script, byte[] key, byte[]... arguments) { + requireNoAmbientTransaction(); + try (StatefulRedisConnection connection = + redisClient.connect(ByteArrayCodec.INSTANCE)) { + RedisAsyncCommands commands = requireCommands(connection); + requirePrincipal(await(commands.aclWhoami())); + String sha = await(commands.scriptLoad(script)); + if (!digest("SHA-1", script).equals(sha)) throw unavailable(); + Long reply = + await(commands.evalsha(sha, ScriptOutputType.INTEGER, new byte[][] {key}, arguments)); + if (reply == null) throw unavailable(); + return reply; + } catch (RuntimeException failure) { + throw unavailable(failure); + } + } + + private RedisScriptDescriptor requireDescriptor( + String scriptId, + String resourcePath, + List arguments, + List outcomes) { + try { + RedisScriptDescriptor descriptor = catalog.require(scriptId); + if (!scriptId.equals(descriptor.scriptId()) + || !resourcePath.equals(descriptor.resourcePath()) + || !"game-session-service".equals(descriptor.owner()) + || !PRINCIPAL.equals(descriptor.principal()) + || descriptor.role() != RedisScriptDescriptor.RedisRole.COORDINATION + || !List.of( + new RedisScriptDescriptor.KeySpec( + "issuerAdmissionBarrier", + KEY_PREFIX, + RedisScriptDescriptor.HashTagDeclaration.REQUIRED)) + .equals(descriptor.keys()) + || !arguments.equals(descriptor.arguments()) + || descriptor.category() != RedisScriptDescriptor.ScriptCategory.SESSION_CAS + || !outcomes.equals(descriptor.outcomes()) + || descriptor.resetSensitivity() != RedisScriptDescriptor.ResetSensitivity.CLUSTER + || descriptor.lossClass() + != RedisScriptDescriptor.LossClass.EMPTY_REDIS_COLD_START_OR_RESET + || descriptor.compatibilityLevel() + != RedisScriptDescriptor.CompatibilityLevel.REQUIRES_CLUSTER_RESET + || !descriptor + .supportedCoexistence() + .equals(List.of(new RedisScriptDescriptor.SupportedCoexistence("v1", "none"))) + || descriptor.legacyPayloadShape() != null) throw unavailable(); + return descriptor; + } catch (RuntimeException failure) { + throw unavailable(failure); + } + } + + private static byte[] scriptSource(RedisScriptDescriptor descriptor) { + try (InputStream input = + CanonicalGameplayIssuerAdmissionBarrierRedisOwner.class + .getClassLoader() + .getResourceAsStream(descriptor.resourcePath())) { + if (input == null) throw unavailable(); + byte[] bytes = input.readNBytes(MAX_SCRIPT_BYTES + 1); + if (bytes.length == 0 + || bytes.length > MAX_SCRIPT_BYTES + || !descriptor.sha256().equals(digest("SHA-256", bytes))) throw unavailable(); + return bytes; + } catch (IOException | RuntimeException failure) { + throw unavailable(failure); + } + } + + private static Map physicalFields( + CanonicalGameplayIssuerAdmissionBarrierValue value) { + var initializer = value.initializer(); + Map fields = new HashMap<>(); + fields.put("schema", ascii(CanonicalGameplayIssuerAdmissionBarrierValue.SCHEMA)); + fields.put("issuerId", ascii(value.issuerId())); + fields.put("tenantId", ascii(value.tenantId().toString())); + fields.put("playableStateNamespaceId", ascii(value.playableStateNamespaceId().toString())); + fields.put("tenantGameplayTag", ascii(value.tenantGameplayTag())); + fields.put("state", ascii(value.state().name())); + fields.put("admissionEpoch", ascii(value.admissionEpoch().toString())); + fields.put("ownerOperationId", ascii(value.ownerOperationId().toString())); + fields.put( + "initializerOperationId", + ascii(initializer == null ? "none" : initializer.operationId().toString())); + fields.put( + "initializerEpoch", + ascii(initializer == null ? "0" : initializer.admissionEpoch().toString())); + fields.put( + "initializerDigest", ascii(initializer == null ? "none" : initializer.exactDigest())); + fields.put("payloadDigest", ascii(value.exactDigest())); + fields.put("payload", value.exactBytes()); + return fields; + } + + private static RedisAsyncCommands requireCommands( + StatefulRedisConnection connection) { + if (connection == null || !connection.isOpen()) throw unavailable(); + RedisAsyncCommands commands = connection.async(); + if (commands == null) throw unavailable(); + return commands; + } + + private static void requirePrincipal(String principal) { + if (!PRINCIPAL.equals(principal)) throw unavailable(); + } + + private static byte[] ascii(String value) { + Objects.requireNonNull(value, "ASCII value"); + for (int index = 0; index < value.length(); index++) { + if (value.charAt(index) > 0x7f) throw unavailable(); + } + return value.getBytes(StandardCharsets.US_ASCII); + } + + private static String asciiString(byte[] value) { + Objects.requireNonNull(value, "Redis field"); + for (byte character : value) if ((character & 0x80) != 0) throw unavailable(); + return new String(value, StandardCharsets.US_ASCII); + } + + private static String digest(String algorithm, byte[] bytes) { + try { + return HexFormat.of().formatHex(MessageDigest.getInstance(algorithm).digest(bytes)); + } catch (Exception failure) { + throw unavailable(failure); + } + } + + private static T await(RedisFuture future) { + if (future == null) throw unavailable(); + try { + return future.get(COMMAND_TIMEOUT_MILLIS, TimeUnit.MILLISECONDS); + } catch (InterruptedException interrupted) { + Thread.currentThread().interrupt(); + throw unavailable(interrupted); + } catch (ExecutionException | TimeoutException failure) { + throw unavailable(failure); + } + } + + private static void requireNoAmbientTransaction() { + if (TransactionSynchronizationManager.isActualTransactionActive()) throw unavailable(); + } + + private static boolean isUnavailable(RuntimeException failure) { + return failure instanceof IllegalStateException + && failure.getMessage() != null + && failure.getMessage().contains("Issuer tenant admission barrier is unavailable"); + } + + private static IllegalStateException unavailable() { + return new IllegalStateException("Issuer tenant admission barrier is unavailable"); + } + + private static IllegalStateException unavailable(Throwable cause) { + return new IllegalStateException("Issuer tenant admission barrier is unavailable", cause); + } + + private static final List OPEN_ARGUMENTS = + List.of( + new RedisScriptDescriptor.ArgumentSpec("issuerId"), + new RedisScriptDescriptor.ArgumentSpec("tenantId"), + new RedisScriptDescriptor.ArgumentSpec("playableStateNamespaceId"), + new RedisScriptDescriptor.ArgumentSpec("tenantGameplayTag"), + new RedisScriptDescriptor.ArgumentSpec("initializerOperationId"), + new RedisScriptDescriptor.ArgumentSpec("admissionBarrierEpoch"), + new RedisScriptDescriptor.ArgumentSpec("initializerTupleDigest"), + new RedisScriptDescriptor.ArgumentSpec("exactBarrierPayloadDigest"), + new RedisScriptDescriptor.ArgumentSpec("exactBarrierPayload"), + new RedisScriptDescriptor.ArgumentSpec("state"), + new RedisScriptDescriptor.ArgumentSpec("createMode")); + private static final List OPEN_OUTCOMES = + List.of( + outcome( + "OPEN_CREATED", + RedisScriptDescriptor.OutcomeCategory.SUCCESS, + RedisScriptDescriptor.MutationEffect.MUTATING), + outcome( + "OPEN_REPLAY", + RedisScriptDescriptor.OutcomeCategory.REPLAY, + RedisScriptDescriptor.MutationEffect.NON_MUTATING), + outcome( + "TYPE_TTL_OR_FIELDSET_REFUSED", + RedisScriptDescriptor.OutcomeCategory.VALIDATION_FAILURE, + RedisScriptDescriptor.MutationEffect.NON_MUTATING), + outcome( + "INVALID_ARGUMENTS_OR_TARGET", + RedisScriptDescriptor.OutcomeCategory.VALIDATION_FAILURE, + RedisScriptDescriptor.MutationEffect.NON_MUTATING), + outcome( + "CLOSED_OR_CONFLICTING_STATE", + RedisScriptDescriptor.OutcomeCategory.STALE, + RedisScriptDescriptor.MutationEffect.NON_MUTATING)); + private static final List CLOSE_ARGUMENTS = + List.of( + new RedisScriptDescriptor.ArgumentSpec("issuerId"), + new RedisScriptDescriptor.ArgumentSpec("tenantId"), + new RedisScriptDescriptor.ArgumentSpec("playableStateNamespaceId"), + new RedisScriptDescriptor.ArgumentSpec("tenantGameplayTag"), + new RedisScriptDescriptor.ArgumentSpec("cutoffOperationId"), + new RedisScriptDescriptor.ArgumentSpec("cutoffAdmissionBarrierEpoch"), + new RedisScriptDescriptor.ArgumentSpec("exactClosedPayloadDigest"), + new RedisScriptDescriptor.ArgumentSpec("exactClosedPayload"), + new RedisScriptDescriptor.ArgumentSpec("capturedInitializerOperationIdOrNone"), + new RedisScriptDescriptor.ArgumentSpec("capturedInitializerAdmissionBarrierEpochOrZero"), + new RedisScriptDescriptor.ArgumentSpec("capturedInitializerTupleDigestOrNone"), + new RedisScriptDescriptor.ArgumentSpec("expectedOriginalOpenPayloadDigestOrNone"), + new RedisScriptDescriptor.ArgumentSpec("expectedOriginalOpenPayloadOrEmpty"), + new RedisScriptDescriptor.ArgumentSpec("state")); + private static final List CLOSE_OUTCOMES = + List.of( + outcome( + "CLOSED_CREATED", + RedisScriptDescriptor.OutcomeCategory.SUCCESS, + RedisScriptDescriptor.MutationEffect.MUTATING), + outcome( + "CLOSED_REPLAY", + RedisScriptDescriptor.OutcomeCategory.REPLAY, + RedisScriptDescriptor.MutationEffect.NON_MUTATING), + outcome( + "CAPTURED_OPEN_CLOSED", + RedisScriptDescriptor.OutcomeCategory.SUCCESS, + RedisScriptDescriptor.MutationEffect.MUTATING), + outcome( + "TYPE_TTL_OR_FIELDSET_REFUSED", + RedisScriptDescriptor.OutcomeCategory.VALIDATION_FAILURE, + RedisScriptDescriptor.MutationEffect.NON_MUTATING), + outcome( + "INVALID_ARGUMENTS_OR_TARGET", + RedisScriptDescriptor.OutcomeCategory.VALIDATION_FAILURE, + RedisScriptDescriptor.MutationEffect.NON_MUTATING), + outcome( + "NEWER_CLOSED_OR_UNEXPECTED_STATE", + RedisScriptDescriptor.OutcomeCategory.STALE, + RedisScriptDescriptor.MutationEffect.NON_MUTATING)); + + private static RedisScriptDescriptor.OutcomeSpec outcome( + String code, + RedisScriptDescriptor.OutcomeCategory category, + RedisScriptDescriptor.MutationEffect effect) { + return new RedisScriptDescriptor.OutcomeSpec(code, category, effect); + } + + interface ProjectionRepository { + PreparedInitializer readPreparedInitializer(UUID operationId); + + /** Commits the sole first-create claim; false permits only replay of an existing OPEN. */ + boolean claimFirstCreatePermit(PreparedInitializer prepared); + + PreparedCutoffTarget readPreparedCutoffTarget( + UUID cutoffOperationId, UUID tenantId, UUID namespaceId); + + void requireStillCurrent(PreparedInitializer prepared); + + void requireStillCurrent(PreparedCutoffTarget prepared); + + void recordOpenReadback(PreparedInitializer prepared, Readback readback); + + void recordClosedReadback(PreparedCutoffTarget prepared, Readback readback); + } + + static final class PreparedInitializer { + private final CanonicalGameplayIssuerAdmissionBarrierValue value; + private final CanonicalGameplayTenantGameplayTagRepository.Assignment assignment; + private final UUID requestOperationId; + private final String key; + + PreparedInitializer( + CanonicalGameplayIssuerAdmissionBarrierValue value, + CanonicalGameplayTenantGameplayTagRepository.Assignment assignment, + UUID requestOperationId, + String key) { + this.value = Objects.requireNonNull(value, "value"); + this.assignment = assignment; + this.requestOperationId = Objects.requireNonNull(requestOperationId, "requestOperationId"); + this.key = Objects.requireNonNull(key, "key"); + if (value.state() != CanonicalGameplayIssuerAdmissionBarrierValue.State.OPEN + || !CanonicalGameplayIssuerAdmissionBarrierKey.forTarget( + value.issuerId(), + value.tenantId(), + value.playableStateNamespaceId(), + value.tenantGameplayTag()) + .equals(key)) throw unavailable(); + if (assignment == null) { + if (!requestOperationId.equals(value.initializer().operationId())) throw unavailable(); + } else if (!assignment.isBindingTransition() + || !assignment.tenantId().equals(value.tenantId()) + || !assignment.playableStateNamespaceId().equals(value.playableStateNamespaceId()) + || !assignment.tenantGameplayTag().equals(value.tenantGameplayTag())) { + throw unavailable(); + } + } + + CanonicalGameplayIssuerAdmissionBarrierValue value() { + return value; + } + + CanonicalGameplayTenantGameplayTagRepository.Assignment assignment() { + return assignment; + } + + UUID requestOperationId() { + return requestOperationId; + } + + String key() { + return key; + } + } + + record PreparedCutoffTarget( + CanonicalGameplayIssuerAdmissionBarrierValue closedValue, + CanonicalGameplayIssuerAdmissionBarrierValue expectedOpenValue, + String key) { + PreparedCutoffTarget { + Objects.requireNonNull(closedValue, "closedValue"); + Objects.requireNonNull(key, "key"); + if (closedValue.state() != CanonicalGameplayIssuerAdmissionBarrierValue.State.CLOSED + || (expectedOpenValue != null + && (expectedOpenValue.state() + != CanonicalGameplayIssuerAdmissionBarrierValue.State.OPEN + || closedValue.initializer() == null + || !Arrays.equals( + closedValue.initializer().exactBytes(), + expectedOpenValue.initializer().exactBytes()))) + || !CanonicalGameplayIssuerAdmissionBarrierKey.forTarget( + closedValue.issuerId(), + closedValue.tenantId(), + closedValue.playableStateNamespaceId(), + closedValue.tenantGameplayTag()) + .equals(key)) throw unavailable(); + } + } + + static final class Readback { + private final CanonicalGameplayIssuerAdmissionBarrierValue value; + private final long scriptOutcome; + private final byte[] exactPhysicalPayload; + + private Readback( + CanonicalGameplayIssuerAdmissionBarrierValue value, + long scriptOutcome, + byte[] exactPhysicalPayload) { + this.value = Objects.requireNonNull(value, "value"); + if (scriptOutcome < 1 || scriptOutcome > 3) throw unavailable(); + this.scriptOutcome = scriptOutcome; + this.exactPhysicalPayload = Objects.requireNonNull(exactPhysicalPayload).clone(); + if (!Arrays.equals(value.exactBytes(), this.exactPhysicalPayload)) throw unavailable(); + } + + CanonicalGameplayIssuerAdmissionBarrierValue value() { + return value; + } + + long scriptOutcome() { + return scriptOutcome; + } + + byte[] exactPhysicalPayload() { + return exactPhysicalPayload.clone(); + } + } +} diff --git a/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/repository/CanonicalGameplayIssuerAdmissionBarrierRedisOwnerFactory.java b/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/repository/CanonicalGameplayIssuerAdmissionBarrierRedisOwnerFactory.java new file mode 100644 index 0000000000..3f9a3acfa3 --- /dev/null +++ b/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/repository/CanonicalGameplayIssuerAdmissionBarrierRedisOwnerFactory.java @@ -0,0 +1,23 @@ +package net.firedevops.firemud.gamesession.repository; + +import io.lettuce.core.RedisClient; +import java.util.Objects; +import net.firedevops.firemud.common.redis.contracts.RedisScriptCatalog; + +/** Explicit manual factory; it does not register a runtime or ServiceLoader provider. */ +final class CanonicalGameplayIssuerAdmissionBarrierRedisOwnerFactory { + private CanonicalGameplayIssuerAdmissionBarrierRedisOwnerFactory() {} + + static CanonicalGameplayIssuerAdmissionBarrierRedisOwner create( + RedisClient redisClient, + RedisScriptCatalog catalog, + CanonicalGameplayIssuerAdmissionBarrierRedisOwner.ProjectionRepository repository, + CanonicalGameplayIssuerBootstrapPartitionRedisOwner.CurrentIssuerStateSource + currentStateSource) { + return new CanonicalGameplayIssuerAdmissionBarrierRedisOwner( + Objects.requireNonNull(redisClient, "redisClient"), + Objects.requireNonNull(catalog, "catalog"), + Objects.requireNonNull(repository, "repository"), + Objects.requireNonNull(currentStateSource, "currentStateSource")); + } +} diff --git a/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/repository/CanonicalGameplayIssuerAdmissionBarrierRepository.java b/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/repository/CanonicalGameplayIssuerAdmissionBarrierRepository.java new file mode 100644 index 0000000000..9d83b6dca5 --- /dev/null +++ b/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/repository/CanonicalGameplayIssuerAdmissionBarrierRepository.java @@ -0,0 +1,1021 @@ +package net.firedevops.firemud.gamesession.repository; + +import java.math.BigInteger; +import java.nio.charset.StandardCharsets; +import java.util.ArrayList; +import java.util.Arrays; +import java.util.List; +import java.util.Objects; +import java.util.UUID; +import net.firedevops.firemud.common.security.GameSessionAccountDelegationProfile; +import org.jooq.DSLContext; +import org.jooq.Record; +import org.jooq.impl.DSL; +import org.springframework.transaction.support.TransactionSynchronizationManager; + +/** SQL projection owner for immutable tenant OPEN initializers and issuer-wide CLOSED cutoffs. */ +final class CanonicalGameplayIssuerAdmissionBarrierRepository + implements CanonicalGameplayIssuerAdmissionBarrierRedisOwner.ProjectionRepository { + private static final String ISSUER = GameSessionAccountDelegationProfile.ISSUER; + private static final String CONTROL = "game_session_canonical_issuer_admission_control"; + private static final String INITIALIZER = "game_session_canonical_issuer_admission_initializer"; + private static final String INITIALIZER_RECEIPT = + "game_session_canonical_issuer_admission_initializer_receipt"; + private static final String CUTOFF_TARGET = + "game_session_canonical_issuer_admission_cutoff_target"; + private static final String LOCAL_OPERATION = + "game_session_canonical_issuer_binding_local_operation"; + private static final String TENANT_TAG = "game_session_canonical_tenant_gameplay_tag"; + + private final DSLContext dsl; + private final CanonicalGameplayTenantGameplayTagRepository tenantTags; + private final CanonicalGameplayIssuerBootstrapPartitionRedisOwner.CurrentIssuerStateSource + currentStateSource; + + CanonicalGameplayIssuerAdmissionBarrierRepository( + DSLContext dsl, + CanonicalGameplayTenantGameplayTagRepository tenantTags, + CanonicalGameplayIssuerBootstrapPartitionRedisOwner.CurrentIssuerStateSource + currentStateSource) { + this.dsl = Objects.requireNonNull(dsl, "dsl"); + this.tenantTags = Objects.requireNonNull(tenantTags, "tenantTags"); + this.currentStateSource = Objects.requireNonNull(currentStateSource, "currentStateSource"); + } + + /** Persists the original complete OPEN payload before the Redis owner is allowed to write it. */ + @Override + public CanonicalGameplayIssuerAdmissionBarrierRedisOwner.PreparedInitializer + readPreparedInitializer(UUID operationId) { + requireNonNil(operationId, "operationId"); + requireNoAmbientTransaction(); + Record originalOperationInitializer = + dsl.fetchOne( + "SELECT operation_id FROM " + INITIALIZER + " WHERE operation_id = ? AND issuer_id = ?", + operationId, + ISSUER); + CanonicalGameplayTenantGameplayTagRepository.Assignment requestAssignment = + originalOperationInitializer == null + ? tenantTags.assignmentForTransition(transitionForLocalOperation(operationId)) + : null; + CanonicalGameplayIssuerBootstrapPartitionRedisOwner.CurrentIssuerState before = + readCurrentState(); + PreparedInitializerSource source = + dsl.transactionResult( + configuration -> { + DSLContext transaction = DSL.using(configuration); + CanonicalGameplayBindingInventoryRepository.lockInventoryRevision(transaction); + if (requestAssignment != null) { + requireCurrentTagMapping( + transaction, + requestAssignment.tenantId(), + requestAssignment.tenantGameplayTag()); + } + CanonicalGameplayIssuerInstalledAnchor anchor = + CanonicalGameplayIssuerBootstrapCoverageRepository + .readInstalledAnchorForBindingPreparationInTransaction(transaction, before); + CanonicalGameplayIssuerAdmissionControlValue control = + CanonicalGameplayIssuerAdmissionControlRepository.requireOpenInTransaction( + transaction, anchor, before); + Record byOperation = + transaction.fetchOne( + "SELECT * FROM " + + INITIALIZER + + " WHERE operation_id = ? AND issuer_id = ? FOR UPDATE", + operationId, + ISSUER); + if (byOperation != null) { + CanonicalGameplayIssuerAdmissionBarrierValue frozen = + readFrozenInitializer(transaction, byOperation, null, anchor, control, before); + if (requestAssignment != null) { + requireSameTargetAssignment(requestAssignment, frozen.initializer()); + } + return new PreparedInitializerSource(frozen, null); + } + if (requestAssignment == null) { + throw conflict("The exact original tenant initializer disappeared"); + } + + CurrentRequestTarget requestTarget = + requireCurrentRequestTarget(transaction, operationId, requestAssignment, before); + Record targetInitializer = + transaction.fetchOne( + "SELECT * FROM " + + INITIALIZER + + " WHERE issuer_id = ? AND tenant_id = ?" + + " AND playable_state_namespace_id = ? AND live_barrier_epoch = ?" + + " FOR UPDATE", + ISSUER, + requestAssignment.tenantId(), + requestAssignment.playableStateNamespaceId(), + control.liveBarrierEpoch()); + if (targetInitializer != null) { + CanonicalGameplayIssuerAdmissionBarrierValue frozen = + readFrozenInitializer( + transaction, targetInitializer, requestAssignment, anchor, control, before); + return new PreparedInitializerSource(frozen, requestAssignment); + } + + CanonicalGameplayAdmissionBarrierTuple tuple = + buildOriginalInitializer( + transaction, + operationId, + requestTarget, + requestAssignment, + anchor, + control, + before); + CanonicalGameplayIssuerAdmissionBarrierValue original = + CanonicalGameplayIssuerAdmissionBarrierValue.open(tuple.initializer()); + persistOriginalInitializer(transaction, original); + return new PreparedInitializerSource(original, requestAssignment); + }); + CanonicalGameplayIssuerBootstrapPartitionRedisOwner.CurrentIssuerState current = + readCurrentState(); + CanonicalGameplayIssuerAdmissionBarrierValue value = source.value(); + if (!value.initializer().matchesCurrentIssuerState(current)) { + throw conflict("Original OPEN initializer no longer matches current Account issuer source"); + } + CanonicalGameplayIssuerAdmissionBarrierRedisOwner.PreparedInitializer prepared = + prepared(value, source.requestAssignment(), operationId); + requireStillCurrent(prepared); + return prepared; + } + + /** Starts the one issuer-wide live cutoff after resolving the complete durable target set. */ + CanonicalGameplayIssuerAdmissionControlValue beginCutoff(UUID operationId, UUID requestId) { + requireNonNil(operationId, "operationId"); + requireNonNil(requestId, "requestId"); + requireNoAmbientTransaction(); + CanonicalGameplayIssuerBootstrapPartitionRedisOwner.CurrentIssuerState before = + readCurrentState(); + CanonicalGameplayIssuerInstalledAnchor anchor = readInstalledAnchor(before); + CanonicalGameplayIssuerAdmissionControlValue pending = + new CanonicalGameplayIssuerAdmissionControlRepository(dsl) + .beginCutoff(operationId, requestId, anchor, before); + if (!pending.matchesCurrentIssuerState(readCurrentState())) { + throw conflict("Current issuer source or stable incarnation moved during cutoff capture"); + } + return pending; + } + + /** Completes the durable cutoff only after every frozen target has a CLOSED readback. */ + CanonicalGameplayIssuerAdmissionControlValue completeCutoff(UUID operationId) { + requireNonNil(operationId, "operationId"); + requireNoAmbientTransaction(); + CanonicalGameplayIssuerBootstrapPartitionRedisOwner.CurrentIssuerState before = + readCurrentState(); + CanonicalGameplayIssuerInstalledAnchor anchor = readInstalledAnchor(before); + CanonicalGameplayIssuerAdmissionControlValue installed = + new CanonicalGameplayIssuerAdmissionControlRepository(dsl) + .completeCutoff(operationId, anchor, before); + if (!installed.matchesCurrentIssuerState(readCurrentState())) { + throw conflict("Current issuer source or stable incarnation moved during cutoff completion"); + } + return installed; + } + + List + readPreparedCutoffTargets(UUID cutoffOperationId) { + requireNonNil(cutoffOperationId, "cutoffOperationId"); + List targets = + dsl.fetch( + "SELECT tenant_id, playable_state_namespace_id FROM " + + CUTOFF_TARGET + + " WHERE operation_id = ? AND issuer_id = ? ORDER BY target_ordinal", + cutoffOperationId, + ISSUER); + List prepared = + new ArrayList<>(); + for (Record target : targets) { + prepared.add( + readPreparedCutoffTarget( + cutoffOperationId, + requiredUuid(target, "tenant_id"), + requiredUuid(target, "playable_state_namespace_id"))); + } + return List.copyOf(prepared); + } + + @Override + public CanonicalGameplayIssuerAdmissionBarrierRedisOwner.PreparedCutoffTarget + readPreparedCutoffTarget(UUID cutoffOperationId, UUID tenantId, UUID namespaceId) { + requireNonNil(cutoffOperationId, "cutoffOperationId"); + requireNonNil(tenantId, "tenantId"); + requireNonNil(namespaceId, "namespaceId"); + requireNoAmbientTransaction(); + CanonicalGameplayIssuerBootstrapPartitionRedisOwner.CurrentIssuerState current = + readCurrentState(); + return dsl.transactionResult( + configuration -> { + DSLContext transaction = DSL.using(configuration); + CanonicalGameplayBindingInventoryRepository.lockInventoryRevision(transaction); + CanonicalGameplayIssuerInstalledAnchor anchor = + CanonicalGameplayIssuerBootstrapCoverageRepository + .readInstalledAnchorForBindingPreparationInTransaction(transaction, current); + CanonicalGameplayIssuerAdmissionControlValue control = + readCurrentControl(transaction, anchor, current); + if (!cutoffOperationId.equals(control.currentOperationId()) + || control.state() + != CanonicalGameplayIssuerAdmissionControlValue.State.CUTOFF_PENDING) { + throw conflict("The exact current issuer cutoff is not pending"); + } + new CanonicalGameplayIssuerAdmissionControlRepository(dsl) + .verifyCurrentCutoffTarget(transaction, control, tenantId, namespaceId, null); + Record target = + transaction.fetchOne( + "SELECT * FROM " + + CUTOFF_TARGET + + " WHERE operation_id = ? AND issuer_id = ? AND tenant_id = ?" + + " AND playable_state_namespace_id = ? FOR UPDATE", + cutoffOperationId, + ISSUER, + tenantId, + namespaceId); + if (target == null + || !tenantId.equals(requiredUuid(target, "tenant_id")) + || !namespaceId.equals(requiredUuid(target, "playable_state_namespace_id"))) { + throw conflict("The exact durable cutoff target is unavailable"); + } + String tenantTag = requireText(target, "tenant_gameplay_tag"); + requireCurrentTagMapping(transaction, tenantId, tenantTag); + CanonicalGameplayIssuerAdmissionBarrierValue closed = + CanonicalGameplayIssuerAdmissionBarrierValue.decode( + requireBytes(target, "closed_payload_bytes")); + byte[] capturedOpen = target.get("captured_open_payload_bytes", byte[].class); + CanonicalGameplayIssuerAdmissionBarrierValue expectedOpen = + capturedOpen == null + ? null + : CanonicalGameplayIssuerAdmissionBarrierValue.decode(capturedOpen); + if (!closed.exactDigest().equals(target.get("closed_payload_digest", String.class))) { + throw conflict("Persisted issuer cutoff target digest is invalid"); + } + return new CanonicalGameplayIssuerAdmissionBarrierRedisOwner.PreparedCutoffTarget( + closed, + expectedOpen, + CanonicalGameplayIssuerAdmissionBarrierKey.forTarget( + ISSUER, tenantId, namespaceId, tenantTag)); + }); + } + + @Override + public void requireStillCurrent( + CanonicalGameplayIssuerAdmissionBarrierRedisOwner.PreparedInitializer prepared) { + Objects.requireNonNull(prepared, "prepared"); + requireNoAmbientTransaction(); + CanonicalGameplayIssuerBootstrapPartitionRedisOwner.CurrentIssuerState current = + readCurrentState(); + CanonicalGameplayIssuerAdmissionBarrierValue.Initializer initializer = + prepared.value().initializer(); + if (!initializer.matchesCurrentIssuerState(current)) { + throw conflict("Original OPEN initializer no longer matches current Account issuer source"); + } + CanonicalGameplayTenantGameplayTagRepository.Assignment assignment = + prepared.assignment() == null + ? null + : tenantTags.assignmentForTransition(prepared.assignment().transitionId()); + if (assignment != null) requireSameAssignment(prepared.assignment(), assignment); + dsl.transactionResult( + configuration -> { + DSLContext transaction = DSL.using(configuration); + CanonicalGameplayBindingInventoryRepository.lockInventoryRevision(transaction); + CanonicalGameplayIssuerInstalledAnchor anchor = + CanonicalGameplayIssuerBootstrapCoverageRepository + .readInstalledAnchorForBindingPreparationInTransaction(transaction, current); + CanonicalGameplayIssuerAdmissionControlValue control = + CanonicalGameplayIssuerAdmissionControlRepository.requireOpenInTransaction( + transaction, anchor, current); + if (!control.liveBarrierEpoch().equals(initializer.admissionEpoch()) + || !control.currentOperationId().equals(anchor.bootstrapOperationId())) { + throw conflict("Original initializer no longer belongs to current OPEN live control"); + } + if (assignment != null) { + requireCurrentTagMapping( + transaction, assignment.tenantId(), assignment.tenantGameplayTag()); + requireCurrentRequestTarget( + transaction, prepared.requestOperationId(), assignment, current); + } + Record saved = + transaction.fetchOne( + "SELECT * FROM " + + INITIALIZER + + " WHERE operation_id = ? AND issuer_id = ? FOR UPDATE", + initializer.operationId(), + ISSUER); + readFrozenInitializer( + transaction, saved, prepared.assignment(), anchor, control, current); + return null; + }); + } + + @Override + public void requireStillCurrent( + CanonicalGameplayIssuerAdmissionBarrierRedisOwner.PreparedCutoffTarget prepared) { + Objects.requireNonNull(prepared, "prepared"); + requireNoAmbientTransaction(); + CanonicalGameplayIssuerBootstrapPartitionRedisOwner.CurrentIssuerState current = + readCurrentState(); + CanonicalGameplayIssuerAdmissionBarrierValue closed = prepared.closedValue(); + dsl.transactionResult( + configuration -> { + DSLContext transaction = DSL.using(configuration); + CanonicalGameplayBindingInventoryRepository.lockInventoryRevision(transaction); + CanonicalGameplayIssuerInstalledAnchor anchor = + CanonicalGameplayIssuerBootstrapCoverageRepository + .readInstalledAnchorForBindingPreparationInTransaction(transaction, current); + CanonicalGameplayIssuerAdmissionControlValue value = + readCurrentControl(transaction, anchor, current); + if (!closed.ownerOperationId().equals(value.currentOperationId()) + || value.state() != CanonicalGameplayIssuerAdmissionControlValue.State.CUTOFF_PENDING + || !closed.admissionEpoch().equals(value.liveBarrierEpoch())) { + throw conflict("Prepared CLOSED target no longer belongs to current pending cutoff"); + } + new CanonicalGameplayIssuerAdmissionControlRepository(dsl) + .verifyCurrentCutoffTarget( + transaction, + value, + closed.tenantId(), + closed.playableStateNamespaceId(), + closed.exactBytes()); + requireCurrentTagMapping(transaction, closed.tenantId(), closed.tenantGameplayTag()); + return null; + }); + } + + @Override + public void recordOpenReadback( + CanonicalGameplayIssuerAdmissionBarrierRedisOwner.PreparedInitializer prepared, + CanonicalGameplayIssuerAdmissionBarrierRedisOwner.Readback readback) { + Objects.requireNonNull(prepared, "prepared"); + Objects.requireNonNull(readback, "readback"); + requireStillCurrent(prepared); + CanonicalGameplayIssuerAdmissionBarrierValue value = prepared.value(); + if (!Arrays.equals(value.exactBytes(), readback.exactPhysicalPayload()) + || !Arrays.equals(value.exactBytes(), readback.value().exactBytes()) + || readback.scriptOutcome() < 1 + || readback.scriptOutcome() > 2) { + throw conflict("OPEN readback does not match the exact original initializer"); + } + CanonicalGameplayIssuerBootstrapPartitionRedisOwner.CurrentIssuerState current = + readCurrentState(); + dsl.transactionResult( + configuration -> { + DSLContext transaction = DSL.using(configuration); + CanonicalGameplayBindingInventoryRepository.lockInventoryRevision(transaction); + CanonicalGameplayIssuerInstalledAnchor anchor = + CanonicalGameplayIssuerBootstrapCoverageRepository + .readInstalledAnchorForBindingPreparationInTransaction(transaction, current); + CanonicalGameplayIssuerAdmissionControlRepository.requireOpenInTransaction( + transaction, anchor, current); + Record initializer = + transaction.fetchSingle( + "SELECT * FROM " + + INITIALIZER + + " WHERE operation_id = ? AND issuer_id = ? FOR UPDATE", + value.initializer().operationId(), + ISSUER); + requirePersistedInitializer(initializer, value); + String initializationState = initializer.get("initialization_state", String.class); + if (!List.of("INITIALIZING", "OPEN_CONFIRMED").contains(initializationState)) { + throw conflict("OPEN readback has no durable first-attempt initializer state"); + } + transaction.execute( + "INSERT INTO " + + INITIALIZER_RECEIPT + + " (operation_id, issuer_id, exact_open_payload_bytes," + + " exact_open_payload_digest, script_outcome) VALUES (?, ?, ?, ?, ?)" + + " ON CONFLICT (operation_id) DO NOTHING", + value.initializer().operationId(), + ISSUER, + value.exactBytes(), + value.exactDigest(), + (short) readback.scriptOutcome()); + Record receipt = + transaction.fetchOne( + "SELECT * FROM " + + INITIALIZER_RECEIPT + + " WHERE operation_id = ? AND issuer_id = ? FOR UPDATE", + value.initializer().operationId(), + ISSUER); + if (receipt == null + || !Arrays.equals( + requireBytes(receipt, "exact_open_payload_bytes"), value.exactBytes()) + || !value.exactDigest().equals(receipt.get("exact_open_payload_digest", String.class)) + || !List.of((short) 1, (short) 2) + .contains(receipt.get("script_outcome", Short.class))) { + throw conflict( + "Original OPEN readback receipt conflicts with durable initializer bytes"); + } + if ("INITIALIZING".equals(initializationState)) { + int confirmed = + transaction.execute( + "UPDATE " + + INITIALIZER + + " SET initialization_state = 'OPEN_CONFIRMED'" + + " WHERE operation_id = ? AND issuer_id = ?" + + " AND initialization_state = 'INITIALIZING'", + value.initializer().operationId(), + ISSUER); + if (confirmed != 1) { + throw conflict("Original OPEN receipt could not confirm its initializer state"); + } + } + return null; + }); + } + + @Override + public void recordClosedReadback( + CanonicalGameplayIssuerAdmissionBarrierRedisOwner.PreparedCutoffTarget prepared, + CanonicalGameplayIssuerAdmissionBarrierRedisOwner.Readback readback) { + Objects.requireNonNull(prepared, "prepared"); + Objects.requireNonNull(readback, "readback"); + requireStillCurrent(prepared); + CanonicalGameplayIssuerAdmissionBarrierValue value = prepared.closedValue(); + if (!Arrays.equals(value.exactBytes(), readback.exactPhysicalPayload()) + || !Arrays.equals(value.exactBytes(), readback.value().exactBytes())) { + throw conflict("CLOSED readback differs from the exact cutoff target"); + } + CanonicalGameplayIssuerBootstrapPartitionRedisOwner.CurrentIssuerState current = + readCurrentState(); + dsl.transactionResult( + configuration -> { + DSLContext transaction = DSL.using(configuration); + CanonicalGameplayBindingInventoryRepository.lockInventoryRevision(transaction); + CanonicalGameplayIssuerInstalledAnchor anchor = + CanonicalGameplayIssuerBootstrapCoverageRepository + .readInstalledAnchorForBindingPreparationInTransaction(transaction, current); + CanonicalGameplayIssuerAdmissionControlValue control = + readCurrentControl(transaction, anchor, current); + if (!value.ownerOperationId().equals(control.currentOperationId()) + || control.state() + != CanonicalGameplayIssuerAdmissionControlValue.State.CUTOFF_PENDING) { + throw conflict("CLOSED readback is not owned by the current pending cutoff"); + } + new CanonicalGameplayIssuerAdmissionControlRepository(dsl) + .verifyCurrentCutoffTarget( + transaction, + control, + value.tenantId(), + value.playableStateNamespaceId(), + value.exactBytes()); + requireCurrentTagMapping(transaction, value.tenantId(), value.tenantGameplayTag()); + Record target = + transaction.fetchOne( + "SELECT * FROM " + + CUTOFF_TARGET + + " WHERE operation_id = ? AND issuer_id = ? AND tenant_id = ?" + + " AND playable_state_namespace_id = ? FOR UPDATE", + value.ownerOperationId(), + ISSUER, + value.tenantId(), + value.playableStateNamespaceId()); + if (target == null + || !Arrays.equals(requireBytes(target, "closed_payload_bytes"), value.exactBytes()) + || !value.exactDigest().equals(target.get("closed_payload_digest", String.class))) { + throw conflict("CLOSED readback target changed before durable acknowledgement"); + } + String state = target.get("target_state", String.class); + if ("REQUIRED".equals(state)) { + int updated = + transaction.execute( + "UPDATE " + + CUTOFF_TARGET + + " SET exact_closed_readback_bytes = ?, exact_closed_readback_digest = ? ," + + " script_outcome = ?, target_state = 'CLOSED'" + + " WHERE operation_id = ? AND target_ordinal = ? AND target_state = 'REQUIRED'", + value.exactBytes(), + value.exactDigest(), + (short) readback.scriptOutcome(), + value.ownerOperationId(), + target.get("target_ordinal", Long.class)); + if (updated != 1) throw conflict("CLOSED target changed during receipt persistence"); + } else if (!"CLOSED".equals(state) + || !Arrays.equals( + requireBytes(target, "exact_closed_readback_bytes"), value.exactBytes()) + || !value + .exactDigest() + .equals(target.get("exact_closed_readback_digest", String.class)) + || !List.of((short) 1, (short) 2, (short) 3) + .contains(target.get("script_outcome", Short.class))) { + throw conflict("CLOSED retry conflicts with its immutable durable readback"); + } + return null; + }); + } + + private CurrentRequestTarget requireCurrentRequestTarget( + DSLContext transaction, + UUID operationId, + CanonicalGameplayTenantGameplayTagRepository.Assignment assignment, + CanonicalGameplayIssuerBootstrapPartitionRedisOwner.CurrentIssuerState current) { + Record row = + transaction.fetchOne( + "SELECT op.operation_id, op.transition_id, op.binding_ref, op.member_value_bytes," + + " op.member_value_digest, op.member_status, op.issuer_id," + + " t.status AS transition_status, t.tenant_id AS transition_tenant_id," + + " t.playable_state_namespace_id AS transition_namespace_id," + + " t.admission_lease_id, t.admission_target_tenant_id," + + " t.admission_target_playable_state_namespace_id," + + " t.admission_target_owner_proof_outcome, t.admission_target_positive_durable_abort," + + " i.account_id, i.tenant_id, i.playable_state_namespace_id, i.lifecycle," + + " i.binding_ref AS inventory_binding_ref, r.reservation_id" + + " FROM " + + LOCAL_OPERATION + + " op" + + " JOIN game_session_canonical_binding_transition t ON t.transition_id = op.transition_id" + + " JOIN game_session_canonical_gameplay_binding_inventory i" + + " ON i.binding_ref = op.binding_ref AND i.transition_id = op.transition_id" + + " JOIN game_session_canonical_issuer_partition_reservation r" + + " ON r.reservation_id = op.reservation_id AND r.transition_id = op.transition_id" + + " WHERE op.operation_id = ? AND op.issuer_id = ?" + + " FOR UPDATE OF op, t, i, r", + operationId, + ISSUER); + if (row == null) throw conflict("The exact original issuer local operation is unavailable"); + UUID transitionId = requiredUuid(row, "transition_id"); + UUID tenantId = requiredUuid(row, "transition_tenant_id"); + UUID namespaceId = requiredUuid(row, "transition_namespace_id"); + if (!transitionId.equals(assignment.transitionId()) + || !tenantId.equals(assignment.tenantId()) + || !namespaceId.equals(assignment.playableStateNamespaceId()) + || !tenantId.equals(requiredUuid(row, "tenant_id")) + || !namespaceId.equals(requiredUuid(row, "playable_state_namespace_id")) + || !requiredUuid(row, "account_id").equals(assignment.accountId()) + || !List.of("PROVISIONAL", "COMMITTED").contains(row.get("transition_status", String.class)) + || !List.of("PROVISIONAL", "ACTIVE").contains(row.get("lifecycle", String.class)) + || row.get("admission_lease_id", UUID.class) == null + || !tenantId.equals(row.get("admission_target_tenant_id", UUID.class)) + || !namespaceId.equals(row.get("admission_target_playable_state_namespace_id", UUID.class)) + || !"COMMITTED".equals(row.get("admission_target_owner_proof_outcome", String.class)) + || !Boolean.FALSE.equals( + row.get("admission_target_positive_durable_abort", Boolean.class))) { + throw conflict("Current issuer NEW request is not the exact registered tenant target"); + } + byte[] memberBytes = requireBytes(row, "member_value_bytes"); + if (!CanonicalGameplayIssuerMemberV2Codec.sha256(memberBytes) + .equals(row.get("member_value_digest", String.class)) + || !"PENDING_PHYSICAL_PROOF".equals(row.get("member_status", String.class))) { + throw conflict("Current local issuer operation has malformed pending member evidence"); + } + CanonicalGameplayIssuerMemberV2Value member = + CanonicalGameplayIssuerMemberV2Codec.decode(memberBytes); + byte[] bindingRef = requireBytes(row, "binding_ref"); + if (!Arrays.equals(bindingRef, requireBytes(row, "inventory_binding_ref")) + || !member.owner().tenantId().equals(tenantId) + || !member.owner().playableStateNamespaceId().equals(namespaceId) + || !member.owner().accountId().equals(assignment.accountId()) + || !Arrays.equals(member.owner().bindingRef().bytes(), bindingRef) + || !member.sourceCheckpoint().issuerId().equals(ISSUER) + || !member + .sourceCheckpoint() + .issuerAuthGeneration() + .equals(current.accountCheckpoint().issuerAuthGeneration()) + || !Arrays.equals( + member.sourceCheckpoint().exactCheckpointBytes(), + current.accountCheckpoint().exactCheckpointBytes()) + || !Objects.equals( + member.sourceCheckpoint().latestIssuerEventDigest(), + current.accountCheckpoint().latestIssuerEventDigest()) + || !Arrays.equals( + CanonicalGameplayIssuerInstalledAnchor.encodeIncarnation(member.incarnation()), + CanonicalGameplayIssuerInstalledAnchor.encodeIncarnation(current.incarnation()))) { + throw conflict("Current local operation differs from the Account or incarnation source"); + } + + return new CurrentRequestTarget( + transitionId, tenantId, namespaceId, assignment.accountId(), bindingRef); + } + + private CanonicalGameplayAdmissionBarrierTuple buildOriginalInitializer( + DSLContext transaction, + UUID operationId, + CurrentRequestTarget expected, + CanonicalGameplayTenantGameplayTagRepository.Assignment assignment, + CanonicalGameplayIssuerInstalledAnchor anchor, + CanonicalGameplayIssuerAdmissionControlValue control, + CanonicalGameplayIssuerBootstrapPartitionRedisOwner.CurrentIssuerState current) { + Record row = + transaction.fetchOne( + "SELECT op.transition_id, op.binding_ref, to_jsonb(t)::text AS registered_target_json," + + " to_jsonb(r)::text AS reservation_json" + + " FROM " + + LOCAL_OPERATION + + " op" + + " JOIN game_session_canonical_binding_transition t ON t.transition_id = op.transition_id" + + " JOIN game_session_canonical_gameplay_binding_inventory i" + + " ON i.binding_ref = op.binding_ref AND i.transition_id = op.transition_id" + + " JOIN game_session_canonical_issuer_partition_reservation r" + + " ON r.reservation_id = op.reservation_id AND r.transition_id = op.transition_id" + + " WHERE op.operation_id = ? AND op.issuer_id = ?" + + " FOR UPDATE OF op, t, i, r", + operationId, + ISSUER); + if (row == null + || !expected.transitionId().equals(requiredUuid(row, "transition_id")) + || !Arrays.equals(expected.bindingRef(), requireBytes(row, "binding_ref"))) { + throw conflict( + "Current issuer NEW target changed before its original initializer was captured"); + } + byte[] reservationBytes = requireText(row, "reservation_json").getBytes(StandardCharsets.UTF_8); + byte[] targetBytes = + requireText(row, "registered_target_json").getBytes(StandardCharsets.UTF_8); + CanonicalGameplayIssuerAdmissionBarrierValue.Initializer initializer = + new CanonicalGameplayIssuerAdmissionBarrierValue.Initializer( + ISSUER, + expected.tenantId(), + expected.namespaceId(), + assignment.tenantGameplayTag(), + operationId, + control.liveBarrierEpoch(), + expected.transitionId(), + expected.accountId(), + expected.bindingRef(), + reservationBytes, + CanonicalGameplayIssuerAdmissionBarrierValue.sha256(reservationBytes), + anchor.exactAnchorBytes(), + anchor.exactAnchorDigest(), + current.accountCheckpoint().issuerAuthGeneration(), + current.accountCheckpoint().exactCheckpointBytes(), + current.accountCheckpoint().checkpointDigest(), + current.accountCheckpoint().latestIssuerEventBytes(), + current.accountCheckpoint().latestIssuerEventDigest(), + CanonicalGameplayIssuerInstalledAnchor.encodeIncarnation(current.incarnation()), + CanonicalGameplayIssuerMemberV2Codec.sha256( + CanonicalGameplayIssuerInstalledAnchor.encodeIncarnation(current.incarnation())), + targetBytes, + CanonicalGameplayIssuerAdmissionBarrierValue.sha256(targetBytes)); + return new CanonicalGameplayAdmissionBarrierTuple(initializer); + } + + private CanonicalGameplayIssuerAdmissionBarrierValue readFrozenInitializer( + DSLContext transaction, + Record row, + CanonicalGameplayTenantGameplayTagRepository.Assignment expectedTarget, + CanonicalGameplayIssuerInstalledAnchor anchor, + CanonicalGameplayIssuerAdmissionControlValue control, + CanonicalGameplayIssuerBootstrapPartitionRedisOwner.CurrentIssuerState current) { + if (row == null) throw conflict("The durable original tenant initializer is missing"); + byte[] payload = requireBytes(row, "open_payload_bytes"); + CanonicalGameplayIssuerAdmissionBarrierValue value = + CanonicalGameplayIssuerAdmissionBarrierValue.decode(payload); + CanonicalGameplayIssuerAdmissionBarrierValue.Initializer initializer = value.initializer(); + requirePersistedInitializer(row, value); + String state = row.get("initialization_state", String.class); + if (initializer == null + || value.state() != CanonicalGameplayIssuerAdmissionBarrierValue.State.OPEN + || !initializer.operationId().equals(row.get("operation_id", UUID.class)) + || !initializer.issuerId().equals(row.get("issuer_id", String.class)) + || !control.liveBarrierEpoch().equals(initializer.admissionEpoch()) + || !initializer.matchesCurrentIssuerState(current) + || !Arrays.equals(initializer.anchorBytes(), anchor.exactAnchorBytes()) + || !initializer.anchorDigest().equals(anchor.exactAnchorDigest()) + || !List.of("PREPARED", "INITIALIZING", "OPEN_CONFIRMED").contains(state)) { + throw conflict("Frozen tenant initializer differs from current positive source and control"); + } + requireCurrentTagMapping(transaction, initializer.tenantId(), initializer.tenantGameplayTag()); + if (expectedTarget != null) requireSameTargetAssignment(expectedTarget, initializer); + return value; + } + + private static void requireCurrentTagMapping( + DSLContext transaction, UUID tenantId, String expectedTag) { + Record mapping = + transaction.fetchOne( + "SELECT allocation_version, tenant_gameplay_tag FROM " + + TENANT_TAG + + " WHERE tenant_id = ? FOR SHARE", + tenantId); + Integer version = mapping == null ? null : mapping.get("allocation_version", Integer.class); + String tag = mapping == null ? null : mapping.get("tenant_gameplay_tag", String.class); + if (version == null + || version <= 0 + || tag == null + || !tag.equals(expectedTag) + || !tag.equals("g" + version + "-" + tenantId.toString().replace("-", ""))) { + throw conflict("Frozen issuer target has no exact current SQL tenant gameplay-tag mapping"); + } + } + + private static void persistOriginalInitializer( + DSLContext transaction, CanonicalGameplayIssuerAdmissionBarrierValue value) { + CanonicalGameplayIssuerAdmissionBarrierValue.Initializer initializer = value.initializer(); + Record prior = + transaction.fetchOne( + "SELECT * FROM " + INITIALIZER + " WHERE operation_id = ? AND issuer_id = ? FOR UPDATE", + initializer.operationId(), + ISSUER); + if (prior != null) { + requirePersistedInitializer(prior, value); + return; + } + int inserted = + transaction.execute( + "INSERT INTO " + + INITIALIZER + + " (operation_id, issuer_id, tenant_id, playable_state_namespace_id," + + " tenant_gameplay_tag, live_barrier_epoch, initialization_state," + + " initializer_exact_bytes," + + " initializer_digest, open_payload_bytes, open_payload_digest)" + + " VALUES (?, ?, ?, ?, ?, ?, 'PREPARED', ?, ?, ?, ?)", + initializer.operationId(), + initializer.issuerId(), + initializer.tenantId(), + initializer.playableStateNamespaceId(), + initializer.tenantGameplayTag(), + initializer.admissionEpoch(), + initializer.exactBytes(), + initializer.exactDigest(), + value.exactBytes(), + value.exactDigest()); + if (inserted != 1) throw conflict("Original issuer initializer did not persist before OPEN"); + Record saved = + transaction.fetchOne( + "SELECT * FROM " + INITIALIZER + " WHERE operation_id = ? AND issuer_id = ? FOR UPDATE", + initializer.operationId(), + ISSUER); + requirePersistedInitializer(saved, value); + } + + private static void requirePersistedInitializer( + Record row, CanonicalGameplayIssuerAdmissionBarrierValue expected) { + if (row == null + || !expected.issuerId().equals(row.get("issuer_id", String.class)) + || !expected.tenantId().equals(row.get("tenant_id", UUID.class)) + || !expected + .playableStateNamespaceId() + .equals(row.get("playable_state_namespace_id", UUID.class)) + || !expected.tenantGameplayTag().equals(row.get("tenant_gameplay_tag", String.class)) + || !expected.admissionEpoch().equals(readBigInteger(row, "live_barrier_epoch")) + || !Arrays.equals( + expected.initializer().exactBytes(), requireBytes(row, "initializer_exact_bytes")) + || !expected.initializer().exactDigest().equals(row.get("initializer_digest", String.class)) + || !Arrays.equals(expected.exactBytes(), requireBytes(row, "open_payload_bytes")) + || !expected.exactDigest().equals(row.get("open_payload_digest", String.class))) { + throw conflict("Persisted original issuer initializer differs from its exact retry source"); + } + } + + private CanonicalGameplayIssuerAdmissionBarrierRedisOwner.PreparedInitializer prepared( + CanonicalGameplayIssuerAdmissionBarrierValue value, + CanonicalGameplayTenantGameplayTagRepository.Assignment assignment, + UUID requestOperationId) { + return new CanonicalGameplayIssuerAdmissionBarrierRedisOwner.PreparedInitializer( + value, + assignment, + requestOperationId, + CanonicalGameplayIssuerAdmissionBarrierKey.forTarget( + ISSUER, value.tenantId(), value.playableStateNamespaceId(), value.tenantGameplayTag())); + } + + /** + * Consumes the sole durable authority to create the first Redis OPEN. The state transition is + * committed before the Redis owner can attempt its command; every later call is replay-only. + */ + @Override + public boolean claimFirstCreatePermit( + CanonicalGameplayIssuerAdmissionBarrierRedisOwner.PreparedInitializer prepared) { + Objects.requireNonNull(prepared, "prepared"); + requireNoAmbientTransaction(); + CanonicalGameplayIssuerAdmissionBarrierValue value = prepared.value(); + UUID operationId = value.initializer().operationId(); + CanonicalGameplayIssuerBootstrapPartitionRedisOwner.CurrentIssuerState current = + readCurrentState(); + if (!value.initializer().matchesCurrentIssuerState(current)) { + throw conflict("Original OPEN initializer no longer matches current Account issuer source"); + } + CanonicalGameplayTenantGameplayTagRepository.Assignment assignment = + prepared.assignment() == null + ? null + : tenantTags.assignmentForTransition(prepared.assignment().transitionId()); + if (assignment != null) requireSameAssignment(prepared.assignment(), assignment); + return dsl.transactionResult( + configuration -> { + DSLContext transaction = DSL.using(configuration); + CanonicalGameplayBindingInventoryRepository.lockInventoryRevision(transaction); + CanonicalGameplayIssuerInstalledAnchor anchor = + CanonicalGameplayIssuerBootstrapCoverageRepository + .readInstalledAnchorForBindingPreparationInTransaction(transaction, current); + CanonicalGameplayIssuerAdmissionControlValue control = + CanonicalGameplayIssuerAdmissionControlRepository.requireOpenInTransaction( + transaction, anchor, current); + if (!control.liveBarrierEpoch().equals(value.admissionEpoch()) + || !control.currentOperationId().equals(anchor.bootstrapOperationId())) { + throw conflict( + "Original initializer no longer belongs to the current OPEN live control"); + } + if (assignment != null) { + requireCurrentTagMapping( + transaction, assignment.tenantId(), assignment.tenantGameplayTag()); + requireCurrentRequestTarget( + transaction, prepared.requestOperationId(), assignment, current); + } + Record saved = + transaction.fetchSingle( + "SELECT * FROM " + + INITIALIZER + + " WHERE operation_id = ? AND issuer_id = ? FOR UPDATE", + operationId, + ISSUER); + readFrozenInitializer( + transaction, saved, prepared.assignment(), anchor, control, current); + requirePersistedInitializer(saved, value); + String state = saved.get("initialization_state", String.class); + if ("PREPARED".equals(state)) { + Record origin = + transaction.fetchOne( + "SELECT transition.status AS transition_status FROM " + + LOCAL_OPERATION + + " operation JOIN game_session_canonical_binding_transition transition" + + " ON transition.transition_id = operation.transition_id" + + " WHERE operation.operation_id = ? AND operation.issuer_id = ?" + + " FOR SHARE OF operation, transition", + operationId, + ISSUER); + if (origin == null) { + throw conflict("Original initializer lost its persisted local-operation provenance"); + } + if ("ABORTED".equals(origin.get("transition_status", String.class))) { + return false; + } + if (!List.of("PROVISIONAL", "COMMITTED") + .contains(origin.get("transition_status", String.class))) { + throw conflict("Original initializer source is no longer an eligible first NEW"); + } + int claimed = + transaction.execute( + "UPDATE " + + INITIALIZER + + " SET initialization_state = 'INITIALIZING'" + + " WHERE operation_id = ? AND issuer_id = ?" + + " AND initialization_state = 'PREPARED'", + operationId, + ISSUER); + if (claimed != 1) { + throw conflict("Original initializer first-create permit was not uniquely claimed"); + } + return true; + } + if ("INITIALIZING".equals(state) || "OPEN_CONFIRMED".equals(state)) return false; + throw conflict("Original initializer has an unknown or non-admitting durable state"); + }); + } + + private UUID transitionForLocalOperation(UUID operationId) { + Record row = + dsl.fetchOne( + "SELECT transition_id FROM " + + LOCAL_OPERATION + + " WHERE operation_id = ? AND issuer_id = ?", + operationId, + ISSUER); + if (row == null) throw conflict("The exact original issuer local operation is unavailable"); + return requiredUuid(row, "transition_id"); + } + + private CanonicalGameplayIssuerInstalledAnchor readInstalledAnchor( + CanonicalGameplayIssuerBootstrapPartitionRedisOwner.CurrentIssuerState current) { + return dsl.transactionResult( + configuration -> { + DSLContext transaction = DSL.using(configuration); + CanonicalGameplayBindingInventoryRepository.lockInventoryRevision(transaction); + return CanonicalGameplayIssuerBootstrapCoverageRepository + .readInstalledAnchorForBindingPreparationInTransaction(transaction, current); + }); + } + + private CanonicalGameplayIssuerAdmissionControlValue readCurrentControl( + DSLContext transaction, + CanonicalGameplayIssuerInstalledAnchor anchor, + CanonicalGameplayIssuerBootstrapPartitionRedisOwner.CurrentIssuerState current) { + Record row = + transaction.fetchOne( + "SELECT * FROM " + CONTROL + " WHERE issuer_id = ? FOR UPDATE", ISSUER); + if (row == null) throw conflict("The positive live issuer admission-control row is missing"); + CanonicalGameplayIssuerAdmissionControlValue value = + CanonicalGameplayIssuerAdmissionControlValue.decode( + requireBytes(row, "control_exact_bytes")); + if (!CanonicalGameplayIssuerAdmissionControlValue.sha256(value.exactBytes()) + .equals(row.get("control_exact_digest", String.class)) + || !value.issuerId().equals(row.get("issuer_id", String.class)) + || !value.matchesCurrentIssuerState(current) + || !Arrays.equals(value.anchorExactBytes(), anchor.exactAnchorBytes()) + || !value.anchorExactDigest().equals(anchor.exactAnchorDigest())) { + throw conflict( + "Issuer control differs from its exact installed anchor and fresh current source"); + } + return value; + } + + private CanonicalGameplayIssuerBootstrapPartitionRedisOwner.CurrentIssuerState + readCurrentState() { + try { + return Objects.requireNonNull( + currentStateSource.readFreshCurrentState(), "Current issuer source returned null"); + } catch (RuntimeException failure) { + throw conflict("Current Account issuer source or stable incarnation is unavailable"); + } + } + + private static void requireSameAssignment( + CanonicalGameplayTenantGameplayTagRepository.Assignment expected, + CanonicalGameplayTenantGameplayTagRepository.Assignment actual) { + if (!expected.tenantId().equals(actual.tenantId()) + || !expected.accountId().equals(actual.accountId()) + || !expected.playableStateNamespaceId().equals(actual.playableStateNamespaceId()) + || !expected.tenantGameplayTag().equals(actual.tenantGameplayTag()) + || !Objects.equals(expected.transitionId(), actual.transitionId())) { + throw conflict("Current tenant target assignment differs from the exact durable original"); + } + } + + private static void requireSameTargetAssignment( + CanonicalGameplayTenantGameplayTagRepository.Assignment expected, + CanonicalGameplayIssuerAdmissionBarrierValue.Initializer actual) { + if (!expected.tenantId().equals(actual.tenantId()) + || !expected.playableStateNamespaceId().equals(actual.playableStateNamespaceId()) + || !expected.tenantGameplayTag().equals(actual.tenantGameplayTag())) { + throw conflict("Fresh NEW request scope differs from the frozen tenant initializer target"); + } + } + + private static byte[] requireBytes(Record row, String field) { + byte[] value = row == null ? null : row.get(field, byte[].class); + if (value == null) throw conflict("Persisted issuer admission bytes are missing: " + field); + return value.clone(); + } + + private static UUID requiredUuid(Record row, String field) { + UUID value = row == null ? null : row.get(field, UUID.class); + if (value == null) throw conflict("Persisted issuer admission UUID is missing: " + field); + return value; + } + + private static String requireText(Record row, String field) { + String value = row == null ? null : row.get(field, String.class); + if (value == null) throw conflict("Persisted issuer admission text is missing: " + field); + return value; + } + + private static BigInteger readBigInteger(Record row, String field) { + java.math.BigDecimal value = row == null ? null : row.get(field, java.math.BigDecimal.class); + if (value == null) throw conflict("Persisted issuer admission integer is missing: " + field); + try { + return value.toBigIntegerExact(); + } catch (ArithmeticException malformed) { + throw conflict("Persisted issuer admission integer is malformed: " + field); + } + } + + private static void requireNonNil(UUID value, String name) { + if (value == null || value.equals(new UUID(0L, 0L))) { + throw new IllegalArgumentException(name + " must be a non-nil UUID"); + } + } + + private void requireNoAmbientTransaction() { + if (TransactionSynchronizationManager.isActualTransactionActive() + || TransactionSynchronizationManager.isSynchronizationActive()) { + throw conflict("Issuer tenant barrier owner cannot join an ambient SQL transaction"); + } + try { + dsl.connectionResult( + connection -> { + if (!connection.getAutoCommit()) { + throw conflict("Issuer tenant barrier owner cannot join a jOOQ transaction"); + } + return Boolean.TRUE; + }); + } catch (RuntimeException failure) { + if (failure instanceof CanonicalGameplayBindingInventoryConflictException) throw failure; + throw new CanonicalGameplayBindingInventoryConflictException( + "Issuer tenant barrier SQL connection state is unavailable", failure); + } + } + + private static CanonicalGameplayBindingInventoryConflictException conflict(String message) { + return new CanonicalGameplayBindingInventoryConflictException(message); + } + + private record CanonicalGameplayAdmissionBarrierTuple( + CanonicalGameplayIssuerAdmissionBarrierValue.Initializer initializer) {} + + private record PreparedInitializerSource( + CanonicalGameplayIssuerAdmissionBarrierValue value, + CanonicalGameplayTenantGameplayTagRepository.Assignment requestAssignment) {} + + private record CurrentRequestTarget( + UUID transitionId, UUID tenantId, UUID namespaceId, UUID accountId, byte[] bindingRef) { + private CurrentRequestTarget { + Objects.requireNonNull(transitionId, "transitionId"); + Objects.requireNonNull(tenantId, "tenantId"); + Objects.requireNonNull(namespaceId, "namespaceId"); + Objects.requireNonNull(accountId, "accountId"); + bindingRef = Objects.requireNonNull(bindingRef, "bindingRef").clone(); + } + + @Override + public byte[] bindingRef() { + return bindingRef.clone(); + } + } +} diff --git a/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/repository/CanonicalGameplayIssuerAdmissionBarrierValue.java b/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/repository/CanonicalGameplayIssuerAdmissionBarrierValue.java new file mode 100644 index 0000000000..1c17f78e85 --- /dev/null +++ b/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/repository/CanonicalGameplayIssuerAdmissionBarrierValue.java @@ -0,0 +1,651 @@ +package net.firedevops.firemud.gamesession.repository; + +import java.io.ByteArrayInputStream; +import java.io.ByteArrayOutputStream; +import java.io.DataInputStream; +import java.io.DataOutputStream; +import java.io.IOException; +import java.math.BigInteger; +import java.nio.charset.CharacterCodingException; +import java.nio.charset.CodingErrorAction; +import java.nio.charset.StandardCharsets; +import java.security.MessageDigest; +import java.util.Arrays; +import java.util.HexFormat; +import java.util.Objects; +import java.util.UUID; +import net.firedevops.firemud.common.security.GameSessionAccountDelegationProfile; + +/** Exact tenant-local issuer admission barrier payload; it is not an issuer-wide proof. */ +final class CanonicalGameplayIssuerAdmissionBarrierValue { + static final String SCHEMA = "gs_issuer_admission_barrier/v1"; + static final int MAX_BYTES = 512 * 1024; + private static final String TARGET_ENCODING = "canonical-issuer-admission-target/v1"; + private static final String VALUE_ENCODING = "canonical-issuer-admission-barrier/v1"; + + enum State { + OPEN, + CLOSED + } + + /** Full immutable initializer source retained by OPEN and any later CLOSED value. */ + static final class Initializer { + private final String issuerId; + private final UUID tenantId; + private final UUID playableStateNamespaceId; + private final String tenantGameplayTag; + private final UUID operationId; + private final BigInteger admissionEpoch; + private final UUID transitionId; + private final UUID accountId; + private final byte[] bindingRefBytes; + private final byte[] reservationBytes; + private final String reservationDigest; + private final byte[] anchorBytes; + private final String anchorDigest; + private final BigInteger accountIssuerAuthGeneration; + private final byte[] accountCheckpointBytes; + private final String accountCheckpointDigest; + private final byte[] accountSourceEventBytes; + private final String accountSourceEventDigest; + private final byte[] incarnationBytes; + private final String incarnationDigest; + private final byte[] registeredTargetBytes; + private final String registeredTargetDigest; + private final byte[] exactBytes; + private final String exactDigest; + + Initializer( + String issuerId, + UUID tenantId, + UUID playableStateNamespaceId, + String tenantGameplayTag, + UUID operationId, + BigInteger admissionEpoch, + UUID transitionId, + UUID accountId, + byte[] bindingRefBytes, + byte[] reservationBytes, + String reservationDigest, + byte[] anchorBytes, + String anchorDigest, + BigInteger accountIssuerAuthGeneration, + byte[] accountCheckpointBytes, + String accountCheckpointDigest, + byte[] accountSourceEventBytes, + String accountSourceEventDigest, + byte[] incarnationBytes, + String incarnationDigest, + byte[] registeredTargetBytes, + String registeredTargetDigest) { + this.issuerId = requireIssuer(issuerId); + this.tenantId = requireNonNil(tenantId, "tenantId"); + this.playableStateNamespaceId = + requireNonNil(playableStateNamespaceId, "playableStateNamespaceId"); + this.tenantGameplayTag = requireTag(tenantGameplayTag); + this.operationId = requireNonNil(operationId, "operationId"); + this.admissionEpoch = requirePositive(admissionEpoch, "admissionEpoch"); + this.transitionId = requireNonNil(transitionId, "transitionId"); + this.accountId = requireNonNil(accountId, "accountId"); + this.bindingRefBytes = nonEmpty(bindingRefBytes, "bindingRefBytes"); + this.reservationBytes = nonEmpty(reservationBytes, "reservationBytes"); + this.reservationDigest = requireDigest(reservationDigest, "reservationDigest"); + requireDigestMatches(this.reservationBytes, this.reservationDigest, "reservation"); + this.anchorBytes = nonEmpty(anchorBytes, "anchorBytes"); + this.anchorDigest = requireDigest(anchorDigest, "anchorDigest"); + requireDigestMatches(this.anchorBytes, this.anchorDigest, "installed anchor"); + this.accountIssuerAuthGeneration = + requirePositive(accountIssuerAuthGeneration, "accountIssuerAuthGeneration"); + this.accountCheckpointBytes = nonEmpty(accountCheckpointBytes, "accountCheckpointBytes"); + this.accountCheckpointDigest = + requireDigest(accountCheckpointDigest, "accountCheckpointDigest"); + requireDigestMatches( + this.accountCheckpointBytes, this.accountCheckpointDigest, "Account checkpoint"); + if ((accountSourceEventBytes == null) != (accountSourceEventDigest == null)) { + throw new IllegalArgumentException("Account source event bytes and digest must be paired"); + } + this.accountSourceEventBytes = + accountSourceEventBytes == null + ? null + : nonEmpty(accountSourceEventBytes, "accountSourceEventBytes"); + this.accountSourceEventDigest = + accountSourceEventDigest == null + ? null + : requireDigest(accountSourceEventDigest, "accountSourceEventDigest"); + if (this.accountSourceEventBytes != null) { + requireDigestMatches( + this.accountSourceEventBytes, this.accountSourceEventDigest, "Account source event"); + } + this.incarnationBytes = nonEmpty(incarnationBytes, "incarnationBytes"); + this.incarnationDigest = requireDigest(incarnationDigest, "incarnationDigest"); + requireDigestMatches(this.incarnationBytes, this.incarnationDigest, "incarnation"); + this.registeredTargetBytes = nonEmpty(registeredTargetBytes, "registeredTargetBytes"); + this.registeredTargetDigest = requireDigest(registeredTargetDigest, "registeredTargetDigest"); + requireDigestMatches( + this.registeredTargetBytes, this.registeredTargetDigest, "registered target"); + long boundedBytes = + (long) this.bindingRefBytes.length + + this.reservationBytes.length + + this.anchorBytes.length + + this.accountCheckpointBytes.length + + (this.accountSourceEventBytes == null ? 0 : this.accountSourceEventBytes.length) + + this.incarnationBytes.length + + this.registeredTargetBytes.length + + 16_384L; + if (boundedBytes > MAX_BYTES) { + throw new IllegalArgumentException("Issuer initializer tuple exceeds its encoded bound"); + } + this.exactBytes = encodeTarget(); + this.exactDigest = sha256(this.exactBytes); + if (this.exactBytes.length > MAX_BYTES) { + throw new IllegalArgumentException("Issuer initializer tuple exceeds its encoded bound"); + } + } + + private byte[] encodeTarget() { + return encode( + out -> { + writeText(out, TARGET_ENCODING); + writeText(out, issuerId); + writeUuid(out, tenantId); + writeUuid(out, playableStateNamespaceId); + writeText(out, tenantGameplayTag); + writeUuid(out, operationId); + writeBigInteger(out, admissionEpoch); + writeUuid(out, transitionId); + writeUuid(out, accountId); + writeBytes(out, bindingRefBytes); + writeBytes(out, reservationBytes); + writeText(out, reservationDigest); + writeBytes(out, anchorBytes); + writeText(out, anchorDigest); + writeBigInteger(out, accountIssuerAuthGeneration); + writeBytes(out, accountCheckpointBytes); + writeText(out, accountCheckpointDigest); + writeNullableBytes(out, accountSourceEventBytes); + writeNullableText(out, accountSourceEventDigest); + writeBytes(out, incarnationBytes); + writeText(out, incarnationDigest); + writeBytes(out, registeredTargetBytes); + writeText(out, registeredTargetDigest); + }); + } + + private static Initializer decode(byte[] bytes) { + if (bytes == null || bytes.length == 0 || bytes.length > MAX_BYTES) throw malformed(); + try (DataInputStream in = new DataInputStream(new ByteArrayInputStream(bytes))) { + if (!TARGET_ENCODING.equals(readText(in))) throw malformed(); + Initializer result = + new Initializer( + readText(in), + readUuid(in), + readUuid(in), + readText(in), + readUuid(in), + readPositive(in), + readUuid(in), + readUuid(in), + readBytes(in), + readBytes(in), + readText(in), + readBytes(in), + readText(in), + readPositive(in), + readBytes(in), + readText(in), + readNullableBytes(in), + readNullableText(in), + readBytes(in), + readText(in), + readBytes(in), + readText(in)); + if (in.available() != 0 || !Arrays.equals(bytes, result.exactBytes())) throw malformed(); + return result; + } catch (IOException | RuntimeException invalid) { + throw malformed(); + } + } + + String issuerId() { + return issuerId; + } + + UUID tenantId() { + return tenantId; + } + + UUID playableStateNamespaceId() { + return playableStateNamespaceId; + } + + String tenantGameplayTag() { + return tenantGameplayTag; + } + + UUID operationId() { + return operationId; + } + + BigInteger admissionEpoch() { + return admissionEpoch; + } + + UUID transitionId() { + return transitionId; + } + + UUID accountId() { + return accountId; + } + + byte[] bindingRefBytes() { + return bindingRefBytes.clone(); + } + + byte[] reservationBytes() { + return reservationBytes.clone(); + } + + String reservationDigest() { + return reservationDigest; + } + + byte[] anchorBytes() { + return anchorBytes.clone(); + } + + String anchorDigest() { + return anchorDigest; + } + + BigInteger accountIssuerAuthGeneration() { + return accountIssuerAuthGeneration; + } + + byte[] accountCheckpointBytes() { + return accountCheckpointBytes.clone(); + } + + String accountCheckpointDigest() { + return accountCheckpointDigest; + } + + byte[] accountSourceEventBytes() { + return accountSourceEventBytes == null ? null : accountSourceEventBytes.clone(); + } + + String accountSourceEventDigest() { + return accountSourceEventDigest; + } + + byte[] incarnationBytes() { + return incarnationBytes.clone(); + } + + String incarnationDigest() { + return incarnationDigest; + } + + byte[] registeredTargetBytes() { + return registeredTargetBytes.clone(); + } + + String registeredTargetDigest() { + return registeredTargetDigest; + } + + byte[] exactBytes() { + return exactBytes.clone(); + } + + String exactDigest() { + return exactDigest; + } + + boolean matchesCurrentIssuerState( + CanonicalGameplayIssuerBootstrapPartitionRedisOwner.CurrentIssuerState current) { + Objects.requireNonNull(current, "current"); + var checkpoint = current.accountCheckpoint(); + return issuerId.equals(checkpoint.issuerId()) + && accountIssuerAuthGeneration.equals(checkpoint.issuerAuthGeneration()) + && Arrays.equals(accountCheckpointBytes, checkpoint.exactCheckpointBytes()) + && accountCheckpointDigest.equals(checkpoint.checkpointDigest()) + && Arrays.equals(accountSourceEventBytes, checkpoint.latestIssuerEventBytes()) + && Objects.equals(accountSourceEventDigest, checkpoint.latestIssuerEventDigest()) + && Arrays.equals( + incarnationBytes, + CanonicalGameplayIssuerInstalledAnchor.encodeIncarnation(current.incarnation())); + } + } + + private final String issuerId; + private final UUID tenantId; + private final UUID playableStateNamespaceId; + private final String tenantGameplayTag; + private final State state; + private final BigInteger admissionEpoch; + private final UUID ownerOperationId; + private final Initializer initializer; + private final byte[] exactBytes; + private final String exactDigest; + + private CanonicalGameplayIssuerAdmissionBarrierValue( + String issuerId, + UUID tenantId, + UUID playableStateNamespaceId, + String tenantGameplayTag, + State state, + BigInteger admissionEpoch, + UUID ownerOperationId, + Initializer initializer) { + this.issuerId = requireIssuer(issuerId); + this.tenantId = requireNonNil(tenantId, "tenantId"); + this.playableStateNamespaceId = + requireNonNil(playableStateNamespaceId, "playableStateNamespaceId"); + this.tenantGameplayTag = requireTag(tenantGameplayTag); + this.state = Objects.requireNonNull(state, "state"); + this.admissionEpoch = requirePositive(admissionEpoch, "admissionEpoch"); + this.ownerOperationId = requireNonNil(ownerOperationId, "ownerOperationId"); + this.initializer = initializer; + if (initializer != null + && (!this.issuerId.equals(initializer.issuerId()) + || !this.tenantId.equals(initializer.tenantId()) + || !this.playableStateNamespaceId.equals(initializer.playableStateNamespaceId()) + || !this.tenantGameplayTag.equals(initializer.tenantGameplayTag()))) { + throw new IllegalArgumentException("Barrier initializer belongs to a different target"); + } + if (state == State.OPEN + && (initializer == null + || !ownerOperationId.equals(initializer.operationId()) + || !admissionEpoch.equals(initializer.admissionEpoch()))) { + throw new IllegalArgumentException("OPEN requires its exact original initializer tuple"); + } + if (state == State.CLOSED + && initializer != null + && (admissionEpoch.compareTo(initializer.admissionEpoch()) <= 0 + || ownerOperationId.equals(initializer.operationId()))) { + throw new IllegalArgumentException("CLOSED must advance past a captured initializer epoch"); + } + this.exactBytes = encodeValue(); + this.exactDigest = sha256(this.exactBytes); + if (this.exactBytes.length > MAX_BYTES) { + throw new IllegalArgumentException("Issuer admission barrier exceeds its encoded bound"); + } + } + + static CanonicalGameplayIssuerAdmissionBarrierValue open(Initializer initializer) { + Objects.requireNonNull(initializer, "initializer"); + return new CanonicalGameplayIssuerAdmissionBarrierValue( + initializer.issuerId(), + initializer.tenantId(), + initializer.playableStateNamespaceId(), + initializer.tenantGameplayTag(), + State.OPEN, + initializer.admissionEpoch(), + initializer.operationId(), + initializer); + } + + static CanonicalGameplayIssuerAdmissionBarrierValue closed( + String issuerId, + UUID tenantId, + UUID playableStateNamespaceId, + String tenantGameplayTag, + BigInteger cutoffEpoch, + UUID cutoffOperationId, + Initializer capturedInitializer) { + return new CanonicalGameplayIssuerAdmissionBarrierValue( + issuerId, + tenantId, + playableStateNamespaceId, + tenantGameplayTag, + State.CLOSED, + cutoffEpoch, + cutoffOperationId, + capturedInitializer); + } + + static CanonicalGameplayIssuerAdmissionBarrierValue decode(byte[] bytes) { + if (bytes == null || bytes.length == 0 || bytes.length > MAX_BYTES) throw malformed(); + try (DataInputStream in = new DataInputStream(new ByteArrayInputStream(bytes))) { + if (!VALUE_ENCODING.equals(readText(in))) throw malformed(); + String issuerId = readText(in); + UUID tenantId = readUuid(in); + UUID namespaceId = readUuid(in); + String tag = readText(in); + State state = State.valueOf(readText(in)); + BigInteger epoch = readPositive(in); + UUID ownerOperationId = readUuid(in); + byte[] initializerBytes = readNullableBytes(in); + String initializerDigest = readNullableText(in); + Initializer initializer = null; + if (initializerBytes != null) { + initializer = Initializer.decode(initializerBytes); + if (!initializer.exactDigest().equals(initializerDigest)) throw malformed(); + } else if (initializerDigest != null) { + throw malformed(); + } + CanonicalGameplayIssuerAdmissionBarrierValue result = + new CanonicalGameplayIssuerAdmissionBarrierValue( + issuerId, tenantId, namespaceId, tag, state, epoch, ownerOperationId, initializer); + if (in.available() != 0 || !Arrays.equals(bytes, result.exactBytes())) throw malformed(); + return result; + } catch (IOException | RuntimeException invalid) { + throw malformed(); + } + } + + private byte[] encodeValue() { + return encode( + out -> { + writeText(out, VALUE_ENCODING); + writeText(out, issuerId); + writeUuid(out, tenantId); + writeUuid(out, playableStateNamespaceId); + writeText(out, tenantGameplayTag); + writeText(out, state.name()); + writeBigInteger(out, admissionEpoch); + writeUuid(out, ownerOperationId); + writeNullableBytes(out, initializer == null ? null : initializer.exactBytes()); + writeNullableText(out, initializer == null ? null : initializer.exactDigest()); + }); + } + + String issuerId() { + return issuerId; + } + + UUID tenantId() { + return tenantId; + } + + UUID playableStateNamespaceId() { + return playableStateNamespaceId; + } + + String tenantGameplayTag() { + return tenantGameplayTag; + } + + State state() { + return state; + } + + BigInteger admissionEpoch() { + return admissionEpoch; + } + + UUID ownerOperationId() { + return ownerOperationId; + } + + Initializer initializer() { + return initializer; + } + + byte[] exactBytes() { + return exactBytes.clone(); + } + + String exactDigest() { + return exactDigest; + } + + static String sha256(byte[] bytes) { + try { + return "sha256:" + + HexFormat.of().formatHex(MessageDigest.getInstance("SHA-256").digest(bytes)); + } catch (Exception failure) { + throw new IllegalStateException("Could not digest exact issuer admission bytes", failure); + } + } + + private static byte[] encode(Writer writer) { + try { + ByteArrayOutputStream bytes = new ByteArrayOutputStream(); + try (DataOutputStream output = new DataOutputStream(bytes)) { + writer.write(output); + } + return bytes.toByteArray(); + } catch (IOException impossible) { + throw new IllegalStateException("Could not encode exact issuer admission bytes", impossible); + } + } + + private static void writeText(DataOutputStream out, String value) throws IOException { + byte[] bytes = Objects.requireNonNull(value, "text").getBytes(StandardCharsets.UTF_8); + writeBytes(out, bytes); + } + + private static void writeBigInteger(DataOutputStream out, BigInteger value) throws IOException { + writeText(out, requirePositive(value, "counter").toString()); + } + + private static void writeUuid(DataOutputStream out, UUID value) throws IOException { + writeText(out, requireNonNil(value, "uuid").toString()); + } + + private static void writeBytes(DataOutputStream out, byte[] value) throws IOException { + if (value.length > MAX_BYTES) throw new IllegalArgumentException("Byte field exceeds bound"); + out.writeInt(value.length); + out.write(value); + } + + private static void writeNullableBytes(DataOutputStream out, byte[] value) throws IOException { + out.writeBoolean(value != null); + if (value != null) writeBytes(out, value); + } + + private static void writeNullableText(DataOutputStream out, String value) throws IOException { + out.writeBoolean(value != null); + if (value != null) writeText(out, value); + } + + private static String readText(DataInputStream in) throws IOException { + return decodeUtf8(readBytes(in)); + } + + private static byte[] readBytes(DataInputStream in) throws IOException { + int length = in.readInt(); + if (length < 1 || length > MAX_BYTES || length > in.available()) throw malformed(); + return in.readNBytes(length); + } + + private static byte[] readNullableBytes(DataInputStream in) throws IOException { + return in.readBoolean() ? readBytes(in) : null; + } + + private static String readNullableText(DataInputStream in) throws IOException { + return in.readBoolean() ? readText(in) : null; + } + + private static UUID readUuid(DataInputStream in) throws IOException { + String text = readText(in); + UUID value; + try { + value = UUID.fromString(text); + } catch (IllegalArgumentException invalid) { + throw malformed(); + } + if (!value.toString().equals(text) || value.equals(new UUID(0L, 0L))) throw malformed(); + return value; + } + + private static BigInteger readPositive(DataInputStream in) throws IOException { + String text = readText(in); + if (!text.matches("[1-9][0-9]{0,255}")) throw malformed(); + return new BigInteger(text); + } + + private static String decodeUtf8(byte[] bytes) throws IOException { + try { + return StandardCharsets.UTF_8 + .newDecoder() + .onMalformedInput(CodingErrorAction.REPORT) + .onUnmappableCharacter(CodingErrorAction.REPORT) + .decode(java.nio.ByteBuffer.wrap(bytes)) + .toString(); + } catch (CharacterCodingException invalid) { + throw malformed(); + } + } + + private static IllegalArgumentException malformed() { + return new IllegalArgumentException("Issuer admission barrier payload is malformed"); + } + + private static byte[] nonEmpty(byte[] value, String name) { + Objects.requireNonNull(value, name); + if (value.length == 0 || value.length > MAX_BYTES) { + throw new IllegalArgumentException(name + " is outside the exact payload bound"); + } + return value.clone(); + } + + private static UUID requireNonNil(UUID value, String name) { + Objects.requireNonNull(value, name); + if (value.equals(new UUID(0L, 0L))) + throw new IllegalArgumentException(name + " must not be nil"); + return value; + } + + private static BigInteger requirePositive(BigInteger value, String name) { + Objects.requireNonNull(value, name); + if (value.signum() <= 0 || value.toString().length() > 256) { + throw new IllegalArgumentException(name + " must be a bounded positive integer"); + } + return value; + } + + private static String requireIssuer(String value) { + if (!GameSessionAccountDelegationProfile.ISSUER.equals(value)) { + throw new IllegalArgumentException("Issuer admission barrier requires the Account issuer"); + } + return value; + } + + private static String requireTag(String value) { + Objects.requireNonNull(value, "tenantGameplayTag"); + if (!value.matches("g[1-9][0-9]{0,9}-[0-9a-f]{32}")) { + throw new IllegalArgumentException("Issuer admission barrier requires an exact gameplay tag"); + } + return value; + } + + private static String requireDigest(String value, String name) { + Objects.requireNonNull(value, name); + if (!value.matches("sha256:[0-9a-f]{64}")) { + throw new IllegalArgumentException(name + " must be canonical SHA-256"); + } + return value; + } + + private static void requireDigestMatches(byte[] bytes, String digest, String name) { + if (!sha256(bytes).equals(digest)) throw new IllegalArgumentException(name + " digest differs"); + } + + @FunctionalInterface + private interface Writer { + void write(DataOutputStream output) throws IOException; + } +} diff --git a/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/repository/CanonicalGameplayIssuerAdmissionControlRepository.java b/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/repository/CanonicalGameplayIssuerAdmissionControlRepository.java new file mode 100644 index 0000000000..c6410fbccf --- /dev/null +++ b/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/repository/CanonicalGameplayIssuerAdmissionControlRepository.java @@ -0,0 +1,1302 @@ +package net.firedevops.firemud.gamesession.repository; + +import java.math.BigInteger; +import java.nio.ByteBuffer; +import java.nio.charset.StandardCharsets; +import java.security.MessageDigest; +import java.security.NoSuchAlgorithmException; +import java.util.ArrayList; +import java.util.Arrays; +import java.util.Comparator; +import java.util.HexFormat; +import java.util.List; +import java.util.Map; +import java.util.Objects; +import java.util.TreeMap; +import java.util.UUID; +import net.firedevops.firemud.common.security.GameSessionAccountDelegationProfile; +import org.jooq.DSLContext; +import org.jooq.Record; +import org.jooq.impl.DSL; +import org.springframework.transaction.support.TransactionSynchronizationManager; + +/** SQL owner for the positive, reset-sensitive live issuer admission-control row. */ +final class CanonicalGameplayIssuerAdmissionControlRepository { + private static final String ISSUER = GameSessionAccountDelegationProfile.ISSUER; + private static final String CONTROL = "game_session_canonical_issuer_admission_control"; + private static final String COUNTER = "game_session_canonical_issuer_admission_epoch_counter"; + private static final String OPERATION = "game_session_canonical_issuer_admission_operation"; + private static final String LAYOUT_CONTROL = + "game_session_canonical_issuer_layout_bootstrap_control"; + private static final String ANCHOR = "game_session_canonical_issuer_installed_anchor"; + private static final String LOCAL_OPERATION = + "game_session_canonical_issuer_binding_local_operation"; + private static final String BOOTSTRAP_MEMBER_OPERATION = + "game_session_canonical_issuer_bootstrap_member_operation"; + private static final String COHORT = "game_session_canonical_issuer_admission_cohort_row"; + private static final String INITIALIZER = "game_session_canonical_issuer_admission_initializer"; + private static final String INITIALIZER_RECEIPT = + "game_session_canonical_issuer_admission_initializer_receipt"; + private static final String CUTOFF_TARGET = + "game_session_canonical_issuer_admission_cutoff_target"; + private static final String TENANT_TAG = "game_session_canonical_tenant_gameplay_tag"; + + private final DSLContext dsl; + + CanonicalGameplayIssuerAdmissionControlRepository(DSLContext dsl) { + this.dsl = Objects.requireNonNull(dsl, "dsl"); + } + + /** + * Positively installs the first live OPEN row from an already-qualified immutable anchor. The + * source and incarnation are controlled local observations, not authority produced here. + */ + CanonicalGameplayIssuerAdmissionControlValue installInitialOpen( + CanonicalGameplayIssuerInstalledAnchor anchor, + CanonicalGameplayIssuerBootstrapPartitionRedisOwner.CurrentIssuerStateSource + currentStateSource) { + Objects.requireNonNull(anchor, "anchor"); + Objects.requireNonNull(currentStateSource, "currentStateSource"); + requireNoAmbientTransaction(); + CanonicalGameplayIssuerBootstrapPartitionRedisOwner.CurrentIssuerState before = + Objects.requireNonNull( + currentStateSource.readFreshCurrentState(), "current state source returned null"); + CanonicalGameplayIssuerAdmissionControlValue installed = + dsl.transactionResult( + configuration -> installInitialInTransaction(DSL.using(configuration), anchor, before)); + CanonicalGameplayIssuerBootstrapPartitionRedisOwner.CurrentIssuerState after = + Objects.requireNonNull( + currentStateSource.readFreshCurrentState(), + "current state source returned null after install"); + if (!installed.matchesCurrentIssuerState(after)) { + throw conflict( + "Current Account issuer source or stable incarnation moved during live-control installation"); + } + return installed; + } + + /** + * Freezes the complete current issuer cohort and advances the positive live-control epoch before + * any tenant-local CLOSED writes are attempted. Tenant keys come from the locked cohort and each + * key must have its exact positive current SQL tenant-tag mapping. + */ + CanonicalGameplayIssuerAdmissionControlValue beginCutoff( + UUID cutoffOperationId, + UUID requestId, + CanonicalGameplayIssuerInstalledAnchor anchor, + CanonicalGameplayIssuerBootstrapPartitionRedisOwner.CurrentIssuerState currentState) { + requireNonNil(cutoffOperationId, "cutoffOperationId"); + requireNonNil(requestId, "requestId"); + Objects.requireNonNull(anchor, "anchor"); + Objects.requireNonNull(currentState, "currentState"); + if (cutoffOperationId.equals(requestId)) { + throw conflict("Issuer cutoff operation and request identities must be distinct"); + } + requireNoAmbientTransaction(); + return dsl.transactionResult( + configuration -> { + DSLContext transaction = DSL.using(configuration); + BigInteger snapshotRevision = + CanonicalGameplayBindingInventoryRepository.lockInventoryRevision(transaction); + lockLayoutControl(transaction, anchor); + Record controlRow = + transaction.fetchOne( + "SELECT * FROM " + CONTROL + " WHERE issuer_id = ? FOR UPDATE", ISSUER); + if (controlRow == null) { + throw conflict("Issuer cutoff requires a positively installed live control row"); + } + CanonicalGameplayIssuerAdmissionControlValue control = loadControl(controlRow); + requireExactAnchorAndCurrentSource(control, anchor, currentState); + Record counter = + transaction.fetchOne( + "SELECT * FROM " + COUNTER + " WHERE issuer_id = ? FOR UPDATE", ISSUER); + if (counter == null) throw conflict("The positive live issuer epoch counter is missing"); + requireCounterMatchesCurrent(transaction, control.liveBarrierEpoch()); + + Record priorOperation = + transaction.fetchOne( + "SELECT * FROM " + OPERATION + " WHERE operation_id = ? FOR UPDATE", + cutoffOperationId); + if (control.state() == CanonicalGameplayIssuerAdmissionControlValue.State.CUTOFF_PENDING + && control.currentOperationId().equals(cutoffOperationId)) { + if (priorOperation == null + || !requestId.equals(uuid(priorOperation, "request_id")) + || !"CUTOFF".equals(text(priorOperation, "operation_kind")) + || !"CUTOFF_PENDING".equals(text(priorOperation, "operation_state"))) { + throw conflict("Issuer cutoff retry differs from its exact pending operation"); + } + verifyCutoffTargets(transaction, control); + return control; + } + if (control.state() != CanonicalGameplayIssuerAdmissionControlValue.State.OPEN + || control.currentOperationKind() + != CanonicalGameplayIssuerAdmissionControlValue.OperationKind + .INITIAL_ANCHOR_INSTALL + || !control.currentOperationId().equals(anchor.bootstrapOperationId()) + || priorOperation != null) { + throw conflict( + "Issuer live control cannot be reset, reopened, or replaced by this cutoff"); + } + requireInitialOperationCurrent(transaction, control); + + List rows = captureCutoffCohort(transaction, snapshotRevision); + Map> targets = groupTargets(rows); + Map tagByTarget = new TreeMap<>(); + for (TargetScope scope : targets.keySet()) { + tagByTarget.put(scope, requireCurrentTenantTagMapping(transaction, scope.tenantId())); + } + + BigInteger priorEpoch = control.liveBarrierEpoch(); + Record allocated = + transaction.fetchOne( + "UPDATE " + + COUNTER + + " SET last_live_barrier_epoch = last_live_barrier_epoch + 1," + + " updated_at = CURRENT_TIMESTAMP" + + " WHERE issuer_id = ? AND last_live_barrier_epoch = ?" + + " RETURNING last_live_barrier_epoch", + ISSUER, + priorEpoch); + if (allocated == null) { + throw conflict("Issuer cutoff lost its serialized live epoch allocation"); + } + BigInteger cutoffEpoch = integer(allocated, "last_live_barrier_epoch"); + String cohortDigest = digestCohort(rows); + CanonicalGameplayIssuerAdmissionControlValue pending = + control.cutoffPending( + cutoffOperationId, cutoffEpoch, snapshotRevision, rows.size(), cohortDigest); + insertCutoffOperation(transaction, pending, requestId, priorEpoch); + updateControl(transaction, pending, control.liveBarrierEpoch()); + insertCohortRows(transaction, pending.currentOperationId(), rows); + insertCutoffTargets(transaction, pending, targets, tagByTarget); + verifyCutoffTargets(transaction, pending); + return pending; + }); + } + + /** Publishes INSTALLED only after every captured tenant target has an exact CLOSED readback. */ + CanonicalGameplayIssuerAdmissionControlValue completeCutoff( + UUID cutoffOperationId, + CanonicalGameplayIssuerInstalledAnchor anchor, + CanonicalGameplayIssuerBootstrapPartitionRedisOwner.CurrentIssuerState currentState) { + requireNonNil(cutoffOperationId, "cutoffOperationId"); + Objects.requireNonNull(anchor, "anchor"); + Objects.requireNonNull(currentState, "currentState"); + requireNoAmbientTransaction(); + return dsl.transactionResult( + configuration -> { + DSLContext transaction = DSL.using(configuration); + CanonicalGameplayBindingInventoryRepository.lockInventoryRevision(transaction); + lockLayoutControl(transaction, anchor); + Record controlRow = + transaction.fetchOne( + "SELECT * FROM " + CONTROL + " WHERE issuer_id = ? FOR UPDATE", ISSUER); + if (controlRow == null) throw conflict("Issuer cutoff control row is missing"); + CanonicalGameplayIssuerAdmissionControlValue control = loadControl(controlRow); + requireExactAnchorAndCurrentSource(control, anchor, currentState); + requireCounterMatchesCurrent(transaction, control.liveBarrierEpoch()); + if (!control.currentOperationId().equals(cutoffOperationId) + || control.state() + != CanonicalGameplayIssuerAdmissionControlValue.State.CUTOFF_PENDING + || control.currentOperationKind() + != CanonicalGameplayIssuerAdmissionControlValue.OperationKind.CUTOFF) { + if (control.currentOperationId().equals(cutoffOperationId) + && control.state() + == CanonicalGameplayIssuerAdmissionControlValue.State.INSTALLED) { + requireCutoffOperationCurrent(transaction, control); + verifyCutoffTargets(transaction, control); + return control; + } + throw conflict("The exact current cutoff is not pending completion"); + } + requireCutoffOperationCurrent(transaction, control); + verifyCutoffTargets(transaction, control); + Record remaining = + transaction.fetchOne( + "SELECT EXISTS (SELECT 1 FROM " + + CUTOFF_TARGET + + " WHERE operation_id = ? AND issuer_id = ? AND target_state <> 'CLOSED')" + + " AS has_open_target", + cutoffOperationId, + ISSUER); + if (remaining == null + || Boolean.TRUE.equals(remaining.get("has_open_target", Boolean.class))) { + throw conflict( + "Every frozen issuer tenant target must read back CLOSED before installation"); + } + CanonicalGameplayIssuerAdmissionControlValue installed = control.installed(); + int updatedOperation = + transaction.execute( + "UPDATE " + + OPERATION + + " SET operation_state = 'INSTALLED', installed_at = CURRENT_TIMESTAMP" + + " WHERE operation_id = ? AND issuer_id = ? AND operation_kind = 'CUTOFF'" + + " AND operation_state = 'CUTOFF_PENDING' AND live_barrier_epoch = ?" + + " AND prior_live_barrier_epoch = ?", + cutoffOperationId, + ISSUER, + control.liveBarrierEpoch(), + control.liveBarrierEpoch().subtract(BigInteger.ONE)); + if (updatedOperation != 1) + throw conflict("Issuer cutoff operation changed before installation"); + updateControl(transaction, installed, control.liveBarrierEpoch()); + Record saved = + transaction.fetchOne( + "SELECT * FROM " + CONTROL + " WHERE issuer_id = ? FOR UPDATE", ISSUER); + if (saved == null + || !Arrays.equals(loadControl(saved).exactBytes(), installed.exactBytes())) { + throw conflict("Installed issuer cutoff did not read back exactly"); + } + return installed; + }); + } + + /** Revalidates a requested CLOSED key against the complete frozen cutoff cohort. */ + void verifyCurrentCutoffTarget( + DSLContext transaction, + CanonicalGameplayIssuerAdmissionControlValue control, + UUID tenantId, + UUID namespaceId, + byte[] expectedClosedPayload) { + Objects.requireNonNull(transaction, "transaction"); + Objects.requireNonNull(control, "control"); + requireNonNil(tenantId, "tenantId"); + requireNonNil(namespaceId, "namespaceId"); + if (control.state() != CanonicalGameplayIssuerAdmissionControlValue.State.CUTOFF_PENDING + || control.currentOperationKind() + != CanonicalGameplayIssuerAdmissionControlValue.OperationKind.CUTOFF) { + throw conflict("A CLOSED target requires the current pending issuer cutoff"); + } + requireCutoffOperationCurrent(transaction, control); + verifyCutoffTargets(transaction, control); + Record target = + transaction.fetchOne( + "SELECT * FROM " + + CUTOFF_TARGET + + " WHERE operation_id = ? AND issuer_id = ? AND tenant_id = ?" + + " AND playable_state_namespace_id = ? FOR UPDATE", + control.currentOperationId(), + ISSUER, + tenantId, + namespaceId); + if (target == null + || (expectedClosedPayload != null + && !Arrays.equals(bytes(target, "closed_payload_bytes"), expectedClosedPayload))) { + throw conflict("Requested CLOSED target differs from the exact frozen cutoff cohort"); + } + } + + private static List captureCutoffCohort( + DSLContext transaction, BigInteger snapshotRevision) { + requireNoFutureCutoffRows(transaction, snapshotRevision); + String sql = + "SELECT source_kind, source_key, source_revision, source_row_json, tenant_id," + + " playable_state_namespace_id, transition_id FROM (" + + " SELECT 'BINDING' AS source_kind, encode(i.binding_ref, 'hex') AS source_key," + + " i.inventory_revision AS source_revision, to_jsonb(i)::text AS source_row_json," + + " i.tenant_id, i.playable_state_namespace_id, i.transition_id" + + " FROM game_session_canonical_gameplay_binding_inventory i" + + " WHERE i.issuer_id = ? AND i.inventory_revision <= ?" + + " UNION ALL SELECT 'TRANSITION', t.transition_id::text, t.inventory_revision," + + " to_jsonb(t)::text, t.tenant_id, t.playable_state_namespace_id, t.transition_id" + + " FROM game_session_canonical_binding_transition t" + + " JOIN game_session_canonical_gameplay_binding_inventory i" + + " ON i.transition_id = t.transition_id AND i.issuer_id = ?" + + " WHERE t.inventory_revision <= ?" + + " UNION ALL SELECT 'RESERVATION', r.reservation_id::text, r.inventory_revision," + + " to_jsonb(r)::text, r.tenant_id, r.playable_state_namespace_id, r.transition_id" + + " FROM game_session_canonical_issuer_partition_reservation r" + + " WHERE r.issuer_id = ? AND r.inventory_revision <= ?" + + " UNION ALL SELECT 'ACCOUNT_OBLIGATION'," + + " a.transition_id::text || ':' || a.obligation_ordinal::text, a.inventory_revision," + + " to_jsonb(a)::text, t.tenant_id, t.playable_state_namespace_id, t.transition_id" + + " FROM game_session_canonical_binding_account_index_obligation a" + + " JOIN game_session_canonical_binding_transition t ON t.transition_id = a.transition_id" + + " JOIN game_session_canonical_gameplay_binding_inventory i" + + " ON i.binding_ref = a.binding_ref AND i.issuer_id = ?" + + " WHERE a.inventory_revision <= ?" + + " UNION ALL SELECT 'ISSUER_OBLIGATION'," + + " encode(o.binding_ref, 'hex') || ':' || o.transition_id::text, o.inventory_revision," + + " to_jsonb(o)::text, t.tenant_id, t.playable_state_namespace_id, t.transition_id" + + " FROM game_session_canonical_binding_issuer_index_obligation o" + + " JOIN game_session_canonical_binding_transition t ON t.transition_id = o.transition_id" + + " JOIN game_session_canonical_gameplay_binding_inventory i" + + " ON i.binding_ref = o.binding_ref AND i.issuer_id = ?" + + " WHERE o.inventory_revision <= ?" + + " UNION ALL SELECT 'REGION_OBLIGATION', g.transition_id::text, g.inventory_revision," + + " to_jsonb(g)::text, t.tenant_id, t.playable_state_namespace_id, t.transition_id" + + " FROM game_session_canonical_binding_region_bridge_obligation g" + + " JOIN game_session_canonical_binding_transition t ON t.transition_id = g.transition_id" + + " JOIN game_session_canonical_gameplay_binding_inventory i" + + " ON i.binding_ref = g.binding_ref AND i.issuer_id = ?" + + " WHERE g.inventory_revision <= ?" + + " UNION ALL SELECT 'LOCAL_OPERATION', o.operation_id::text," + + " o.local_inventory_snapshot_revision, to_jsonb(o)::text, t.tenant_id," + + " t.playable_state_namespace_id, t.transition_id" + + " FROM game_session_canonical_issuer_binding_local_operation o" + + " JOIN game_session_canonical_binding_transition t ON t.transition_id = o.transition_id" + + " WHERE o.issuer_id = ? AND o.local_inventory_snapshot_revision <= ?" + + " UNION ALL SELECT 'BOOTSTRAP_MEMBER_OPERATION', m.member_operation_id::text," + + " m.original_inventory_snapshot_revision, to_jsonb(m)::text, r.tenant_id," + + " r.playable_state_namespace_id, r.transition_id" + + " FROM game_session_canonical_issuer_bootstrap_member_operation m" + + " JOIN game_session_canonical_issuer_partition_reservation r" + + " ON r.reservation_id = m.reservation_id" + + " WHERE m.issuer_id = ? AND m.original_inventory_snapshot_revision <= ?" + + " UNION ALL SELECT 'PENDING_INITIALIZER', init.operation_id::text," + + " local.local_inventory_snapshot_revision, to_jsonb(init)::text, init.tenant_id," + + " init.playable_state_namespace_id, local.transition_id" + + " FROM game_session_canonical_issuer_admission_initializer init" + + " JOIN game_session_canonical_issuer_binding_local_operation local" + + " ON local.operation_id = init.operation_id AND local.issuer_id = init.issuer_id" + + " LEFT JOIN game_session_canonical_issuer_admission_initializer_receipt receipt" + + " ON receipt.operation_id = init.operation_id AND receipt.issuer_id = init.issuer_id" + + " WHERE init.issuer_id = ? AND receipt.operation_id IS NULL" + + " AND local.local_inventory_snapshot_revision <= ?" + + ") captured ORDER BY source_kind COLLATE \"C\", source_key COLLATE \"C\""; + List binds = new ArrayList<>(); + for (int index = 0; index < 9; index++) { + binds.add(ISSUER); + binds.add(snapshotRevision); + } + return transaction + .fetch(sql, binds.toArray()) + .map( + row -> { + String json = text(row, "source_row_json"); + String digest = + CanonicalGameplayIssuerAdmissionControlValue.sha256( + json.getBytes(StandardCharsets.UTF_8)); + BigInteger revision = integer(row, "source_revision"); + if (revision.signum() <= 0 || revision.compareTo(snapshotRevision) > 0) { + throw conflict( + "Issuer cutoff cohort contains a source outside its locked snapshot"); + } + return new CohortRow( + text(row, "source_kind"), + text(row, "source_key"), + revision, + json, + uuid(row, "tenant_id"), + uuid(row, "playable_state_namespace_id"), + uuid(row, "transition_id"), + digest); + }); + } + + private static void requireNoFutureCutoffRows( + DSLContext transaction, BigInteger snapshotRevision) { + String sql = + "SELECT EXISTS (SELECT 1 FROM game_session_canonical_gameplay_binding_inventory" + + " WHERE issuer_id = ? AND inventory_revision > ?)" + + " OR EXISTS (SELECT 1 FROM game_session_canonical_binding_transition t" + + " JOIN game_session_canonical_gameplay_binding_inventory i" + + " ON i.transition_id = t.transition_id AND i.issuer_id = ?" + + " WHERE t.inventory_revision > ?)" + + " OR EXISTS (SELECT 1 FROM game_session_canonical_issuer_partition_reservation" + + " WHERE issuer_id = ? AND inventory_revision > ?)" + + " OR EXISTS (SELECT 1 FROM game_session_canonical_binding_account_index_obligation a" + + " JOIN game_session_canonical_gameplay_binding_inventory i" + + " ON i.binding_ref = a.binding_ref AND i.issuer_id = ?" + + " WHERE a.inventory_revision > ?)" + + " OR EXISTS (SELECT 1 FROM game_session_canonical_binding_issuer_index_obligation o" + + " JOIN game_session_canonical_gameplay_binding_inventory i" + + " ON i.binding_ref = o.binding_ref AND i.issuer_id = ?" + + " WHERE o.inventory_revision > ?)" + + " OR EXISTS (SELECT 1 FROM game_session_canonical_binding_region_bridge_obligation g" + + " JOIN game_session_canonical_gameplay_binding_inventory i" + + " ON i.binding_ref = g.binding_ref AND i.issuer_id = ?" + + " WHERE g.inventory_revision > ?)" + + " OR EXISTS (SELECT 1 FROM game_session_canonical_issuer_binding_local_operation" + + " WHERE issuer_id = ? AND local_inventory_snapshot_revision > ?)" + + " OR EXISTS (SELECT 1 FROM game_session_canonical_issuer_bootstrap_member_operation" + + " WHERE issuer_id = ? AND original_inventory_snapshot_revision > ?)" + + " OR EXISTS (SELECT 1 FROM game_session_canonical_issuer_admission_initializer init" + + " JOIN game_session_canonical_issuer_binding_local_operation local" + + " ON local.operation_id = init.operation_id AND local.issuer_id = init.issuer_id" + + " WHERE init.issuer_id = ? AND local.local_inventory_snapshot_revision > ?)" + + " AS has_future_rows"; + List binds = new ArrayList<>(); + for (int index = 0; index < 9; index++) { + binds.add(ISSUER); + binds.add(snapshotRevision); + } + Record future = transaction.fetchOne(sql, binds.toArray()); + if (future == null || Boolean.TRUE.equals(future.get("has_future_rows", Boolean.class))) { + throw conflict( + "Issuer cutoff found source rows newer than its serialized inventory snapshot"); + } + } + + private static Map> groupTargets(List rows) { + Map> targets = new TreeMap<>(); + for (CohortRow row : rows) { + TargetScope scope = new TargetScope(row.tenantId(), row.namespaceId()); + targets.computeIfAbsent(scope, ignored -> new ArrayList<>()).add(row); + } + return targets; + } + + private static void insertCutoffOperation( + DSLContext transaction, + CanonicalGameplayIssuerAdmissionControlValue value, + UUID requestId, + BigInteger priorEpoch) { + int inserted = + transaction.execute( + "INSERT INTO " + + OPERATION + + " (operation_id, request_id, issuer_id, operation_kind, operation_state," + + " live_barrier_epoch, prior_live_barrier_epoch, bootstrap_operation_id," + + " bootstrap_request_id, bootstrap_control_epoch, anchor_exact_bytes," + + " anchor_exact_digest, account_issuer_auth_generation, account_checkpoint_bytes," + + " account_checkpoint_digest, account_source_event_bytes, account_source_event_digest," + + " stable_incarnation_bytes, stable_incarnation_digest, inventory_snapshot_revision," + + " cohort_row_count, cohort_digest, installed_at)" + + " VALUES (?, ?, ?, 'CUTOFF', 'CUTOFF_PENDING', ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, NULL)", + value.currentOperationId(), + requestId, + value.issuerId(), + value.liveBarrierEpoch(), + priorEpoch, + value.bootstrapOperationId(), + value.bootstrapRequestId(), + value.bootstrapControlEpoch(), + value.anchorExactBytes(), + value.anchorExactDigest(), + value.accountIssuerAuthGeneration(), + value.accountCheckpointBytes(), + value.accountCheckpointDigest(), + value.accountSourceEventBytes(), + value.accountSourceEventDigest(), + value.stableIncarnationBytes(), + value.stableIncarnationDigest(), + value.inventorySnapshotRevision(), + value.cohortRowCount(), + value.cohortDigest()); + if (inserted != 1) throw conflict("Issuer cutoff operation did not persist"); + } + + private static void insertCohortRows( + DSLContext transaction, UUID operationId, List rows) { + for (int index = 0; index < rows.size(); index++) { + CohortRow row = rows.get(index); + int inserted = + transaction.execute( + "INSERT INTO " + + COHORT + + " (operation_id, issuer_id, row_ordinal, source_kind, source_key," + + " source_inventory_revision, source_row_json, source_row_digest)" + + " VALUES (?, ?, ?, ?, ?, ?, ?, ?)", + operationId, + ISSUER, + (long) index, + row.sourceKind(), + row.sourceKey(), + row.sourceRevision(), + row.sourceJson(), + row.sourceDigest()); + if (inserted != 1) throw conflict("Issuer cutoff cohort row did not persist"); + } + } + + private static void insertCutoffTargets( + DSLContext transaction, + CanonicalGameplayIssuerAdmissionControlValue control, + Map> targets, + Map tagByTarget) { + int ordinal = 0; + for (Map.Entry> entry : targets.entrySet()) { + TargetScope scope = entry.getKey(); + String tenantTag = tagByTarget.get(scope); + if (tenantTag == null) throw conflict("Issuer cutoff target has no current SQL tenant tag"); + Record initializerRow = + transaction.fetchOne( + "SELECT * FROM " + + INITIALIZER + + " WHERE issuer_id = ? AND tenant_id = ? AND playable_state_namespace_id = ?" + + " AND live_barrier_epoch <= ? ORDER BY live_barrier_epoch DESC LIMIT 1 FOR UPDATE", + ISSUER, + scope.tenantId(), + scope.namespaceId(), + control.liveBarrierEpoch().subtract(BigInteger.ONE)); + CanonicalGameplayIssuerAdmissionBarrierValue.Initializer initializer = null; + byte[] openPayload = null; + String openDigest = null; + UUID initializerOperationId = null; + BigInteger initializerEpoch = null; + String initializerDigest = null; + if (initializerRow != null) { + initializerOperationId = uuid(initializerRow, "operation_id"); + initializerEpoch = integer(initializerRow, "live_barrier_epoch"); + byte[] initializerBytes = bytes(initializerRow, "initializer_exact_bytes"); + initializerDigest = text(initializerRow, "initializer_digest"); + openPayload = bytes(initializerRow, "open_payload_bytes"); + openDigest = text(initializerRow, "open_payload_digest"); + if (!CanonicalGameplayIssuerAdmissionControlValue.sha256(initializerBytes) + .equals(initializerDigest) + || !CanonicalGameplayIssuerAdmissionControlValue.sha256(openPayload) + .equals(openDigest)) { + throw conflict("Persisted original issuer initializer digest is invalid"); + } + CanonicalGameplayIssuerAdmissionBarrierValue decoded = + CanonicalGameplayIssuerAdmissionBarrierValue.decode(openPayload); + initializer = decoded.initializer(); + if (decoded.state() != CanonicalGameplayIssuerAdmissionBarrierValue.State.OPEN + || !decoded.issuerId().equals(ISSUER) + || !decoded.tenantId().equals(scope.tenantId()) + || !decoded.playableStateNamespaceId().equals(scope.namespaceId()) + || !decoded.tenantGameplayTag().equals(tenantTag) + || !decoded.ownerOperationId().equals(initializerOperationId) + || !decoded.admissionEpoch().equals(initializerEpoch) + || initializer == null + || !initializer.exactDigest().equals(initializerDigest) + || !initializer.operationId().equals(initializerOperationId) + || !initializer.admissionEpoch().equals(initializerEpoch) + || !initializer.tenantGameplayTag().equals(tenantTag) + || !Arrays.equals(initializer.anchorBytes(), control.anchorExactBytes()) + || !initializer.anchorDigest().equals(control.anchorExactDigest()) + || !initializer + .accountIssuerAuthGeneration() + .equals(control.accountIssuerAuthGeneration()) + || !Arrays.equals( + initializer.accountCheckpointBytes(), control.accountCheckpointBytes()) + || !initializer.accountCheckpointDigest().equals(control.accountCheckpointDigest()) + || !Arrays.equals( + initializer.accountSourceEventBytes(), control.accountSourceEventBytes()) + || !Objects.equals( + initializer.accountSourceEventDigest(), control.accountSourceEventDigest()) + || !Arrays.equals(initializer.incarnationBytes(), control.stableIncarnationBytes()) + || !initializer.incarnationDigest().equals(control.stableIncarnationDigest())) { + throw conflict( + "Captured original OPEN initializer differs from the frozen issuer source"); + } + } + String targetDigest = digestTargetSource(entry.getValue()); + CanonicalGameplayIssuerAdmissionBarrierValue closed = + CanonicalGameplayIssuerAdmissionBarrierValue.closed( + ISSUER, + scope.tenantId(), + scope.namespaceId(), + tenantTag, + control.liveBarrierEpoch(), + control.currentOperationId(), + initializer); + int inserted = + transaction.execute( + "INSERT INTO " + + CUTOFF_TARGET + + " (operation_id, issuer_id, target_ordinal, tenant_id," + + " playable_state_namespace_id, tenant_gameplay_tag, target_source_digest," + + " captured_initializer_operation_id, captured_initializer_epoch," + + " captured_initializer_digest, captured_open_payload_bytes," + + " captured_open_payload_digest, closed_payload_bytes, closed_payload_digest," + + " exact_closed_readback_bytes, exact_closed_readback_digest, script_outcome, target_state)" + + " VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, NULL, NULL, NULL, 'REQUIRED')", + control.currentOperationId(), + ISSUER, + (long) ordinal++, + scope.tenantId(), + scope.namespaceId(), + tenantTag, + targetDigest, + initializerOperationId, + initializerEpoch, + initializerDigest, + openPayload, + openDigest, + closed.exactBytes(), + closed.exactDigest()); + if (inserted != 1) throw conflict("Issuer cutoff target did not persist"); + } + } + + private static List verifyFrozenCohort( + DSLContext transaction, CanonicalGameplayIssuerAdmissionControlValue control) { + // Terminal cleanup may advance live source revisions after intent. Resolve every target only + // from the original retained JSON and its retained transition/reservation dependencies. + List rows = + transaction + .fetch( + "WITH frozen AS (SELECT *, source_row_json::jsonb AS source FROM " + + COHORT + + " WHERE operation_id = ? AND issuer_id = ?)" + + " SELECT c.*, (scope.source ->> 'tenant_id')::uuid AS tenant_id," + + " (scope.source ->> 'playable_state_namespace_id')::uuid" + + " AS playable_state_namespace_id FROM frozen c" + + " LEFT JOIN frozen transition ON transition.source_kind = 'TRANSITION'" + + " AND transition.source_key = c.source ->> 'transition_id'" + + " LEFT JOIN frozen reservation ON reservation.source_kind = 'RESERVATION'" + + " AND reservation.source_key = c.source ->> 'reservation_id'" + + " CROSS JOIN LATERAL (SELECT CASE" + + " WHEN c.source_kind IN ('BINDING', 'TRANSITION', 'RESERVATION'," + + " 'PENDING_INITIALIZER') THEN c.source" + + " WHEN c.source_kind IN ('ACCOUNT_OBLIGATION', 'ISSUER_OBLIGATION'," + + " 'REGION_OBLIGATION', 'LOCAL_OPERATION') THEN transition.source" + + " WHEN c.source_kind = 'BOOTSTRAP_MEMBER_OPERATION' THEN reservation.source" + + " END AS source) scope ORDER BY c.row_ordinal", + control.currentOperationId(), + ISSUER) + .map( + row -> { + String json = text(row, "source_row_json"); + String storedDigest = text(row, "source_row_digest"); + if (!CanonicalGameplayIssuerAdmissionControlValue.sha256( + json.getBytes(StandardCharsets.UTF_8)) + .equals(storedDigest)) { + throw conflict( + "Issuer cutoff cohort source digest differs from its stored JSON"); + } + return new CohortRow( + text(row, "source_kind"), + text(row, "source_key"), + integer(row, "source_inventory_revision"), + json, + uuid(row, "tenant_id"), + uuid(row, "playable_state_namespace_id"), + null, + storedDigest); + }); + for (int index = 0; index < rows.size(); index++) { + if (rows.get(index).sourceRevision().compareTo(control.inventorySnapshotRevision()) > 0) { + throw conflict("Issuer cutoff cohort row is newer than its frozen inventory snapshot"); + } + Record ordinal = + transaction.fetchOne( + "SELECT row_ordinal FROM " + + COHORT + + " WHERE operation_id = ? AND issuer_id = ? AND source_kind = ? AND source_key = ?", + control.currentOperationId(), + ISSUER, + rows.get(index).sourceKind(), + rows.get(index).sourceKey()); + if (ordinal == null || longInteger(ordinal, "row_ordinal") != index) { + throw conflict("Issuer cutoff cohort ordinals are not contiguous and canonical"); + } + } + if (rows.size() != control.cohortRowCount() + || !digestCohort(rows).equals(control.cohortDigest())) { + throw conflict("Issuer cutoff cohort no longer matches its frozen complete digest"); + } + return rows; + } + + private static String requireCurrentTenantTagMapping(DSLContext transaction, UUID tenantId) { + Record mapping = + transaction.fetchOne( + "SELECT allocation_version, tenant_gameplay_tag FROM " + + TENANT_TAG + + " WHERE tenant_id = ? FOR SHARE", + tenantId); + Integer version = mapping == null ? null : mapping.get("allocation_version", Integer.class); + String tag = mapping == null ? null : mapping.get("tenant_gameplay_tag", String.class); + if (version == null + || version <= 0 + || tag == null + || !tag.matches("g[1-9][0-9]{0,9}-[0-9a-f]{32}") + || !tag.equals("g" + version + "-" + tenantId.toString().replace("-", ""))) { + throw conflict("Issuer cutoff requires a positive exact SQL tenant gameplay-tag mapping"); + } + return tag; + } + + private static void verifyCutoffTargets( + DSLContext transaction, CanonicalGameplayIssuerAdmissionControlValue control) { + List rows = + transaction.fetch( + "SELECT * FROM " + + CUTOFF_TARGET + + " WHERE operation_id = ? AND issuer_id = ? ORDER BY target_ordinal", + control.currentOperationId(), + ISSUER); + Map> cohortTargets = + groupTargets(verifyFrozenCohort(transaction, control)); + if (rows.size() != cohortTargets.size()) { + throw conflict("Issuer cutoff target set differs from its complete frozen cohort"); + } + for (int index = 0; index < rows.size(); index++) { + Record row = rows.get(index); + UUID tenantId = uuid(row, "tenant_id"); + UUID namespaceId = uuid(row, "playable_state_namespace_id"); + String tenantTag = text(row, "tenant_gameplay_tag"); + TargetScope scope = new TargetScope(tenantId, namespaceId); + List sources = cohortTargets.get(scope); + if (!tenantTag.equals(requireCurrentTenantTagMapping(transaction, tenantId))) { + throw conflict("Issuer cutoff tenant tag differs from the current immutable SQL mapping"); + } + if (sources == null + || longInteger(row, "target_ordinal") != index + || !CanonicalGameplayIssuerAdmissionControlValue.sha256( + bytes(row, "closed_payload_bytes")) + .equals(text(row, "closed_payload_digest")) + || !digestTargetSource(sources).equals(text(row, "target_source_digest"))) { + throw conflict("Issuer cutoff target differs from its immutable captured source"); + } + CanonicalGameplayIssuerAdmissionBarrierValue closed = + CanonicalGameplayIssuerAdmissionBarrierValue.decode(bytes(row, "closed_payload_bytes")); + if (closed.state() != CanonicalGameplayIssuerAdmissionBarrierValue.State.CLOSED + || !closed.issuerId().equals(ISSUER) + || !closed.tenantId().equals(tenantId) + || !closed.playableStateNamespaceId().equals(namespaceId) + || !closed.tenantGameplayTag().equals(tenantTag) + || !closed.ownerOperationId().equals(control.currentOperationId()) + || !closed.admissionEpoch().equals(control.liveBarrierEpoch())) { + throw conflict("Issuer cutoff target payload does not bind its exact live cutoff"); + } + byte[] capturedOpen = nullableBytes(row, "captured_open_payload_bytes"); + if (capturedOpen != null) { + CanonicalGameplayIssuerAdmissionBarrierValue open = + CanonicalGameplayIssuerAdmissionBarrierValue.decode(capturedOpen); + if (open.state() != CanonicalGameplayIssuerAdmissionBarrierValue.State.OPEN + || closed.initializer() == null + || !Arrays.equals(open.initializer().exactBytes(), closed.initializer().exactBytes()) + || !CanonicalGameplayIssuerAdmissionControlValue.sha256(capturedOpen) + .equals(text(row, "captured_open_payload_digest"))) { + throw conflict("Issuer cutoff target lost its exact captured original OPEN value"); + } + } else if (closed.initializer() != null + || nullableBytes(row, "captured_open_payload_digest") != null + || row.get("captured_initializer_operation_id", UUID.class) != null + || row.get("captured_initializer_epoch", java.math.BigDecimal.class) != null + || row.get("captured_initializer_digest", String.class) != null) { + throw conflict("Issuer cutoff target has partial initializer evidence"); + } + byte[] readback = nullableBytes(row, "exact_closed_readback_bytes"); + if ("CLOSED".equals(text(row, "target_state"))) { + if (readback == null + || !CanonicalGameplayIssuerAdmissionControlValue.sha256(readback) + .equals(text(row, "exact_closed_readback_digest")) + || !Arrays.equals(readback, closed.exactBytes())) { + throw conflict("Issuer CLOSED receipt differs from its exact persistent target payload"); + } + } else if (!"REQUIRED".equals(text(row, "target_state")) || readback != null) { + throw conflict("Issuer cutoff target has an unknown or partial readback state"); + } + } + } + + private static void requireCutoffOperationCurrent( + DSLContext transaction, CanonicalGameplayIssuerAdmissionControlValue control) { + Record operation = + transaction.fetchOne( + "SELECT * FROM " + OPERATION + " WHERE operation_id = ? FOR UPDATE", + control.currentOperationId()); + if (operation == null + || !ISSUER.equals(text(operation, "issuer_id")) + || !"CUTOFF".equals(text(operation, "operation_kind")) + || !text(operation, "operation_state").equals(control.state().name()) + || !control.liveBarrierEpoch().equals(integer(operation, "live_barrier_epoch")) + || !control.bootstrapOperationId().equals(uuid(operation, "bootstrap_operation_id")) + || !control.bootstrapRequestId().equals(uuid(operation, "bootstrap_request_id")) + || !control.bootstrapControlEpoch().equals(integer(operation, "bootstrap_control_epoch")) + || !Arrays.equals(control.anchorExactBytes(), bytes(operation, "anchor_exact_bytes")) + || !control.anchorExactDigest().equals(text(operation, "anchor_exact_digest")) + || !control + .accountIssuerAuthGeneration() + .equals(integer(operation, "account_issuer_auth_generation")) + || !Arrays.equals( + control.accountCheckpointBytes(), bytes(operation, "account_checkpoint_bytes")) + || !control.accountCheckpointDigest().equals(text(operation, "account_checkpoint_digest")) + || !Arrays.equals( + control.accountSourceEventBytes(), + nullableBytes(operation, "account_source_event_bytes")) + || !Objects.equals( + control.accountSourceEventDigest(), + nullableText(operation, "account_source_event_digest")) + || !Arrays.equals( + control.stableIncarnationBytes(), bytes(operation, "stable_incarnation_bytes")) + || !control.stableIncarnationDigest().equals(text(operation, "stable_incarnation_digest")) + || !control + .inventorySnapshotRevision() + .equals(integer(operation, "inventory_snapshot_revision")) + || control.cohortRowCount() != longInteger(operation, "cohort_row_count") + || !control.cohortDigest().equals(text(operation, "cohort_digest"))) { + throw conflict("Live issuer cutoff has no exact current durable operation"); + } + } + + private static void updateControl( + DSLContext transaction, + CanonicalGameplayIssuerAdmissionControlValue value, + BigInteger expectedEpoch) { + int updated = + transaction.execute( + "UPDATE " + + CONTROL + + " SET state = ?, live_barrier_epoch = ?, current_operation_id = ?," + + " current_operation_kind = ?, bootstrap_operation_id = ?, bootstrap_request_id = ?," + + " bootstrap_control_epoch = ?, anchor_exact_bytes = ?, anchor_exact_digest = ?," + + " account_issuer_auth_generation = ?, account_checkpoint_bytes = ?," + + " account_checkpoint_digest = ?, account_source_event_bytes = ?," + + " account_source_event_digest = ?, stable_incarnation_bytes = ?," + + " stable_incarnation_digest = ?, inventory_snapshot_revision = ?," + + " cohort_row_count = ?, cohort_digest = ?, control_exact_bytes = ?," + + " control_exact_digest = ?, updated_at = CURRENT_TIMESTAMP" + + " WHERE issuer_id = ? AND live_barrier_epoch = ?", + value.state().name(), + value.liveBarrierEpoch(), + value.currentOperationId(), + value.currentOperationKind().name(), + value.bootstrapOperationId(), + value.bootstrapRequestId(), + value.bootstrapControlEpoch(), + value.anchorExactBytes(), + value.anchorExactDigest(), + value.accountIssuerAuthGeneration(), + value.accountCheckpointBytes(), + value.accountCheckpointDigest(), + value.accountSourceEventBytes(), + value.accountSourceEventDigest(), + value.stableIncarnationBytes(), + value.stableIncarnationDigest(), + value.inventorySnapshotRevision(), + value.cohortRowCount(), + value.cohortDigest(), + value.exactBytes(), + value.exactDigest(), + value.issuerId(), + expectedEpoch); + if (updated != 1) throw conflict("Live issuer control changed before its exact update"); + } + + private static String digestCohort(List rows) { + MessageDigest digest = sha256Digest(); + rows.stream() + .sorted(Comparator.comparing(CohortRow::sourceKind).thenComparing(CohortRow::sourceKey)) + .forEach( + row -> { + updateFramed(digest, row.sourceKind().getBytes(StandardCharsets.UTF_8)); + updateFramed(digest, row.sourceKey().getBytes(StandardCharsets.UTF_8)); + updateFramed( + digest, row.sourceRevision().toString().getBytes(StandardCharsets.US_ASCII)); + updateFramed(digest, row.sourceDigest().getBytes(StandardCharsets.US_ASCII)); + }); + return "sha256:" + HexFormat.of().formatHex(digest.digest()); + } + + private static String digestTargetSource(List rows) { + MessageDigest digest = sha256Digest(); + rows.stream() + .sorted(Comparator.comparing(CohortRow::sourceKind).thenComparing(CohortRow::sourceKey)) + .forEach( + row -> { + updateFramed(digest, row.sourceKind().getBytes(StandardCharsets.UTF_8)); + updateFramed(digest, row.sourceKey().getBytes(StandardCharsets.UTF_8)); + updateFramed(digest, row.sourceDigest().getBytes(StandardCharsets.US_ASCII)); + }); + return "sha256:" + HexFormat.of().formatHex(digest.digest()); + } + + private static MessageDigest sha256Digest() { + try { + return MessageDigest.getInstance("SHA-256"); + } catch (NoSuchAlgorithmException impossible) { + throw new IllegalStateException("SHA-256 is unavailable", impossible); + } + } + + private static void updateFramed(MessageDigest digest, byte[] value) { + digest.update(ByteBuffer.allocate(Integer.BYTES).putInt(value.length).array()); + digest.update(value); + } + + private static void requireNonNil(UUID value, String name) { + if (value == null || value.equals(new UUID(0L, 0L))) { + throw new IllegalArgumentException(name + " must be a non-nil UUID"); + } + } + + private record CohortRow( + String sourceKind, + String sourceKey, + BigInteger sourceRevision, + String sourceJson, + UUID tenantId, + UUID namespaceId, + UUID transitionId, + String sourceDigest) {} + + private record TargetScope(UUID tenantId, UUID namespaceId) implements Comparable { + @Override + public int compareTo(TargetScope other) { + int tenant = tenantId.compareTo(other.tenantId); + return tenant != 0 ? tenant : namespaceId.compareTo(other.namespaceId); + } + } + + /** + * Requires a positive current OPEN control after the caller has locked inventory, then layout + * control. Missing state, source movement, and every cutoff state deny preparation. + */ + static CanonicalGameplayIssuerAdmissionControlValue requireOpenInTransaction( + DSLContext transaction, + CanonicalGameplayIssuerInstalledAnchor anchor, + CanonicalGameplayIssuerBootstrapPartitionRedisOwner.CurrentIssuerState currentState) { + Objects.requireNonNull(transaction, "transaction"); + Objects.requireNonNull(anchor, "anchor"); + Objects.requireNonNull(currentState, "currentState"); + lockLayoutControl(transaction, anchor); + Record row = + transaction.fetchOne( + "SELECT * FROM " + CONTROL + " WHERE issuer_id = ? FOR UPDATE", ISSUER); + if (row == null) + throw conflict("Ordinary issuer work requires a positive live admission-control row"); + CanonicalGameplayIssuerAdmissionControlValue value = loadControl(row); + requireExactAnchorAndCurrentSource(value, anchor, currentState); + if (value.state() != CanonicalGameplayIssuerAdmissionControlValue.State.OPEN + || value.currentOperationKind() + != CanonicalGameplayIssuerAdmissionControlValue.OperationKind.INITIAL_ANCHOR_INSTALL) { + throw conflict("Live issuer admission control is cutting off or installed closed"); + } + requireCounterMatchesCurrent(transaction, value.liveBarrierEpoch()); + requireInitialOperationCurrent(transaction, value); + return value; + } + + private CanonicalGameplayIssuerAdmissionControlValue installInitialInTransaction( + DSLContext transaction, + CanonicalGameplayIssuerInstalledAnchor anchor, + CanonicalGameplayIssuerBootstrapPartitionRedisOwner.CurrentIssuerState currentState) { + CanonicalGameplayBindingInventoryRepository.lockInventoryRevision(transaction); + lockLayoutControl(transaction, anchor); + Record existing = + transaction.fetchOne( + "SELECT * FROM " + CONTROL + " WHERE issuer_id = ? FOR UPDATE", ISSUER); + if (existing != null) { + CanonicalGameplayIssuerAdmissionControlValue prior = loadControl(existing); + requireExactAnchorAndCurrentSource(prior, anchor, currentState); + if (prior.state() == CanonicalGameplayIssuerAdmissionControlValue.State.OPEN + && prior.currentOperationKind() + == CanonicalGameplayIssuerAdmissionControlValue.OperationKind.INITIAL_ANCHOR_INSTALL + && prior.currentOperationId().equals(anchor.bootstrapOperationId())) { + requireCounterMatchesCurrent(transaction, prior.liveBarrierEpoch()); + requireInitialOperationCurrent(transaction, prior); + return prior; + } + throw conflict("Existing issuer admission control cannot be reset or reopened"); + } + + Record counter = + transaction.fetchOne( + "SELECT * FROM " + COUNTER + " WHERE issuer_id = ? FOR UPDATE", ISSUER); + if (counter == null) throw conflict("The positive live issuer epoch counter is missing"); + BigInteger last = integer(counter, "last_live_barrier_epoch"); + if (last.signum() != 0) { + throw conflict("Missing live issuer control cannot be reconstructed from its epoch counter"); + } + // Existing post-anchor operations have no V1046 initializer provenance and cannot be + // reclassified as safe OPEN work during this install. + Record oldLocal = + transaction.fetchOne( + "SELECT EXISTS (SELECT 1 FROM " + LOCAL_OPERATION + " WHERE issuer_id = ?) AS has_rows", + ISSUER); + if (oldLocal == null || Boolean.TRUE.equals(oldLocal.get("has_rows", Boolean.class))) { + throw conflict("Initial live control cannot adopt an unregistered local issuer operation"); + } + + Record allocated = + transaction.fetchOne( + "UPDATE " + + COUNTER + + " SET last_live_barrier_epoch = last_live_barrier_epoch + 1," + + " updated_at = CURRENT_TIMESTAMP" + + " WHERE issuer_id = ? AND last_live_barrier_epoch = 0" + + " RETURNING last_live_barrier_epoch", + ISSUER); + if (allocated == null) + throw conflict("Live issuer epoch allocation lost its serialized counter"); + BigInteger liveEpoch = integer(allocated, "last_live_barrier_epoch"); + CanonicalGameplayIssuerAdmissionControlValue requested = + CanonicalGameplayIssuerAdmissionControlValue.initialOpen( + anchor, + currentState, + liveEpoch, + 0L, + CanonicalGameplayIssuerAdmissionControlValue.sha256( + "issuer-admission-initial-cohort/v1" + .getBytes(java.nio.charset.StandardCharsets.UTF_8))); + + insertInitialOperation(transaction, requested); + insertControl(transaction, requested); + Record saved = + transaction.fetchOne( + "SELECT * FROM " + CONTROL + " WHERE issuer_id = ? FOR UPDATE", ISSUER); + if (saved == null) throw conflict("Initial live issuer control did not persist"); + CanonicalGameplayIssuerAdmissionControlValue result = loadControl(saved); + if (!Arrays.equals(result.exactBytes(), requested.exactBytes())) { + throw conflict("Persisted initial live issuer control differs from its exact owner value"); + } + return result; + } + + private static void lockLayoutControl( + DSLContext transaction, CanonicalGameplayIssuerInstalledAnchor anchor) { + Record control = + transaction.fetchOne( + "SELECT * FROM " + LAYOUT_CONTROL + " WHERE issuer_id = ? FOR UPDATE", ISSUER); + if (control == null + || !ISSUER.equals(text(control, "issuer_id")) + || !"INITIAL_BOOTSTRAP_INTENT".equals(text(control, "state")) + || !anchor.bootstrapOperationId().equals(uuid(control, "current_operation_id")) + || !anchor.controlEpoch().equals(integer(control, "control_epoch")) + || !anchor.operationFence().equals(integer(control, "current_operation_fence")) + || !anchor.coverageFence().equals(integer(control, "current_coverage_fence"))) { + throw conflict( + "Live admission control requires its exact immutable V1030 bootstrap provenance"); + } + Record anchorRow = + transaction.fetchOne( + "SELECT exact_anchor_bytes, exact_anchor_digest FROM " + + ANCHOR + + " WHERE issuer_id = ? FOR UPDATE", + ISSUER); + if (anchorRow == null + || !Arrays.equals(bytes(anchorRow, "exact_anchor_bytes"), anchor.exactAnchorBytes()) + || !anchor.exactAnchorDigest().equals(text(anchorRow, "exact_anchor_digest"))) { + throw conflict("Live admission control requires the exact installed anchor row"); + } + } + + private static void insertInitialOperation( + DSLContext transaction, CanonicalGameplayIssuerAdmissionControlValue value) { + int inserted = + transaction.execute( + "INSERT INTO " + + OPERATION + + " (operation_id, request_id, issuer_id, operation_kind, operation_state," + + " live_barrier_epoch, prior_live_barrier_epoch, bootstrap_operation_id," + + " bootstrap_request_id, bootstrap_control_epoch, anchor_exact_bytes," + + " anchor_exact_digest, account_issuer_auth_generation, account_checkpoint_bytes," + + " account_checkpoint_digest, account_source_event_bytes, account_source_event_digest," + + " stable_incarnation_bytes, stable_incarnation_digest, inventory_snapshot_revision," + + " cohort_row_count, cohort_digest, installed_at)" + + " VALUES (?, ?, ?, 'INITIAL_ANCHOR_INSTALL', 'OPEN', ?, NULL, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, CURRENT_TIMESTAMP)", + value.currentOperationId(), + value.bootstrapRequestId(), + value.issuerId(), + value.liveBarrierEpoch(), + value.bootstrapOperationId(), + value.bootstrapRequestId(), + value.bootstrapControlEpoch(), + value.anchorExactBytes(), + value.anchorExactDigest(), + value.accountIssuerAuthGeneration(), + value.accountCheckpointBytes(), + value.accountCheckpointDigest(), + value.accountSourceEventBytes(), + value.accountSourceEventDigest(), + value.stableIncarnationBytes(), + value.stableIncarnationDigest(), + value.inventorySnapshotRevision(), + value.cohortRowCount(), + value.cohortDigest()); + if (inserted != 1) throw conflict("Initial live issuer control operation did not persist"); + } + + private static void insertControl( + DSLContext transaction, CanonicalGameplayIssuerAdmissionControlValue value) { + int inserted = + transaction.execute( + "INSERT INTO " + + CONTROL + + " (issuer_id, state, live_barrier_epoch, current_operation_id, current_operation_kind," + + " bootstrap_operation_id, bootstrap_request_id, bootstrap_control_epoch," + + " anchor_exact_bytes, anchor_exact_digest, account_issuer_auth_generation," + + " account_checkpoint_bytes, account_checkpoint_digest, account_source_event_bytes," + + " account_source_event_digest, stable_incarnation_bytes, stable_incarnation_digest," + + " inventory_snapshot_revision, cohort_row_count, cohort_digest, control_exact_bytes," + + " control_exact_digest) VALUES (?, 'OPEN', ?, ?, 'INITIAL_ANCHOR_INSTALL', ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)", + value.issuerId(), + value.liveBarrierEpoch(), + value.currentOperationId(), + value.bootstrapOperationId(), + value.bootstrapRequestId(), + value.bootstrapControlEpoch(), + value.anchorExactBytes(), + value.anchorExactDigest(), + value.accountIssuerAuthGeneration(), + value.accountCheckpointBytes(), + value.accountCheckpointDigest(), + value.accountSourceEventBytes(), + value.accountSourceEventDigest(), + value.stableIncarnationBytes(), + value.stableIncarnationDigest(), + value.inventorySnapshotRevision(), + value.cohortRowCount(), + value.cohortDigest(), + value.exactBytes(), + value.exactDigest()); + if (inserted != 1) throw conflict("Initial live issuer admission control did not persist"); + } + + private static CanonicalGameplayIssuerAdmissionControlValue loadControl(Record row) { + byte[] exact = bytes(row, "control_exact_bytes"); + String digest = text(row, "control_exact_digest"); + if (!CanonicalGameplayIssuerAdmissionControlValue.sha256(exact).equals(digest)) { + throw conflict("Persisted issuer admission control digest differs from its exact bytes"); + } + CanonicalGameplayIssuerAdmissionControlValue value; + try { + value = CanonicalGameplayIssuerAdmissionControlValue.decode(exact); + } catch (RuntimeException malformed) { + throw conflict("Persisted issuer admission-control value is malformed"); + } + if (!value.issuerId().equals(text(row, "issuer_id")) + || !value.state().name().equals(text(row, "state")) + || !value.liveBarrierEpoch().equals(integer(row, "live_barrier_epoch")) + || !value.currentOperationId().equals(uuid(row, "current_operation_id")) + || !value.currentOperationKind().name().equals(text(row, "current_operation_kind")) + || !value.bootstrapOperationId().equals(uuid(row, "bootstrap_operation_id")) + || !value.bootstrapRequestId().equals(uuid(row, "bootstrap_request_id")) + || !value.bootstrapControlEpoch().equals(integer(row, "bootstrap_control_epoch")) + || !Arrays.equals(value.anchorExactBytes(), bytes(row, "anchor_exact_bytes")) + || !value.anchorExactDigest().equals(text(row, "anchor_exact_digest")) + || !value + .accountIssuerAuthGeneration() + .equals(integer(row, "account_issuer_auth_generation")) + || !Arrays.equals(value.accountCheckpointBytes(), bytes(row, "account_checkpoint_bytes")) + || !value.accountCheckpointDigest().equals(text(row, "account_checkpoint_digest")) + || !Arrays.equals( + value.accountSourceEventBytes(), nullableBytes(row, "account_source_event_bytes")) + || !Objects.equals( + value.accountSourceEventDigest(), nullableText(row, "account_source_event_digest")) + || !Arrays.equals(value.stableIncarnationBytes(), bytes(row, "stable_incarnation_bytes")) + || !value.stableIncarnationDigest().equals(text(row, "stable_incarnation_digest")) + || !value.inventorySnapshotRevision().equals(integer(row, "inventory_snapshot_revision")) + || value.cohortRowCount() != longInteger(row, "cohort_row_count") + || !value.cohortDigest().equals(text(row, "cohort_digest"))) { + throw conflict("Issuer admission-control columns differ from their exact typed value"); + } + return value; + } + + private static void requireExactAnchorAndCurrentSource( + CanonicalGameplayIssuerAdmissionControlValue value, + CanonicalGameplayIssuerInstalledAnchor anchor, + CanonicalGameplayIssuerBootstrapPartitionRedisOwner.CurrentIssuerState currentState) { + if (!value.bootstrapOperationId().equals(anchor.bootstrapOperationId()) + || !value.bootstrapRequestId().equals(anchor.bootstrapRequestId()) + || !value.bootstrapControlEpoch().equals(anchor.controlEpoch()) + || !Arrays.equals(value.anchorExactBytes(), anchor.exactAnchorBytes()) + || !value.anchorExactDigest().equals(anchor.exactAnchorDigest()) + || !value.matchesCurrentIssuerState(currentState)) { + throw conflict("Live issuer control no longer matches its exact anchor and current sources"); + } + } + + private static void requireCounterMatchesCurrent(DSLContext transaction, BigInteger liveEpoch) { + Record counter = + transaction.fetchOne( + "SELECT * FROM " + COUNTER + " WHERE issuer_id = ? FOR UPDATE", ISSUER); + if (counter == null || !integer(counter, "last_live_barrier_epoch").equals(liveEpoch)) { + throw conflict("Live issuer admission epoch differs from its positive owner counter"); + } + } + + private static void requireInitialOperationCurrent( + DSLContext transaction, CanonicalGameplayIssuerAdmissionControlValue value) { + Record operation = + transaction.fetchOne( + "SELECT * FROM " + OPERATION + " WHERE operation_id = ? FOR UPDATE", + value.currentOperationId()); + if (operation == null + || !ISSUER.equals(text(operation, "issuer_id")) + || !"INITIAL_ANCHOR_INSTALL".equals(text(operation, "operation_kind")) + || !"OPEN".equals(text(operation, "operation_state")) + || !value.liveBarrierEpoch().equals(integer(operation, "live_barrier_epoch")) + || !value.bootstrapRequestId().equals(uuid(operation, "request_id")) + || !value.bootstrapOperationId().equals(uuid(operation, "bootstrap_operation_id")) + || !value.bootstrapControlEpoch().equals(integer(operation, "bootstrap_control_epoch")) + || !Arrays.equals(value.anchorExactBytes(), bytes(operation, "anchor_exact_bytes")) + || !value.anchorExactDigest().equals(text(operation, "anchor_exact_digest")) + || !value + .accountIssuerAuthGeneration() + .equals(integer(operation, "account_issuer_auth_generation")) + || !Arrays.equals( + value.accountCheckpointBytes(), bytes(operation, "account_checkpoint_bytes")) + || !value.accountCheckpointDigest().equals(text(operation, "account_checkpoint_digest")) + || !Arrays.equals( + value.accountSourceEventBytes(), nullableBytes(operation, "account_source_event_bytes")) + || !Objects.equals( + value.accountSourceEventDigest(), + nullableText(operation, "account_source_event_digest")) + || !Arrays.equals( + value.stableIncarnationBytes(), bytes(operation, "stable_incarnation_bytes")) + || !value.stableIncarnationDigest().equals(text(operation, "stable_incarnation_digest")) + || !value + .inventorySnapshotRevision() + .equals(integer(operation, "inventory_snapshot_revision")) + || value.cohortRowCount() != longInteger(operation, "cohort_row_count") + || !value.cohortDigest().equals(text(operation, "cohort_digest"))) { + throw conflict("Live issuer control has no exact persisted initial-anchor operation"); + } + } + + private static BigInteger integer(Record row, String name) { + java.math.BigDecimal value = row.get(name, java.math.BigDecimal.class); + if (value == null) throw conflict("Persisted issuer admission field is missing: " + name); + try { + return value.toBigIntegerExact(); + } catch (ArithmeticException malformed) { + throw conflict("Persisted issuer admission integer is malformed: " + name); + } + } + + private static long longInteger(Record row, String name) { + Long value = row.get(name, Long.class); + if (value == null || value < 0) { + throw conflict("Persisted issuer admission count is missing or negative: " + name); + } + return value; + } + + private static java.util.UUID uuid(Record row, String name) { + java.util.UUID value = row.get(name, java.util.UUID.class); + if (value == null) throw conflict("Persisted issuer admission UUID is missing: " + name); + return value; + } + + private static String text(Record row, String name) { + String value = row.get(name, String.class); + if (value == null) throw conflict("Persisted issuer admission text is missing: " + name); + return value; + } + + private static byte[] bytes(Record row, String name) { + byte[] value = row.get(name, byte[].class); + if (value == null) throw conflict("Persisted issuer admission bytes are missing: " + name); + return value; + } + + private static byte[] nullableBytes(Record row, String name) { + return row.get(name, byte[].class); + } + + private static String nullableText(Record row, String name) { + return row.get(name, String.class); + } + + private void requireNoAmbientTransaction() { + if (TransactionSynchronizationManager.isActualTransactionActive() + || TransactionSynchronizationManager.isSynchronizationActive()) { + throw conflict("Issuer admission-control owner cannot join an ambient transaction"); + } + try { + dsl.connectionResult( + connection -> { + if (!connection.getAutoCommit()) { + throw conflict("Issuer admission-control owner cannot join a jOOQ transaction"); + } + return Boolean.TRUE; + }); + } catch (RuntimeException failure) { + if (failure instanceof CanonicalGameplayBindingInventoryConflictException) throw failure; + throw new CanonicalGameplayBindingInventoryConflictException( + "Issuer admission-control SQL connection state is unavailable", failure); + } + } + + private static CanonicalGameplayBindingInventoryConflictException conflict(String message) { + return new CanonicalGameplayBindingInventoryConflictException(message); + } +} diff --git a/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/repository/CanonicalGameplayIssuerAdmissionControlValue.java b/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/repository/CanonicalGameplayIssuerAdmissionControlValue.java new file mode 100644 index 0000000000..90a2d3b555 --- /dev/null +++ b/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/repository/CanonicalGameplayIssuerAdmissionControlValue.java @@ -0,0 +1,553 @@ +package net.firedevops.firemud.gamesession.repository; + +import java.io.ByteArrayInputStream; +import java.io.ByteArrayOutputStream; +import java.io.DataInputStream; +import java.io.DataOutputStream; +import java.io.IOException; +import java.math.BigInteger; +import java.nio.ByteBuffer; +import java.nio.charset.CharacterCodingException; +import java.nio.charset.CodingErrorAction; +import java.nio.charset.StandardCharsets; +import java.security.MessageDigest; +import java.util.Arrays; +import java.util.HexFormat; +import java.util.Objects; +import java.util.UUID; +import net.firedevops.firemud.common.security.GameSessionAccountDelegationProfile; + +/** Exact live issuer admission-control value, in its own epoch domain from the V1030 layout. */ +final class CanonicalGameplayIssuerAdmissionControlValue { + static final String SCHEMA = "gs_issuer_admission_control/v1"; + static final int MAX_BYTES = 512 * 1024; + private static final String ENCODING = "canonical-live-issuer-admission-control/v1"; + + enum State { + OPEN, + CUTOFF_PENDING, + INSTALLED + } + + enum OperationKind { + INITIAL_ANCHOR_INSTALL, + CUTOFF + } + + private final String issuerId; + private final State state; + private final BigInteger liveBarrierEpoch; + private final UUID currentOperationId; + private final OperationKind currentOperationKind; + private final UUID bootstrapOperationId; + private final UUID bootstrapRequestId; + private final BigInteger bootstrapControlEpoch; + private final byte[] anchorExactBytes; + private final String anchorExactDigest; + private final BigInteger accountIssuerAuthGeneration; + private final byte[] accountCheckpointBytes; + private final String accountCheckpointDigest; + private final byte[] accountSourceEventBytes; + private final String accountSourceEventDigest; + private final byte[] stableIncarnationBytes; + private final String stableIncarnationDigest; + private final BigInteger inventorySnapshotRevision; + private final long cohortRowCount; + private final String cohortDigest; + private final byte[] exactBytes; + private final String exactDigest; + + private CanonicalGameplayIssuerAdmissionControlValue( + String issuerId, + State state, + BigInteger liveBarrierEpoch, + UUID currentOperationId, + OperationKind currentOperationKind, + UUID bootstrapOperationId, + UUID bootstrapRequestId, + BigInteger bootstrapControlEpoch, + byte[] anchorExactBytes, + String anchorExactDigest, + BigInteger accountIssuerAuthGeneration, + byte[] accountCheckpointBytes, + String accountCheckpointDigest, + byte[] accountSourceEventBytes, + String accountSourceEventDigest, + byte[] stableIncarnationBytes, + String stableIncarnationDigest, + BigInteger inventorySnapshotRevision, + long cohortRowCount, + String cohortDigest) { + this.issuerId = requireIssuer(issuerId); + this.state = Objects.requireNonNull(state, "state"); + this.liveBarrierEpoch = requirePositive(liveBarrierEpoch, "liveBarrierEpoch"); + this.currentOperationId = requireNonNil(currentOperationId, "currentOperationId"); + this.currentOperationKind = + Objects.requireNonNull(currentOperationKind, "currentOperationKind"); + this.bootstrapOperationId = requireNonNil(bootstrapOperationId, "bootstrapOperationId"); + this.bootstrapRequestId = requireNonNil(bootstrapRequestId, "bootstrapRequestId"); + this.bootstrapControlEpoch = requirePositive(bootstrapControlEpoch, "bootstrapControlEpoch"); + this.anchorExactBytes = nonEmpty(anchorExactBytes, "anchorExactBytes"); + this.anchorExactDigest = requireDigest(anchorExactDigest, "anchorExactDigest"); + requireDigestMatches(this.anchorExactBytes, this.anchorExactDigest, "installed anchor"); + this.accountIssuerAuthGeneration = + requirePositive(accountIssuerAuthGeneration, "accountIssuerAuthGeneration"); + this.accountCheckpointBytes = nonEmpty(accountCheckpointBytes, "accountCheckpointBytes"); + this.accountCheckpointDigest = + requireDigest(accountCheckpointDigest, "accountCheckpointDigest"); + requireDigestMatches( + this.accountCheckpointBytes, this.accountCheckpointDigest, "Account checkpoint"); + if ((accountSourceEventBytes == null) != (accountSourceEventDigest == null)) { + throw new IllegalArgumentException("Account source event bytes and digest must be paired"); + } + this.accountSourceEventBytes = + accountSourceEventBytes == null + ? null + : nonEmpty(accountSourceEventBytes, "accountSourceEventBytes"); + this.accountSourceEventDigest = + accountSourceEventDigest == null + ? null + : requireDigest(accountSourceEventDigest, "accountSourceEventDigest"); + if (this.accountSourceEventBytes != null) { + requireDigestMatches( + this.accountSourceEventBytes, this.accountSourceEventDigest, "Account source event"); + } + this.stableIncarnationBytes = nonEmpty(stableIncarnationBytes, "stableIncarnationBytes"); + this.stableIncarnationDigest = + requireDigest(stableIncarnationDigest, "stableIncarnationDigest"); + requireDigestMatches( + this.stableIncarnationBytes, this.stableIncarnationDigest, "stable incarnation"); + this.inventorySnapshotRevision = + requirePositive(inventorySnapshotRevision, "inventorySnapshotRevision"); + if (cohortRowCount < 0) + throw new IllegalArgumentException("cohortRowCount must not be negative"); + this.cohortRowCount = cohortRowCount; + this.cohortDigest = requireDigest(cohortDigest, "cohortDigest"); + if ((state == State.OPEN) != (currentOperationKind == OperationKind.INITIAL_ANCHOR_INSTALL)) { + throw new IllegalArgumentException("Only the initial-anchor install may establish OPEN"); + } + this.exactBytes = encode(); + if (exactBytes.length > MAX_BYTES) { + throw new IllegalArgumentException("Issuer admission-control value exceeds its bound"); + } + this.exactDigest = sha256(exactBytes); + } + + static CanonicalGameplayIssuerAdmissionControlValue initialOpen( + CanonicalGameplayIssuerInstalledAnchor anchor, + CanonicalGameplayIssuerBootstrapPartitionRedisOwner.CurrentIssuerState current, + BigInteger liveBarrierEpoch, + long cohortRowCount, + String cohortDigest) { + Objects.requireNonNull(anchor, "anchor"); + Objects.requireNonNull(current, "current"); + var checkpoint = current.accountCheckpoint(); + byte[] anchorBytes = anchor.exactAnchorBytes(); + if (!anchor.issuerId().equals(checkpoint.issuerId()) + || !anchor.issuerAuthGeneration().equals(checkpoint.issuerAuthGeneration()) + || !Arrays.equals(anchor.sourceCheckpointBytes(), checkpoint.exactCheckpointBytes()) + || !Objects.equals(anchor.sourceEventDigest(), checkpoint.latestIssuerEventDigest()) + || !Arrays.equals(anchor.sourceEventBytes(), checkpoint.latestIssuerEventBytes()) + || !Arrays.equals( + anchor.incarnationBytes(), + CanonicalGameplayIssuerInstalledAnchor.encodeIncarnation(current.incarnation()))) { + throw new IllegalArgumentException( + "Live issuer control requires the exact current anchor sources"); + } + return new CanonicalGameplayIssuerAdmissionControlValue( + anchor.issuerId(), + State.OPEN, + liveBarrierEpoch, + anchor.bootstrapOperationId(), + OperationKind.INITIAL_ANCHOR_INSTALL, + anchor.bootstrapOperationId(), + anchor.bootstrapRequestId(), + anchor.controlEpoch(), + anchorBytes, + sha256(anchorBytes), + checkpoint.issuerAuthGeneration(), + checkpoint.exactCheckpointBytes(), + checkpoint.checkpointDigest(), + checkpoint.latestIssuerEventBytes(), + checkpoint.latestIssuerEventDigest(), + anchor.incarnationBytes(), + anchor.incarnationDigest(), + anchor.issuerInventorySnapshotRevision(), + cohortRowCount, + cohortDigest); + } + + CanonicalGameplayIssuerAdmissionControlValue cutoffPending( + UUID cutoffOperationId, + BigInteger targetLiveBarrierEpoch, + BigInteger snapshotRevision, + long frozenCohortRowCount, + String frozenCohortDigest) { + if (state != State.OPEN + || currentOperationKind != OperationKind.INITIAL_ANCHOR_INSTALL + || targetLiveBarrierEpoch.compareTo(liveBarrierEpoch) <= 0) { + throw new IllegalArgumentException("Issuer cutoff must advance the live admission epoch"); + } + return new CanonicalGameplayIssuerAdmissionControlValue( + issuerId, + State.CUTOFF_PENDING, + targetLiveBarrierEpoch, + requireNonNil(cutoffOperationId, "cutoffOperationId"), + OperationKind.CUTOFF, + bootstrapOperationId, + bootstrapRequestId, + bootstrapControlEpoch, + anchorExactBytes, + anchorExactDigest, + accountIssuerAuthGeneration, + accountCheckpointBytes, + accountCheckpointDigest, + accountSourceEventBytes, + accountSourceEventDigest, + stableIncarnationBytes, + stableIncarnationDigest, + snapshotRevision, + frozenCohortRowCount, + frozenCohortDigest); + } + + CanonicalGameplayIssuerAdmissionControlValue installed() { + if (state != State.CUTOFF_PENDING || currentOperationKind != OperationKind.CUTOFF) { + throw new IllegalArgumentException("Only a pending cutoff can become installed"); + } + return new CanonicalGameplayIssuerAdmissionControlValue( + issuerId, + State.INSTALLED, + liveBarrierEpoch, + currentOperationId, + currentOperationKind, + bootstrapOperationId, + bootstrapRequestId, + bootstrapControlEpoch, + anchorExactBytes, + anchorExactDigest, + accountIssuerAuthGeneration, + accountCheckpointBytes, + accountCheckpointDigest, + accountSourceEventBytes, + accountSourceEventDigest, + stableIncarnationBytes, + stableIncarnationDigest, + inventorySnapshotRevision, + cohortRowCount, + cohortDigest); + } + + static CanonicalGameplayIssuerAdmissionControlValue decode(byte[] bytes) { + if (bytes == null || bytes.length == 0 || bytes.length > MAX_BYTES) throw malformed(); + try (DataInputStream in = new DataInputStream(new ByteArrayInputStream(bytes))) { + if (!ENCODING.equals(readText(in))) throw malformed(); + CanonicalGameplayIssuerAdmissionControlValue result = + new CanonicalGameplayIssuerAdmissionControlValue( + readText(in), + State.valueOf(readText(in)), + readPositive(in), + readUuid(in), + OperationKind.valueOf(readText(in)), + readUuid(in), + readUuid(in), + readPositive(in), + readBytes(in), + readText(in), + readPositive(in), + readBytes(in), + readText(in), + readNullableBytes(in), + readNullableText(in), + readBytes(in), + readText(in), + readPositive(in), + in.readLong(), + readText(in)); + if (in.available() != 0 || !Arrays.equals(bytes, result.exactBytes())) throw malformed(); + return result; + } catch (IOException | RuntimeException invalid) { + throw malformed(); + } + } + + private byte[] encode() { + return encode( + out -> { + writeText(out, ENCODING); + writeText(out, issuerId); + writeText(out, state.name()); + writeBigInteger(out, liveBarrierEpoch); + writeUuid(out, currentOperationId); + writeText(out, currentOperationKind.name()); + writeUuid(out, bootstrapOperationId); + writeUuid(out, bootstrapRequestId); + writeBigInteger(out, bootstrapControlEpoch); + writeBytes(out, anchorExactBytes); + writeText(out, anchorExactDigest); + writeBigInteger(out, accountIssuerAuthGeneration); + writeBytes(out, accountCheckpointBytes); + writeText(out, accountCheckpointDigest); + writeNullableBytes(out, accountSourceEventBytes); + writeNullableText(out, accountSourceEventDigest); + writeBytes(out, stableIncarnationBytes); + writeText(out, stableIncarnationDigest); + writeBigInteger(out, inventorySnapshotRevision); + out.writeLong(cohortRowCount); + writeText(out, cohortDigest); + }); + } + + boolean matchesCurrentIssuerState( + CanonicalGameplayIssuerBootstrapPartitionRedisOwner.CurrentIssuerState current) { + Objects.requireNonNull(current, "current"); + var checkpoint = current.accountCheckpoint(); + return issuerId.equals(checkpoint.issuerId()) + && accountIssuerAuthGeneration.equals(checkpoint.issuerAuthGeneration()) + && Arrays.equals(accountCheckpointBytes, checkpoint.exactCheckpointBytes()) + && accountCheckpointDigest.equals(checkpoint.checkpointDigest()) + && Arrays.equals(accountSourceEventBytes, checkpoint.latestIssuerEventBytes()) + && Objects.equals(accountSourceEventDigest, checkpoint.latestIssuerEventDigest()) + && Arrays.equals( + stableIncarnationBytes, + CanonicalGameplayIssuerInstalledAnchor.encodeIncarnation(current.incarnation())); + } + + String issuerId() { + return issuerId; + } + + State state() { + return state; + } + + BigInteger liveBarrierEpoch() { + return liveBarrierEpoch; + } + + UUID currentOperationId() { + return currentOperationId; + } + + OperationKind currentOperationKind() { + return currentOperationKind; + } + + UUID bootstrapOperationId() { + return bootstrapOperationId; + } + + UUID bootstrapRequestId() { + return bootstrapRequestId; + } + + BigInteger bootstrapControlEpoch() { + return bootstrapControlEpoch; + } + + byte[] anchorExactBytes() { + return anchorExactBytes.clone(); + } + + String anchorExactDigest() { + return anchorExactDigest; + } + + BigInteger accountIssuerAuthGeneration() { + return accountIssuerAuthGeneration; + } + + byte[] accountCheckpointBytes() { + return accountCheckpointBytes.clone(); + } + + String accountCheckpointDigest() { + return accountCheckpointDigest; + } + + byte[] accountSourceEventBytes() { + return accountSourceEventBytes == null ? null : accountSourceEventBytes.clone(); + } + + String accountSourceEventDigest() { + return accountSourceEventDigest; + } + + byte[] stableIncarnationBytes() { + return stableIncarnationBytes.clone(); + } + + String stableIncarnationDigest() { + return stableIncarnationDigest; + } + + BigInteger inventorySnapshotRevision() { + return inventorySnapshotRevision; + } + + long cohortRowCount() { + return cohortRowCount; + } + + String cohortDigest() { + return cohortDigest; + } + + byte[] exactBytes() { + return exactBytes.clone(); + } + + String exactDigest() { + return exactDigest; + } + + static String sha256(byte[] bytes) { + try { + return "sha256:" + + HexFormat.of().formatHex(MessageDigest.getInstance("SHA-256").digest(bytes)); + } catch (Exception failure) { + throw new IllegalStateException( + "Could not digest exact issuer admission-control bytes", failure); + } + } + + private static byte[] encode(Writer writer) { + try { + ByteArrayOutputStream bytes = new ByteArrayOutputStream(); + try (DataOutputStream out = new DataOutputStream(bytes)) { + writer.write(out); + } + return bytes.toByteArray(); + } catch (IOException impossible) { + throw new IllegalStateException( + "Could not encode issuer admission-control bytes", impossible); + } + } + + private static void writeText(DataOutputStream out, String value) throws IOException { + byte[] bytes = Objects.requireNonNull(value, "text").getBytes(StandardCharsets.UTF_8); + writeBytes(out, bytes); + } + + private static void writeBytes(DataOutputStream out, byte[] value) throws IOException { + if (value == null || value.length == 0 || value.length > MAX_BYTES) { + throw new IllegalArgumentException("Control bytes are outside their bound"); + } + out.writeInt(value.length); + out.write(value); + } + + private static void writeNullableBytes(DataOutputStream out, byte[] value) throws IOException { + out.writeBoolean(value != null); + if (value != null) writeBytes(out, value); + } + + private static void writeNullableText(DataOutputStream out, String value) throws IOException { + out.writeBoolean(value != null); + if (value != null) writeText(out, value); + } + + private static void writeUuid(DataOutputStream out, UUID value) throws IOException { + writeText(out, requireNonNil(value, "uuid").toString()); + } + + private static void writeBigInteger(DataOutputStream out, BigInteger value) throws IOException { + writeText(out, requirePositive(value, "counter").toString()); + } + + private static String readText(DataInputStream in) throws IOException { + byte[] bytes = readBytes(in); + try { + return StandardCharsets.UTF_8 + .newDecoder() + .onMalformedInput(CodingErrorAction.REPORT) + .onUnmappableCharacter(CodingErrorAction.REPORT) + .decode(ByteBuffer.wrap(bytes)) + .toString(); + } catch (CharacterCodingException invalid) { + throw malformed(); + } + } + + private static byte[] readBytes(DataInputStream in) throws IOException { + int length = in.readInt(); + if (length < 1 || length > MAX_BYTES || length > in.available()) throw malformed(); + return in.readNBytes(length); + } + + private static byte[] readNullableBytes(DataInputStream in) throws IOException { + return in.readBoolean() ? readBytes(in) : null; + } + + private static String readNullableText(DataInputStream in) throws IOException { + return in.readBoolean() ? readText(in) : null; + } + + private static UUID readUuid(DataInputStream in) throws IOException { + String value = readText(in); + UUID uuid; + try { + uuid = UUID.fromString(value); + } catch (RuntimeException malformed) { + throw malformed(); + } + if (!uuid.toString().equals(value) || uuid.equals(new UUID(0L, 0L))) throw malformed(); + return uuid; + } + + private static BigInteger readPositive(DataInputStream in) throws IOException { + String value = readText(in); + if (!value.matches("[1-9][0-9]{0,255}")) throw malformed(); + return new BigInteger(value); + } + + private static String requireIssuer(String issuerId) { + if (!GameSessionAccountDelegationProfile.ISSUER.equals(issuerId)) { + throw new IllegalArgumentException("Live issuer control requires the exact Account issuer"); + } + return issuerId; + } + + private static UUID requireNonNil(UUID value, String name) { + Objects.requireNonNull(value, name); + if (value.equals(new UUID(0L, 0L))) + throw new IllegalArgumentException(name + " must not be nil"); + return value; + } + + private static BigInteger requirePositive(BigInteger value, String name) { + Objects.requireNonNull(value, name); + if (value.signum() <= 0 || value.toString().length() > 256) { + throw new IllegalArgumentException(name + " must be a bounded positive integer"); + } + return value; + } + + private static byte[] nonEmpty(byte[] value, String name) { + Objects.requireNonNull(value, name); + if (value.length == 0 || value.length > MAX_BYTES) { + throw new IllegalArgumentException(name + " is outside its byte bound"); + } + return value.clone(); + } + + private static String requireDigest(String digest, String name) { + Objects.requireNonNull(digest, name); + if (!digest.matches("sha256:[0-9a-f]{64}")) + throw new IllegalArgumentException(name + " is malformed"); + return digest; + } + + private static void requireDigestMatches(byte[] bytes, String digest, String name) { + if (!sha256(bytes).equals(digest)) throw new IllegalArgumentException(name + " digest differs"); + } + + private static IllegalArgumentException malformed() { + return new IllegalArgumentException("Issuer admission-control value is malformed"); + } + + @FunctionalInterface + private interface Writer { + void write(DataOutputStream out) throws IOException; + } +} diff --git a/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/repository/CanonicalGameplayIssuerBindingLocalAcknowledgement.java b/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/repository/CanonicalGameplayIssuerBindingLocalAcknowledgement.java new file mode 100644 index 0000000000..74beb64f23 --- /dev/null +++ b/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/repository/CanonicalGameplayIssuerBindingLocalAcknowledgement.java @@ -0,0 +1,463 @@ +package net.firedevops.firemud.gamesession.repository; + +import java.math.BigInteger; +import java.util.Arrays; +import java.util.Objects; +import java.util.UUID; +import net.firedevops.firemud.common.security.GameSessionAccountDelegationProfile; +import net.firedevops.firemud.gamesession.binding.CanonicalIssuerPartitionReservation; + +/** + * Durable, versioned proof for one ordinary NEW issuer member and its reservation readback. Its + * positive transition evidence generation is issued only with the accepted SQL receipt and is + * separate from both the preparatory member-operation generation and the anchor's global coverage + * generation. This binding-local evidence does not establish issuer-wide coverage, barrier OPEN, or + * tenant admission. + */ +final class CanonicalGameplayIssuerBindingLocalAcknowledgement { + static final int SCHEMA_VERSION = 1; + static final String SCOPE = "ISSUER_BINDING_LOCAL"; + static final String GLOBAL_COVERAGE_GENERATION = "NOT_YET_ISSUED"; + + private final Evidence evidence; + private final byte[] exactBytes; + private final String digest; + + private CanonicalGameplayIssuerBindingLocalAcknowledgement(Evidence evidence, byte[] exactBytes) { + this.evidence = Objects.requireNonNull(evidence, "evidence"); + this.exactBytes = Objects.requireNonNull(exactBytes, "exactBytes").clone(); + this.digest = CanonicalGameplayIssuerMemberV2Codec.sha256(this.exactBytes); + if (!Arrays.equals( + this.exactBytes, + CanonicalGameplayIssuerBindingLocalAcknowledgementCodec.encode(evidence))) { + throw new IllegalArgumentException( + "Issuer binding-local acknowledgement bytes are not canonical"); + } + } + + static CanonicalGameplayIssuerBindingLocalAcknowledgement create(Evidence evidence) { + return new CanonicalGameplayIssuerBindingLocalAcknowledgement( + evidence, CanonicalGameplayIssuerBindingLocalAcknowledgementCodec.encode(evidence)); + } + + static CanonicalGameplayIssuerBindingLocalAcknowledgement decode(byte[] exactBytes) { + Evidence evidence = CanonicalGameplayIssuerBindingLocalAcknowledgementCodec.decode(exactBytes); + return new CanonicalGameplayIssuerBindingLocalAcknowledgement(evidence, exactBytes); + } + + Evidence evidence() { + return evidence; + } + + UUID operationId() { + return evidence.operationId(); + } + + UUID requestId() { + return evidence.requestId(); + } + + UUID transitionId() { + return evidence.transitionId(); + } + + byte[] exactBytes() { + return exactBytes.clone(); + } + + String digest() { + return digest; + } + + record Evidence( + UUID operationId, + BigInteger issuerBindingLocalAcknowledgementGeneration, + UUID requestId, + UUID transitionId, + UUID candidateAccountIndexFence, + String issuerId, + byte[] bindingRef, + BigInteger bindingGeneration, + byte[] memberValueBytes, + String memberValueDigest, + Reservation reservation, + Anchor anchor, + MemberOperation memberOperation, + CurrentSource currentSource, + PhysicalReadback physicalReadback, + Capacity capacity, + String sqlCurrentnessDigest) { + Evidence { + requireNonNil(operationId, "operationId"); + issuerBindingLocalAcknowledgementGeneration = + positive( + issuerBindingLocalAcknowledgementGeneration, + "issuerBindingLocalAcknowledgementGeneration"); + requireNonNil(requestId, "requestId"); + requireNonNil(transitionId, "transitionId"); + requireNonNil(candidateAccountIndexFence, "candidateAccountIndexFence"); + if (requestId.equals(transitionId)) { + throw new IllegalArgumentException("Request and transition identity must be distinct"); + } + if (!GameSessionAccountDelegationProfile.ISSUER.equals(issuerId)) { + throw new IllegalArgumentException("Issuer is not the exact Account environment issuer"); + } + bindingRef = nonEmpty(bindingRef, "bindingRef"); + bindingGeneration = positive(bindingGeneration, "bindingGeneration"); + memberValueBytes = nonEmpty(memberValueBytes, "memberValueBytes"); + memberValueDigest = digest(memberValueDigest, "memberValueDigest"); + reservation = Objects.requireNonNull(reservation, "reservation"); + anchor = Objects.requireNonNull(anchor, "anchor"); + memberOperation = Objects.requireNonNull(memberOperation, "memberOperation"); + currentSource = Objects.requireNonNull(currentSource, "currentSource"); + physicalReadback = Objects.requireNonNull(physicalReadback, "physicalReadback"); + capacity = Objects.requireNonNull(capacity, "capacity"); + sqlCurrentnessDigest = digest(sqlCurrentnessDigest, "sqlCurrentnessDigest"); + + CanonicalGameplayIssuerMemberV2Value member = + CanonicalGameplayIssuerMemberV2Codec.decode(memberValueBytes); + if (!memberValueDigest.equals(CanonicalGameplayIssuerMemberV2Codec.sha256(memberValueBytes)) + || !member.owner().issuerId().equals(issuerId) + || !Arrays.equals(member.owner().bindingRef().bytes(), bindingRef) + || !member.bindingGeneration().equals(bindingGeneration) + || !reservation.matches(member) + || !anchor.matches(member) + || !memberOperation.matches(member) + || !currentSource.matches(member) + || !physicalReadback.matches(memberValueBytes, bindingRef, reservation.reservationId()) + || !capacity.matches(member, physicalReadback)) { + throw new IllegalArgumentException( + "Issuer binding-local acknowledgement differs from its exact member and proof tuples"); + } + } + + @Override + public byte[] bindingRef() { + return bindingRef.clone(); + } + + @Override + public byte[] memberValueBytes() { + return memberValueBytes.clone(); + } + } + + record Reservation( + UUID reservationId, + UUID transitionId, + UUID reservationFence, + BigInteger partitionId, + String lifecycle, + UUID issuerCoverageOperationId, + BigInteger issuerCoverageOperationFence, + BigInteger coverageFence, + BigInteger inventorySnapshotRevision, + BigInteger inventoryRevision) { + Reservation { + requireNonNil(reservationId, "reservationId"); + requireNonNil(transitionId, "reservation transitionId"); + requireNonNil(reservationFence, "reservationFence"); + partitionId = nonNegative(partitionId, "partitionId"); + if (!CanonicalIssuerPartitionReservation.Lifecycle.RESERVED.name().equals(lifecycle)) { + throw new IllegalArgumentException( + "An issuer binding-local acknowledgement requires RESERVED"); + } + requireNonNil(issuerCoverageOperationId, "original issuerCoverageOperationId"); + issuerCoverageOperationFence = + positive(issuerCoverageOperationFence, "original operationFence"); + coverageFence = positive(coverageFence, "original coverageFence"); + inventorySnapshotRevision = + positive(inventorySnapshotRevision, "original inventorySnapshotRevision"); + inventoryRevision = positive(inventoryRevision, "local inventoryRevision"); + } + + private boolean matches(CanonicalGameplayIssuerMemberV2Value member) { + var value = member.reservation(); + return reservationId.equals(value.reservationId()) + && transitionId.equals(value.transitionId()) + && reservationFence.equals(value.reservationFence()) + && partitionId.equals(value.partitionId()) + && lifecycle.equals(value.lifecycle().name()) + && issuerCoverageOperationId.equals(value.issuerCoverageOperationId()) + && issuerCoverageOperationFence.equals(value.issuerCoverageOperationFence()) + && coverageFence.equals(value.coverageFence()) + && inventorySnapshotRevision.equals(value.inventorySnapshotRevision()) + && inventoryRevision.equals(value.inventoryRevision()); + } + } + + record Anchor( + UUID bootstrapOperationId, + UUID issuerCoverageOperationId, + BigInteger operationFence, + BigInteger coverageFence, + BigInteger inventorySnapshotRevision, + BigInteger globalCoverageGeneration, + BigInteger controlEpoch, + BigInteger layoutVersion, + BigInteger partitionCount, + BigInteger partitionCapacity, + String mappingIdentity, + byte[] layoutDescriptorBytes, + String layoutDescriptorDigest, + byte[] exactBytes, + String exactDigest) { + Anchor { + requireNonNil(bootstrapOperationId, "bootstrapOperationId"); + requireNonNil(issuerCoverageOperationId, "anchor issuerCoverageOperationId"); + operationFence = positive(operationFence, "anchor operationFence"); + coverageFence = positive(coverageFence, "anchor coverageFence"); + inventorySnapshotRevision = + positive(inventorySnapshotRevision, "anchor inventorySnapshotRevision"); + globalCoverageGeneration = + positive(globalCoverageGeneration, "anchor globalCoverageGeneration"); + controlEpoch = positive(controlEpoch, "issuerControlEpoch"); + layoutVersion = positive(layoutVersion, "layoutVersion"); + partitionCount = positive(partitionCount, "partitionCount"); + partitionCapacity = positive(partitionCapacity, "partitionCapacity"); + if (operationFence.equals(coverageFence) || !operationFence.equals(controlEpoch)) { + throw new IllegalArgumentException("Installed issuer control tuple is not exact"); + } + if (!bootstrapOperationId.equals(issuerCoverageOperationId)) { + throw new IllegalArgumentException("Installed anchor differs from its bootstrap operation"); + } + if (!CanonicalGameplayIssuerLayoutBootstrapIntent.MAPPING_IDENTITY.equals(mappingIdentity)) { + throw new IllegalArgumentException("Issuer mapping identity is unsupported"); + } + layoutDescriptorBytes = nonEmpty(layoutDescriptorBytes, "layoutDescriptorBytes"); + layoutDescriptorDigest = digest(layoutDescriptorDigest, "layoutDescriptorDigest"); + exactBytes = nonEmpty(exactBytes, "exactAnchorBytes"); + exactDigest = digest(exactDigest, "exactAnchorDigest"); + requireMatches(layoutDescriptorBytes, layoutDescriptorDigest, "layout descriptor"); + requireMatches(exactBytes, exactDigest, "installed anchor"); + } + + @Override + public byte[] layoutDescriptorBytes() { + return layoutDescriptorBytes.clone(); + } + + @Override + public byte[] exactBytes() { + return exactBytes.clone(); + } + + private boolean matches(CanonicalGameplayIssuerMemberV2Value member) { + var value = member.anchor(); + return issuerCoverageOperationId.equals(value.issuerCoverageOperationId()) + && operationFence.equals(value.operationFence()) + && coverageFence.equals(value.coverageFence()) + && inventorySnapshotRevision.equals(value.issuerInventorySnapshotRevision()) + && controlEpoch.equals(member.issuerControlEpoch()) + && layoutVersion.equals(member.layoutDescriptor().layoutVersion()) + && partitionCount.equals(member.layoutDescriptor().partitionCount()) + && partitionCapacity.equals(member.layoutDescriptor().partitionCapacity()) + && mappingIdentity.equals(member.layoutDescriptor().mappingIdentity()) + && Arrays.equals(layoutDescriptorBytes, member.layoutDescriptor().exactDescriptorBytes()); + } + } + + record MemberOperation(UUID operationId, BigInteger operationFence, BigInteger generation) { + MemberOperation { + requireNonNil(operationId, "member operationId"); + operationFence = positive(operationFence, "member operationFence"); + generation = positive(generation, "member operation generation"); + } + + private boolean matches(CanonicalGameplayIssuerMemberV2Value member) { + var value = member.memberOperation(); + return operationId.equals(value.operationId()) + && operationFence.equals(value.operationFence()) + && generation.equals(value.coverageGeneration()); + } + } + + record CurrentSource( + BigInteger issuerAuthGeneration, + byte[] checkpointBytes, + String checkpointDigest, + byte[] eventBytes, + String eventDigest, + byte[] incarnationBytes, + String incarnationDigest) { + CurrentSource { + issuerAuthGeneration = positive(issuerAuthGeneration, "issuerAuthGeneration"); + checkpointBytes = nonEmpty(checkpointBytes, "current source checkpoint bytes"); + checkpointDigest = digest(checkpointDigest, "current source checkpoint digest"); + eventBytes = eventBytes == null ? null : nonEmpty(eventBytes, "current source event bytes"); + eventDigest = eventDigest == null ? null : digest(eventDigest, "current source event digest"); + if ((eventBytes == null) != (eventDigest == null)) { + throw new IllegalArgumentException( + "Current issuer source event bytes and digest must be paired"); + } + incarnationBytes = nonEmpty(incarnationBytes, "current stable incarnation bytes"); + incarnationDigest = digest(incarnationDigest, "current stable incarnation digest"); + requireMatches(checkpointBytes, checkpointDigest, "current source checkpoint"); + if (eventBytes != null) requireMatches(eventBytes, eventDigest, "current source event"); + requireMatches(incarnationBytes, incarnationDigest, "current stable incarnation"); + } + + @Override + public byte[] checkpointBytes() { + return checkpointBytes.clone(); + } + + @Override + public byte[] eventBytes() { + return eventBytes == null ? null : eventBytes.clone(); + } + + @Override + public byte[] incarnationBytes() { + return incarnationBytes.clone(); + } + + private boolean matches(CanonicalGameplayIssuerMemberV2Value member) { + var source = member.sourceCheckpoint(); + return issuerAuthGeneration.equals(member.owner().issuerAuthGeneration()) + && Arrays.equals(checkpointBytes, source.exactCheckpointBytes()) + && checkpointDigest.equals(source.checkpointDigest()) + && Arrays.equals(eventBytes, source.latestIssuerEventBytes()) + && Objects.equals(eventDigest, source.latestIssuerEventDigest()) + && Arrays.equals( + incarnationBytes, + CanonicalGameplayIssuerInstalledAnchor.encodeIncarnation(member.incarnation())); + } + } + + record PhysicalReadback( + byte[] bindingValueBytes, + String bindingValueDigest, + byte[] capacityValueBytes, + String capacityValueDigest, + String partitionFieldSetDigest, + int scriptOutcome, + int fieldCount, + int reservationCount, + int bindingCount, + int countedCapacity) { + PhysicalReadback { + bindingValueBytes = nonEmpty(bindingValueBytes, "physical binding readback"); + bindingValueDigest = digest(bindingValueDigest, "physical binding readback digest"); + capacityValueBytes = nonEmpty(capacityValueBytes, "physical capacity readback"); + capacityValueDigest = digest(capacityValueDigest, "physical capacity readback digest"); + partitionFieldSetDigest = digest(partitionFieldSetDigest, "physical field-set digest"); + if (scriptOutcome < 1 || scriptOutcome > 3) { + throw new IllegalArgumentException("Physical issuer script outcome is unsupported"); + } + if (fieldCount < 1 || reservationCount < 1 || bindingCount < 1 || countedCapacity < 1) { + throw new IllegalArgumentException("Physical issuer readback counts must be positive"); + } + if (fieldCount != 2 + reservationCount + bindingCount || bindingCount > reservationCount) { + throw new IllegalArgumentException("Physical issuer field counts are inconsistent"); + } + requireMatches(bindingValueBytes, bindingValueDigest, "physical binding value"); + requireMatches(capacityValueBytes, capacityValueDigest, "physical capacity value"); + if (!Arrays.equals(bindingValueBytes, capacityValueBytes)) { + throw new IllegalArgumentException("Binding and reservation readbacks differ"); + } + } + + @Override + public byte[] bindingValueBytes() { + return bindingValueBytes.clone(); + } + + @Override + public byte[] capacityValueBytes() { + return capacityValueBytes.clone(); + } + + private boolean matches(byte[] memberBytes, byte[] bindingRef, UUID reservationId) { + if (!Arrays.equals(bindingValueBytes, memberBytes) + || !Arrays.equals(capacityValueBytes, memberBytes)) return false; + var member = CanonicalGameplayIssuerMemberV2Codec.decode(memberBytes); + return Arrays.equals(member.owner().bindingRef().bytes(), bindingRef) + && reservationId.equals(member.reservation().reservationId()); + } + } + + record Capacity( + BigInteger partitionId, + BigInteger partitionCapacity, + BigInteger baselineCountedCapacity, + BigInteger baselineReservationCount, + BigInteger baselineBindingCount, + BigInteger sqlPartitionCapacity, + BigInteger sqlAggregateCapacity, + BigInteger issuerAggregateBound) { + Capacity { + partitionId = nonNegative(partitionId, "capacity partitionId"); + partitionCapacity = positive(partitionCapacity, "capacity partitionCapacity"); + baselineCountedCapacity = nonNegative(baselineCountedCapacity, "baselineCountedCapacity"); + baselineReservationCount = nonNegative(baselineReservationCount, "baselineReservationCount"); + baselineBindingCount = nonNegative(baselineBindingCount, "baselineBindingCount"); + sqlPartitionCapacity = positive(sqlPartitionCapacity, "sqlPartitionCapacity"); + sqlAggregateCapacity = nonNegative(sqlAggregateCapacity, "sqlAggregateCapacity"); + issuerAggregateBound = positive(issuerAggregateBound, "issuerAggregateBound"); + if (baselineCountedCapacity.compareTo(partitionCapacity) > 0 + || sqlPartitionCapacity.compareTo(partitionCapacity) > 0 + || sqlAggregateCapacity.signum() == 0 + || sqlAggregateCapacity.compareTo(issuerAggregateBound) > 0) { + throw new IllegalArgumentException("Issuer local capacity proof exceeds its pinned bound"); + } + } + + private boolean matches( + CanonicalGameplayIssuerMemberV2Value member, PhysicalReadback readback) { + return partitionId.equals(member.reservation().partitionId()) + && partitionCapacity.equals(member.layoutDescriptor().partitionCapacity()) + && partitionId.compareTo(member.layoutDescriptor().partitionCount()) < 0 + && BigInteger.valueOf(readback.countedCapacity()).compareTo(partitionCapacity) <= 0 + && BigInteger.valueOf(readback.countedCapacity()) + .compareTo(baselineCountedCapacity.add(BigInteger.ONE)) + >= 0 + && BigInteger.valueOf(readback.reservationCount()) + .compareTo(baselineReservationCount.add(BigInteger.ONE)) + >= 0 + && BigInteger.valueOf(readback.bindingCount()) + .compareTo(baselineBindingCount.add(BigInteger.ONE)) + >= 0 + && BigInteger.valueOf(readback.countedCapacity()).compareTo(sqlPartitionCapacity) <= 0 + && sqlPartitionCapacity.compareTo(baselineCountedCapacity.add(BigInteger.ONE)) >= 0; + } + } + + private static void requireNonNil(UUID value, String name) { + Objects.requireNonNull(value, name); + if (value.equals(new UUID(0L, 0L))) + throw new IllegalArgumentException(name + " must not be nil"); + } + + private static byte[] nonEmpty(byte[] value, String name) { + Objects.requireNonNull(value, name); + if (value.length == 0) throw new IllegalArgumentException(name + " must not be empty"); + return value.clone(); + } + + private static BigInteger positive(BigInteger value, String name) { + Objects.requireNonNull(value, name); + if (value.signum() <= 0) throw new IllegalArgumentException(name + " must be positive"); + return value; + } + + private static BigInteger nonNegative(BigInteger value, String name) { + Objects.requireNonNull(value, name); + if (value.signum() < 0) throw new IllegalArgumentException(name + " must not be negative"); + return value; + } + + private static String digest(String value, String name) { + Objects.requireNonNull(value, name); + if (!value.matches("sha256:[0-9a-f]{64}")) { + throw new IllegalArgumentException(name + " must be canonical SHA-256"); + } + return value; + } + + private static void requireMatches(byte[] value, String expected, String name) { + if (!CanonicalGameplayIssuerMemberV2Codec.sha256(value).equals(expected)) { + throw new IllegalArgumentException(name + " digest does not match its exact bytes"); + } + } +} diff --git a/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/repository/CanonicalGameplayIssuerBindingLocalAcknowledgementCodec.java b/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/repository/CanonicalGameplayIssuerBindingLocalAcknowledgementCodec.java new file mode 100644 index 0000000000..1ea58dd5b5 --- /dev/null +++ b/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/repository/CanonicalGameplayIssuerBindingLocalAcknowledgementCodec.java @@ -0,0 +1,479 @@ +package net.firedevops.firemud.gamesession.repository; + +import com.fasterxml.jackson.core.JsonFactory; +import com.fasterxml.jackson.core.StreamReadConstraints; +import com.fasterxml.jackson.core.StreamReadFeature; +import com.fasterxml.jackson.databind.DeserializationFeature; +import com.fasterxml.jackson.databind.JsonNode; +import com.fasterxml.jackson.databind.ObjectMapper; +import com.fasterxml.jackson.databind.node.ObjectNode; +import java.io.IOException; +import java.math.BigInteger; +import java.nio.ByteBuffer; +import java.nio.charset.CodingErrorAction; +import java.nio.charset.StandardCharsets; +import java.util.Arrays; +import java.util.Base64; +import java.util.Iterator; +import java.util.Objects; +import java.util.Set; +import java.util.UUID; +import java.util.regex.Pattern; +import net.firedevops.firemud.common.json.Rfc8785CanonicalJson; + +/** Closed, bounded RFC 8785 codec for the separate issuer binding-local acknowledgement. */ +final class CanonicalGameplayIssuerBindingLocalAcknowledgementCodec { + static final int MAX_ACKNOWLEDGEMENT_BYTES = 1024 * 1024; + private static final Pattern POSITIVE_DECIMAL = Pattern.compile("[1-9][0-9]{0,255}"); + private static final Pattern NON_NEGATIVE_DECIMAL = Pattern.compile("(?:0|[1-9][0-9]{0,255})"); + private static final Pattern SHA256 = Pattern.compile("sha256:[0-9a-f]{64}"); + private static final JsonFactory JSON_FACTORY = + JsonFactory.builder() + .streamReadConstraints( + StreamReadConstraints.builder() + .maxNestingDepth(8) + .maxStringLength(MAX_ACKNOWLEDGEMENT_BYTES) + .maxNumberLength(8) + .build()) + .enable(StreamReadFeature.STRICT_DUPLICATE_DETECTION) + .build(); + private static final ObjectMapper JSON = + new ObjectMapper(JSON_FACTORY).enable(DeserializationFeature.FAIL_ON_TRAILING_TOKENS); + private static final Set ROOT_FIELDS = + Set.of( + "schemaVersion", + "scope", + "issuerBindingLocalAcknowledgementGeneration", + "globalIssuerCoverageGeneration", + "operation", + "binding", + "reservation", + "anchor", + "memberOperation", + "currentSource", + "physicalReadback", + "capacity", + "sqlCurrentnessDigest"); + private static final Set OPERATION_FIELDS = + Set.of("issuerId", "operationId", "requestId", "transitionId", "candidateAccountIndexFence"); + private static final Set BINDING_FIELDS = + Set.of("bindingRef", "bindingGeneration", "memberValueBytes", "memberValueDigest"); + private static final Set RESERVATION_FIELDS = + Set.of( + "reservationId", + "transitionId", + "reservationFence", + "partitionId", + "lifecycle", + "issuerCoverageOperationId", + "issuerCoverageOperationFence", + "coverageFence", + "inventorySnapshotRevision", + "inventoryRevision"); + private static final Set ANCHOR_FIELDS = + Set.of( + "bootstrapOperationId", + "issuerCoverageOperationId", + "operationFence", + "coverageFence", + "inventorySnapshotRevision", + "globalCoverageGeneration", + "controlEpoch", + "layoutVersion", + "partitionCount", + "partitionCapacity", + "mappingIdentity", + "layoutDescriptorBytes", + "layoutDescriptorDigest", + "exactBytes", + "exactDigest"); + private static final Set MEMBER_OPERATION_FIELDS = + Set.of("operationId", "operationFence", "generation"); + private static final Set CURRENT_SOURCE_FIELDS = + Set.of( + "issuerAuthGeneration", + "checkpointBytes", + "checkpointDigest", + "eventBytes", + "eventDigest", + "incarnationBytes", + "incarnationDigest"); + private static final Set PHYSICAL_READBACK_FIELDS = + Set.of( + "bindingValueBytes", + "bindingValueDigest", + "capacityValueBytes", + "capacityValueDigest", + "partitionFieldSetDigest", + "scriptOutcome", + "fieldCount", + "reservationCount", + "bindingCount", + "countedCapacity"); + private static final Set CAPACITY_FIELDS = + Set.of( + "partitionId", + "partitionCapacity", + "baselineCountedCapacity", + "baselineReservationCount", + "baselineBindingCount", + "sqlPartitionCapacity", + "sqlAggregateCapacity", + "issuerAggregateBound"); + + private CanonicalGameplayIssuerBindingLocalAcknowledgementCodec() {} + + static byte[] encode(CanonicalGameplayIssuerBindingLocalAcknowledgement.Evidence evidence) { + Objects.requireNonNull(evidence, "evidence"); + try { + ObjectNode root = JSON.createObjectNode(); + root.put("schemaVersion", CanonicalGameplayIssuerBindingLocalAcknowledgement.SCHEMA_VERSION); + root.put("scope", CanonicalGameplayIssuerBindingLocalAcknowledgement.SCOPE); + root.put( + "issuerBindingLocalAcknowledgementGeneration", + evidence.issuerBindingLocalAcknowledgementGeneration().toString()); + root.put( + "globalIssuerCoverageGeneration", + CanonicalGameplayIssuerBindingLocalAcknowledgement.GLOBAL_COVERAGE_GENERATION); + + var operation = root.putObject("operation"); + operation.put("issuerId", evidence.issuerId()); + operation.put("operationId", evidence.operationId().toString()); + operation.put("requestId", evidence.requestId().toString()); + operation.put("transitionId", evidence.transitionId().toString()); + operation.put("candidateAccountIndexFence", evidence.candidateAccountIndexFence().toString()); + + var binding = root.putObject("binding"); + binding.put("bindingRef", encodeBase64(evidence.bindingRef())); + binding.put("bindingGeneration", evidence.bindingGeneration().toString()); + binding.put("memberValueBytes", encodeBase64(evidence.memberValueBytes())); + binding.put("memberValueDigest", evidence.memberValueDigest()); + + var reservation = root.putObject("reservation"); + var r = evidence.reservation(); + reservation.put("reservationId", r.reservationId().toString()); + reservation.put("transitionId", r.transitionId().toString()); + reservation.put("reservationFence", r.reservationFence().toString()); + reservation.put("partitionId", r.partitionId().toString()); + reservation.put("lifecycle", r.lifecycle()); + reservation.put("issuerCoverageOperationId", r.issuerCoverageOperationId().toString()); + reservation.put("issuerCoverageOperationFence", r.issuerCoverageOperationFence().toString()); + reservation.put("coverageFence", r.coverageFence().toString()); + reservation.put("inventorySnapshotRevision", r.inventorySnapshotRevision().toString()); + reservation.put("inventoryRevision", r.inventoryRevision().toString()); + + var anchor = root.putObject("anchor"); + var a = evidence.anchor(); + anchor.put("bootstrapOperationId", a.bootstrapOperationId().toString()); + anchor.put("issuerCoverageOperationId", a.issuerCoverageOperationId().toString()); + anchor.put("operationFence", a.operationFence().toString()); + anchor.put("coverageFence", a.coverageFence().toString()); + anchor.put("inventorySnapshotRevision", a.inventorySnapshotRevision().toString()); + anchor.put("globalCoverageGeneration", a.globalCoverageGeneration().toString()); + anchor.put("controlEpoch", a.controlEpoch().toString()); + anchor.put("layoutVersion", a.layoutVersion().toString()); + anchor.put("partitionCount", a.partitionCount().toString()); + anchor.put("partitionCapacity", a.partitionCapacity().toString()); + anchor.put("mappingIdentity", a.mappingIdentity()); + anchor.put("layoutDescriptorBytes", encodeBase64(a.layoutDescriptorBytes())); + anchor.put("layoutDescriptorDigest", a.layoutDescriptorDigest()); + anchor.put("exactBytes", encodeBase64(a.exactBytes())); + anchor.put("exactDigest", a.exactDigest()); + + var memberOperation = root.putObject("memberOperation"); + memberOperation.put("operationId", evidence.memberOperation().operationId().toString()); + memberOperation.put("operationFence", evidence.memberOperation().operationFence().toString()); + memberOperation.put("generation", evidence.memberOperation().generation().toString()); + + var source = root.putObject("currentSource"); + var s = evidence.currentSource(); + source.put("issuerAuthGeneration", s.issuerAuthGeneration().toString()); + source.put("checkpointBytes", encodeBase64(s.checkpointBytes())); + source.put("checkpointDigest", s.checkpointDigest()); + source.put("eventBytes", s.eventBytes() == null ? null : encodeBase64(s.eventBytes())); + source.put("eventDigest", s.eventDigest()); + source.put("incarnationBytes", encodeBase64(s.incarnationBytes())); + source.put("incarnationDigest", s.incarnationDigest()); + + var physical = root.putObject("physicalReadback"); + var p = evidence.physicalReadback(); + physical.put("bindingValueBytes", encodeBase64(p.bindingValueBytes())); + physical.put("bindingValueDigest", p.bindingValueDigest()); + physical.put("capacityValueBytes", encodeBase64(p.capacityValueBytes())); + physical.put("capacityValueDigest", p.capacityValueDigest()); + physical.put("partitionFieldSetDigest", p.partitionFieldSetDigest()); + physical.put("scriptOutcome", p.scriptOutcome()); + physical.put("fieldCount", p.fieldCount()); + physical.put("reservationCount", p.reservationCount()); + physical.put("bindingCount", p.bindingCount()); + physical.put("countedCapacity", p.countedCapacity()); + + var capacity = root.putObject("capacity"); + var c = evidence.capacity(); + capacity.put("partitionId", c.partitionId().toString()); + capacity.put("partitionCapacity", c.partitionCapacity().toString()); + capacity.put("baselineCountedCapacity", c.baselineCountedCapacity().toString()); + capacity.put("baselineReservationCount", c.baselineReservationCount().toString()); + capacity.put("baselineBindingCount", c.baselineBindingCount().toString()); + capacity.put("sqlPartitionCapacity", c.sqlPartitionCapacity().toString()); + capacity.put("sqlAggregateCapacity", c.sqlAggregateCapacity().toString()); + capacity.put("issuerAggregateBound", c.issuerAggregateBound().toString()); + root.put("sqlCurrentnessDigest", evidence.sqlCurrentnessDigest()); + + byte[] result = Rfc8785CanonicalJson.canonicalizeUtf8(JSON.writeValueAsString(root)); + if (result.length == 0 || result.length > MAX_ACKNOWLEDGEMENT_BYTES) { + throw invalid("Issuer binding-local acknowledgement exceeds its 1 MiB bound"); + } + return result; + } catch (IOException failure) { + throw new IllegalArgumentException( + "Could not encode issuer binding-local acknowledgement", failure); + } + } + + static CanonicalGameplayIssuerBindingLocalAcknowledgement.Evidence decode(byte[] encoded) { + Objects.requireNonNull(encoded, "encoded"); + if (encoded.length == 0 || encoded.length > MAX_ACKNOWLEDGEMENT_BYTES) { + throw invalid("Issuer binding-local acknowledgement is empty or exceeds its bound"); + } + JsonNode root = parse(encoded); + requireFields(root, ROOT_FIELDS, "root"); + if (intValue(root, "schemaVersion") + != CanonicalGameplayIssuerBindingLocalAcknowledgement.SCHEMA_VERSION + || !text(root, "scope").equals(CanonicalGameplayIssuerBindingLocalAcknowledgement.SCOPE) + || !text(root, "globalIssuerCoverageGeneration") + .equals( + CanonicalGameplayIssuerBindingLocalAcknowledgement.GLOBAL_COVERAGE_GENERATION)) { + throw invalid("Issuer binding-local acknowledgement version or scope is unsupported"); + } + + JsonNode operation = object(root, "operation", OPERATION_FIELDS); + JsonNode binding = object(root, "binding", BINDING_FIELDS); + JsonNode reservation = object(root, "reservation", RESERVATION_FIELDS); + JsonNode anchor = object(root, "anchor", ANCHOR_FIELDS); + JsonNode memberOperation = object(root, "memberOperation", MEMBER_OPERATION_FIELDS); + JsonNode currentSource = object(root, "currentSource", CURRENT_SOURCE_FIELDS); + JsonNode physicalReadback = object(root, "physicalReadback", PHYSICAL_READBACK_FIELDS); + JsonNode capacity = object(root, "capacity", CAPACITY_FIELDS); + + CanonicalGameplayIssuerBindingLocalAcknowledgement.Reservation reservationValue = + new CanonicalGameplayIssuerBindingLocalAcknowledgement.Reservation( + uuid(reservation, "reservationId"), + uuid(reservation, "transitionId"), + uuid(reservation, "reservationFence"), + nonNegative(reservation, "partitionId"), + text(reservation, "lifecycle"), + uuid(reservation, "issuerCoverageOperationId"), + positive(reservation, "issuerCoverageOperationFence"), + positive(reservation, "coverageFence"), + positive(reservation, "inventorySnapshotRevision"), + positive(reservation, "inventoryRevision")); + CanonicalGameplayIssuerBindingLocalAcknowledgement.Anchor anchorValue = + new CanonicalGameplayIssuerBindingLocalAcknowledgement.Anchor( + uuid(anchor, "bootstrapOperationId"), + uuid(anchor, "issuerCoverageOperationId"), + positive(anchor, "operationFence"), + positive(anchor, "coverageFence"), + positive(anchor, "inventorySnapshotRevision"), + positive(anchor, "globalCoverageGeneration"), + positive(anchor, "controlEpoch"), + positive(anchor, "layoutVersion"), + positive(anchor, "partitionCount"), + positive(anchor, "partitionCapacity"), + text(anchor, "mappingIdentity"), + base64(anchor, "layoutDescriptorBytes"), + digest(anchor, "layoutDescriptorDigest"), + base64(anchor, "exactBytes"), + digest(anchor, "exactDigest")); + CanonicalGameplayIssuerBindingLocalAcknowledgement.MemberOperation memberOperationValue = + new CanonicalGameplayIssuerBindingLocalAcknowledgement.MemberOperation( + uuid(memberOperation, "operationId"), + positive(memberOperation, "operationFence"), + positive(memberOperation, "generation")); + CanonicalGameplayIssuerBindingLocalAcknowledgement.CurrentSource currentSourceValue = + new CanonicalGameplayIssuerBindingLocalAcknowledgement.CurrentSource( + positive(currentSource, "issuerAuthGeneration"), + base64(currentSource, "checkpointBytes"), + digest(currentSource, "checkpointDigest"), + nullableBase64(currentSource, "eventBytes"), + nullableDigest(currentSource, "eventDigest"), + base64(currentSource, "incarnationBytes"), + digest(currentSource, "incarnationDigest")); + CanonicalGameplayIssuerBindingLocalAcknowledgement.PhysicalReadback physicalReadbackValue = + new CanonicalGameplayIssuerBindingLocalAcknowledgement.PhysicalReadback( + base64(physicalReadback, "bindingValueBytes"), + digest(physicalReadback, "bindingValueDigest"), + base64(physicalReadback, "capacityValueBytes"), + digest(physicalReadback, "capacityValueDigest"), + digest(physicalReadback, "partitionFieldSetDigest"), + intValue(physicalReadback, "scriptOutcome"), + nonNegativeInt(physicalReadback, "fieldCount"), + nonNegativeInt(physicalReadback, "reservationCount"), + nonNegativeInt(physicalReadback, "bindingCount"), + nonNegativeInt(physicalReadback, "countedCapacity")); + CanonicalGameplayIssuerBindingLocalAcknowledgement.Capacity capacityValue = + new CanonicalGameplayIssuerBindingLocalAcknowledgement.Capacity( + nonNegative(capacity, "partitionId"), + positive(capacity, "partitionCapacity"), + nonNegative(capacity, "baselineCountedCapacity"), + nonNegative(capacity, "baselineReservationCount"), + nonNegative(capacity, "baselineBindingCount"), + positive(capacity, "sqlPartitionCapacity"), + nonNegative(capacity, "sqlAggregateCapacity"), + positive(capacity, "issuerAggregateBound")); + + var evidence = + new CanonicalGameplayIssuerBindingLocalAcknowledgement.Evidence( + uuid(operation, "operationId"), + positive(root, "issuerBindingLocalAcknowledgementGeneration"), + uuid(operation, "requestId"), + uuid(operation, "transitionId"), + uuid(operation, "candidateAccountIndexFence"), + text(operation, "issuerId"), + base64(binding, "bindingRef"), + positive(binding, "bindingGeneration"), + base64(binding, "memberValueBytes"), + digest(binding, "memberValueDigest"), + reservationValue, + anchorValue, + memberOperationValue, + currentSourceValue, + physicalReadbackValue, + capacityValue, + digest(root, "sqlCurrentnessDigest")); + if (!Arrays.equals(encoded, encode(evidence))) { + throw invalid("Issuer binding-local acknowledgement is not canonical"); + } + return evidence; + } + + private static JsonNode parse(byte[] encoded) { + try { + String json = + StandardCharsets.UTF_8 + .newDecoder() + .onMalformedInput(CodingErrorAction.REPORT) + .onUnmappableCharacter(CodingErrorAction.REPORT) + .decode(ByteBuffer.wrap(encoded)) + .toString(); + JsonNode root = JSON.readTree(json); + if (root == null || !root.isObject()) throw invalid("Acknowledgement root must be an object"); + return root; + } catch (IOException malformed) { + throw new IllegalArgumentException( + "Issuer binding-local acknowledgement is malformed", malformed); + } + } + + private static JsonNode object(JsonNode parent, String name, Set fields) { + JsonNode value = parent.get(name); + requireFields(value, fields, name); + return value; + } + + private static void requireFields(JsonNode value, Set expected, String name) { + if (value == null || !value.isObject()) throw invalid(name + " must be an object"); + Set actual = new java.util.HashSet<>(); + Iterator names = value.fieldNames(); + while (names.hasNext()) actual.add(names.next()); + if (!actual.equals(expected)) throw invalid(name + " contains missing or unknown fields"); + } + + private static String text(JsonNode object, String field) { + JsonNode value = object.get(field); + if (value == null || !value.isTextual() || value.textValue().isEmpty()) { + throw invalid(field + " must be nonempty text"); + } + return value.textValue(); + } + + private static int intValue(JsonNode object, String field) { + JsonNode value = object.get(field); + if (value == null || !value.isIntegralNumber() || !value.canConvertToInt()) { + throw invalid(field + " must be an exact integer"); + } + return value.intValue(); + } + + private static int nonNegativeInt(JsonNode object, String field) { + int value = intValue(object, field); + if (value < 0) throw invalid(field + " must not be negative"); + return value; + } + + private static BigInteger positive(JsonNode object, String field) { + return decimal(text(object, field), field, true); + } + + private static BigInteger nonNegative(JsonNode object, String field) { + return decimal(text(object, field), field, false); + } + + private static BigInteger decimal(String value, String name, boolean positive) { + Pattern pattern = positive ? POSITIVE_DECIMAL : NON_NEGATIVE_DECIMAL; + if (!pattern.matcher(value).matches()) throw invalid(name + " is not canonical decimal"); + return new BigInteger(value); + } + + private static UUID uuid(JsonNode object, String field) { + String value = text(object, field); + try { + UUID parsed = UUID.fromString(value); + if (!parsed.toString().equals(value) || parsed.equals(new UUID(0L, 0L))) { + throw invalid(field + " is not a canonical non-nil UUID"); + } + return parsed; + } catch (IllegalArgumentException malformed) { + throw invalid(field + " is not a canonical non-nil UUID", malformed); + } + } + + private static String digest(JsonNode object, String field) { + String value = text(object, field); + if (!SHA256.matcher(value).matches()) throw invalid(field + " is not canonical SHA-256"); + return value; + } + + private static String nullableDigest(JsonNode object, String field) { + JsonNode value = object.get(field); + if (value == null || value.isNull()) return null; + if (!value.isTextual() || !SHA256.matcher(value.textValue()).matches()) { + throw invalid(field + " is not canonical SHA-256 or null"); + } + return value.textValue(); + } + + private static byte[] base64(JsonNode object, String field) { + String value = text(object, field); + try { + byte[] decoded = Base64.getDecoder().decode(value); + if (decoded.length == 0 || !Base64.getEncoder().encodeToString(decoded).equals(value)) { + throw invalid(field + " is not canonical padded Base64"); + } + return decoded; + } catch (IllegalArgumentException malformed) { + throw invalid(field + " is not canonical padded Base64", malformed); + } + } + + private static byte[] nullableBase64(JsonNode object, String field) { + JsonNode value = object.get(field); + if (value == null || value.isNull()) return null; + if (!value.isTextual()) throw invalid(field + " must be canonical Base64 or null"); + ObjectNode wrapper = JSON.createObjectNode(); + wrapper.set(field, value); + return base64(wrapper, field); + } + + private static String encodeBase64(byte[] value) { + return Base64.getEncoder().encodeToString(value); + } + + private static IllegalArgumentException invalid(String message) { + return new IllegalArgumentException(message); + } + + private static IllegalArgumentException invalid(String message, Throwable cause) { + return new IllegalArgumentException(message, cause); + } +} diff --git a/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/repository/CanonicalGameplayIssuerBindingLocalAcknowledgementRepository.java b/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/repository/CanonicalGameplayIssuerBindingLocalAcknowledgementRepository.java new file mode 100644 index 0000000000..42b9436621 --- /dev/null +++ b/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/repository/CanonicalGameplayIssuerBindingLocalAcknowledgementRepository.java @@ -0,0 +1,784 @@ +package net.firedevops.firemud.gamesession.repository; + +import java.math.BigDecimal; +import java.math.BigInteger; +import java.nio.charset.StandardCharsets; +import java.util.Arrays; +import java.util.Map; +import java.util.Objects; +import java.util.UUID; +import net.firedevops.firemud.common.security.GameSessionAccountDelegationProfile; +import net.firedevops.firemud.gamesession.binding.CanonicalIssuerPartitionReservation; +import net.firedevops.firemud.gamesession.repository.CanonicalGameplayIssuerBindingLocalAcknowledgement.Anchor; +import net.firedevops.firemud.gamesession.repository.CanonicalGameplayIssuerBindingLocalAcknowledgement.Capacity; +import net.firedevops.firemud.gamesession.repository.CanonicalGameplayIssuerBindingLocalAcknowledgement.CurrentSource; +import net.firedevops.firemud.gamesession.repository.CanonicalGameplayIssuerBindingLocalAcknowledgement.Evidence; +import net.firedevops.firemud.gamesession.repository.CanonicalGameplayIssuerBindingLocalAcknowledgement.MemberOperation; +import net.firedevops.firemud.gamesession.repository.CanonicalGameplayIssuerBindingLocalAcknowledgement.PhysicalReadback; +import net.firedevops.firemud.gamesession.repository.CanonicalGameplayIssuerBindingLocalAcknowledgement.Reservation; +import org.jooq.DSLContext; +import org.jooq.Record; +import org.springframework.transaction.support.TransactionSynchronizationManager; + +/** SQL owner for immutable ordinary NEW issuer binding-local physical acknowledgement receipts. */ +final class CanonicalGameplayIssuerBindingLocalAcknowledgementRepository { + private static final String ACKNOWLEDGEMENT = + "game_session_canonical_issuer_binding_local_acknowledgement"; + private static final String GENERATION_COUNTER = + "game_session_canonical_issuer_binding_local_ack_gen_counter"; + private static final int MAX_FIELD_COUNT = + CanonicalGameplayIssuerBootstrapPartitionPhysicalCodec.MAX_HASH_FIELDS + + 2 * CanonicalGameplayIssuerBootstrapPartitionPhysicalCodec.MAX_MEMBER_OPERATIONS; + + private final DSLContext dsl; + private final CanonicalGameplayIssuerBootstrapPartitionRedisOwner.CurrentIssuerStateSource + currentIssuerStateSource; + private final CanonicalGameplayIssuerBindingLocalProjectionRepository projectionRepository; + + CanonicalGameplayIssuerBindingLocalAcknowledgementRepository( + DSLContext dsl, + CanonicalGameplayIssuerBootstrapPartitionRedisOwner.CurrentIssuerStateSource + currentIssuerStateSource) { + this.dsl = Objects.requireNonNull(dsl, "dsl"); + this.currentIssuerStateSource = + Objects.requireNonNull(currentIssuerStateSource, "currentIssuerStateSource"); + this.projectionRepository = + new CanonicalGameplayIssuerBindingLocalProjectionRepository(dsl, currentIssuerStateSource); + } + + /** + * Records the exact first physical acknowledgement only from the private readback produced by the + * real one-key Redis owner. SQL rechecks the installed anchor and all current source rows under + * the inventory clock; no transaction spans Redis or the external current-source reads. + */ + CanonicalGameplayIssuerBindingLocalAcknowledgement acknowledge( + CanonicalGameplayIssuerBindingLocalRedisOwner.Readback readback) { + Objects.requireNonNull(readback, "readback"); + requireNoAmbientTransaction(); + CanonicalGameplayIssuerBindingLocalOperation operation = readback.operation(); + var before = readCurrentIssuerState("before acknowledgement"); + CanonicalGameplayIssuerBindingLocalAcknowledgement acknowledged = + dsl.transactionResult( + configuration -> { + DSLContext transaction = org.jooq.impl.DSL.using(configuration); + CanonicalGameplayBindingInventoryRepository.lockInventoryRevision(transaction); + var work = + projectionRepository.readPreparedPartitionWorkInTransaction( + transaction, operation, before); + requireCurrentIssuerSource(operation, before); + requireEligibleCandidate(work); + + Record existing = + transaction.fetchOne( + "SELECT * FROM " + ACKNOWLEDGEMENT + " WHERE operation_id = ? FOR UPDATE", + operation.operationId()); + if (existing != null) { + var prior = readAcknowledgement(transaction, existing); + requireSameOperation(prior.evidence(), operation); + requireSameCurrentSources(prior.evidence(), operation, before); + requireReadbackTargetStillMatches(prior.evidence(), readback); + return prior; + } + + if (!Arrays.equals(readback.sqlCurrentnessDigest(), work.sqlCurrentnessDigest())) { + throw unavailable( + "SQL issuer cohort changed after physical readback; retry the original operation"); + } + ReadbackProof proof = validateReadback(operation, work, readback, before); + // The independent transition generation advances only in this SQL transaction, + // after both the exact current SQL operation and private physical readback validate. + // Counter advancement and immutable receipt insertion commit or roll back together. + BigInteger acknowledgementGeneration = + allocateAcknowledgementGeneration(transaction, operation.anchor().issuerId()); + Evidence evidence = + buildEvidence(operation, readback, before, proof, acknowledgementGeneration); + var result = CanonicalGameplayIssuerBindingLocalAcknowledgement.create(evidence); + insert(transaction, result); + Record stored = + transaction.fetchOne( + "SELECT * FROM " + ACKNOWLEDGEMENT + " WHERE operation_id = ? FOR UPDATE", + operation.operationId()); + if (stored == null) throw unavailable("Durable issuer acknowledgement disappeared"); + var durable = readAcknowledgement(transaction, stored); + if (!Arrays.equals(result.exactBytes(), durable.exactBytes()) + || !result.digest().equals(durable.digest())) { + throw unavailable( + "Durable issuer acknowledgement readback differs from its source"); + } + return durable; + }); + var after = readCurrentIssuerState("after acknowledgement"); + if (!sameCurrentIssuerState(before, after)) { + throw unavailable( + "Issuer source or storage incarnation moved after acknowledgement persistence; the exact historical receipt remains retained"); + } + return acknowledged; + } + + /** Reads and integrity-checks retained evidence without implying that it is currently usable. */ + CanonicalGameplayIssuerBindingLocalAcknowledgement readHistorical(UUID operationId) { + Objects.requireNonNull(operationId, "operationId"); + requireNoAmbientTransaction(); + Record row = + dsl.fetchOne("SELECT * FROM " + ACKNOWLEDGEMENT + " WHERE operation_id = ?", operationId); + if (row == null) return null; + return readAcknowledgement(dsl, row); + } + + private void insert( + DSLContext transaction, CanonicalGameplayIssuerBindingLocalAcknowledgement acknowledgement) { + Evidence evidence = acknowledgement.evidence(); + Reservation reservation = evidence.reservation(); + Anchor anchor = evidence.anchor(); + MemberOperation memberOperation = evidence.memberOperation(); + transaction.execute( + "INSERT INTO " + + ACKNOWLEDGEMENT + + " (operation_id, acknowledgement_generation, issuer_id, request_id, transition_id, binding_ref, binding_generation," + + " reservation_id, reservation_fence, original_issuer_coverage_operation_id," + + " original_issuer_coverage_operation_fence, original_coverage_fence," + + " original_inventory_snapshot_revision, original_inventory_revision," + + " anchor_bootstrap_operation_id, anchor_issuer_coverage_operation_id," + + " anchor_operation_fence, anchor_coverage_fence, anchor_inventory_snapshot_revision," + + " anchor_global_coverage_generation," + + " issuer_control_epoch, local_member_operation_id, local_member_operation_fence," + + " local_member_generation, physical_partition_id, physical_field_set_digest," + + " sql_currentness_digest, acknowledgement_schema_version, acknowledgement_bytes," + + " acknowledgement_digest)" + + " VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)" + + " ON CONFLICT (operation_id) DO NOTHING", + evidence.operationId(), + evidence.issuerBindingLocalAcknowledgementGeneration(), + evidence.issuerId(), + evidence.requestId(), + evidence.transitionId(), + evidence.bindingRef(), + evidence.bindingGeneration(), + reservation.reservationId(), + reservation.reservationFence(), + reservation.issuerCoverageOperationId(), + reservation.issuerCoverageOperationFence(), + reservation.coverageFence(), + reservation.inventorySnapshotRevision(), + reservation.inventoryRevision(), + anchor.bootstrapOperationId(), + anchor.issuerCoverageOperationId(), + anchor.operationFence(), + anchor.coverageFence(), + anchor.inventorySnapshotRevision(), + anchor.globalCoverageGeneration(), + anchor.controlEpoch(), + memberOperation.operationId(), + memberOperation.operationFence(), + memberOperation.generation(), + reservation.partitionId(), + evidence.physicalReadback().partitionFieldSetDigest(), + evidence.sqlCurrentnessDigest(), + (short) CanonicalGameplayIssuerBindingLocalAcknowledgement.SCHEMA_VERSION, + acknowledgement.exactBytes(), + acknowledgement.digest()); + } + + private static BigInteger allocateAcknowledgementGeneration( + DSLContext transaction, String issuerId) { + transaction.execute( + "INSERT INTO " + + GENERATION_COUNTER + + " (issuer_id, last_issued_binding_local_acknowledgement_generation, counter_version)" + + " VALUES (?, 0, 0) ON CONFLICT (issuer_id) DO NOTHING", + issuerId); + Record counter = + transaction.fetchOne( + "SELECT * FROM " + GENERATION_COUNTER + " WHERE issuer_id = ? FOR UPDATE", issuerId); + if (counter == null) + throw unavailable("Issuer binding-local ACK generation counter is missing"); + + BigInteger previous = + nonnegative(counter, "last_issued_binding_local_acknowledgement_generation"); + Long versionValue = counter.get("counter_version", Long.class); + if (versionValue == null + || versionValue < 0 + || (versionValue == 0 && previous.signum() != 0) + || (versionValue > 0 && previous.signum() == 0)) { + throw unavailable("Issuer binding-local ACK generation counter is malformed"); + } + Record latestReceipt = + transaction.fetchOne( + "SELECT MAX(acknowledgement_generation) AS latest_generation FROM " + + ACKNOWLEDGEMENT + + " WHERE issuer_id = ?", + issuerId); + Object latestValue = latestReceipt == null ? null : latestReceipt.get("latest_generation"); + BigInteger latest = + latestValue == null + ? BigInteger.ZERO + : numberValue(latestValue, "latest acknowledgement generation"); + if (!previous.equals(latest)) { + throw unavailable( + "Issuer binding-local ACK generation counter differs from retained receipts"); + } + + BigInteger next = previous.add(BigInteger.ONE); + if (next.toString().length() > 256) { + throw unavailable("Issuer binding-local ACK generation is outside its bound"); + } + long nextVersion; + try { + nextVersion = Math.addExact(versionValue, 1L); + } catch (ArithmeticException overflow) { + throw unavailable( + "Issuer binding-local ACK generation counter version is exhausted", overflow); + } + Record updated = + transaction.fetchOne( + "UPDATE " + + GENERATION_COUNTER + + " SET last_issued_binding_local_acknowledgement_generation = ?," + + " counter_version = ?, updated_at = CURRENT_TIMESTAMP" + + " WHERE issuer_id = ? AND last_issued_binding_local_acknowledgement_generation = ?" + + " AND counter_version = ? RETURNING issuer_id", + next, + nextVersion, + issuerId, + previous, + versionValue); + if (updated == null) { + throw unavailable("Issuer binding-local ACK generation compare-and-set lost"); + } + return next; + } + + private static BigInteger numberValue(Object value, String field) { + if (!(value instanceof Number number)) throw unavailable(field + " is missing or nonnumeric"); + try { + if (number instanceof BigDecimal decimal) return decimal.toBigIntegerExact(); + return BigInteger.valueOf(number.longValue()); + } catch (ArithmeticException malformed) { + throw unavailable(field + " is not an exact integer", malformed); + } + } + + private static CanonicalGameplayIssuerBindingLocalAcknowledgement readAcknowledgement( + DSLContext query, Record row) { + byte[] exactBytes = bytes(row, "acknowledgement_bytes"); + CanonicalGameplayIssuerBindingLocalAcknowledgement acknowledgement; + try { + acknowledgement = CanonicalGameplayIssuerBindingLocalAcknowledgement.decode(exactBytes); + } catch (RuntimeException malformed) { + throw unavailable("Stored issuer binding-local acknowledgement is malformed", malformed); + } + Evidence evidence = acknowledgement.evidence(); + Record operation = + query.fetchOne( + "SELECT * FROM " + + "game_session_canonical_issuer_binding_local_operation" + + " WHERE operation_id = ?", + evidence.operationId()); + Record installedAnchor = + query.fetchOne( + "SELECT global_coverage_generation, exact_anchor_bytes" + + " FROM game_session_canonical_issuer_installed_anchor WHERE issuer_id = ?", + evidence.issuerId()); + Record generationCounter = + query.fetchOne( + "SELECT last_issued_binding_local_acknowledgement_generation" + + " FROM game_session_canonical_issuer_binding_local_ack_gen_counter" + + " WHERE issuer_id = ?", + evidence.issuerId()); + if (!uuid(row, "operation_id").equals(evidence.operationId()) + || !positive(row, "acknowledgement_generation") + .equals(evidence.issuerBindingLocalAcknowledgementGeneration()) + || !GameSessionAccountDelegationProfile.ISSUER.equals(text(row, "issuer_id")) + || !text(row, "issuer_id").equals(evidence.issuerId()) + || !uuid(row, "request_id").equals(evidence.requestId()) + || !uuid(row, "transition_id").equals(evidence.transitionId()) + || !Arrays.equals(bytes(row, "binding_ref"), evidence.bindingRef()) + || !positive(row, "binding_generation").equals(evidence.bindingGeneration()) + || !uuid(row, "reservation_id").equals(evidence.reservation().reservationId()) + || !uuid(row, "reservation_fence").equals(evidence.reservation().reservationFence()) + || !uuid(row, "original_issuer_coverage_operation_id") + .equals(evidence.reservation().issuerCoverageOperationId()) + || !positive(row, "original_issuer_coverage_operation_fence") + .equals(evidence.reservation().issuerCoverageOperationFence()) + || !positive(row, "original_coverage_fence").equals(evidence.reservation().coverageFence()) + || !positive(row, "original_inventory_snapshot_revision") + .equals(evidence.reservation().inventorySnapshotRevision()) + || !positive(row, "original_inventory_revision") + .equals(evidence.reservation().inventoryRevision()) + || !uuid(row, "anchor_bootstrap_operation_id") + .equals(evidence.anchor().bootstrapOperationId()) + || !uuid(row, "anchor_issuer_coverage_operation_id") + .equals(evidence.anchor().issuerCoverageOperationId()) + || !positive(row, "anchor_operation_fence").equals(evidence.anchor().operationFence()) + || !positive(row, "anchor_coverage_fence").equals(evidence.anchor().coverageFence()) + || !positive(row, "anchor_inventory_snapshot_revision") + .equals(evidence.anchor().inventorySnapshotRevision()) + || !positive(row, "anchor_global_coverage_generation") + .equals(evidence.anchor().globalCoverageGeneration()) + || !positive(row, "issuer_control_epoch").equals(evidence.anchor().controlEpoch()) + || !uuid(row, "local_member_operation_id").equals(evidence.memberOperation().operationId()) + || !positive(row, "local_member_operation_fence") + .equals(evidence.memberOperation().operationFence()) + || !positive(row, "local_member_generation").equals(evidence.memberOperation().generation()) + || !nonnegative(row, "physical_partition_id").equals(evidence.reservation().partitionId()) + || !text(row, "physical_field_set_digest") + .equals(evidence.physicalReadback().partitionFieldSetDigest()) + || !text(row, "sql_currentness_digest").equals(evidence.sqlCurrentnessDigest()) + || !Objects.equals(row.get("acknowledgement_schema_version", Short.class), (short) 1) + || !acknowledgement.digest().equals(text(row, "acknowledgement_digest")) + || installedAnchor == null + || !positive(installedAnchor, "global_coverage_generation") + .equals(evidence.anchor().globalCoverageGeneration()) + || !Arrays.equals( + bytes(installedAnchor, "exact_anchor_bytes"), evidence.anchor().exactBytes()) + || generationCounter == null + || nonnegative(generationCounter, "last_issued_binding_local_acknowledgement_generation") + .compareTo(evidence.issuerBindingLocalAcknowledgementGeneration()) + < 0 + || operation == null + || !"PENDING_PHYSICAL_PROOF".equals(text(operation, "member_status")) + || !Objects.equals(operation.get("member_schema_version", Short.class), (short) 2) + || !text(operation, "issuer_id").equals(evidence.issuerId()) + || !uuid(operation, "request_id").equals(evidence.requestId()) + || !uuid(operation, "transition_id").equals(evidence.transitionId()) + || !uuid(operation, "candidate_account_index_fence") + .equals(evidence.candidateAccountIndexFence()) + || !Arrays.equals(bytes(operation, "binding_ref"), evidence.bindingRef()) + || !positive(operation, "binding_generation").equals(evidence.bindingGeneration()) + || !uuid(operation, "reservation_id").equals(evidence.reservation().reservationId()) + || !uuid(operation, "reservation_fence").equals(evidence.reservation().reservationFence()) + || !positive(operation, "original_issuer_coverage_operation_fence") + .equals(evidence.reservation().issuerCoverageOperationFence()) + || !uuid(operation, "original_issuer_coverage_operation_id") + .equals(evidence.reservation().issuerCoverageOperationId()) + || !positive(operation, "original_coverage_fence") + .equals(evidence.reservation().coverageFence()) + || !positive(operation, "original_inventory_snapshot_revision") + .equals(evidence.reservation().inventorySnapshotRevision()) + || !positive(operation, "local_inventory_snapshot_revision") + .equals(evidence.reservation().inventoryRevision()) + || !uuid(operation, "anchor_bootstrap_operation_id") + .equals(evidence.anchor().bootstrapOperationId()) + || !uuid(operation, "anchor_issuer_coverage_operation_id") + .equals(evidence.anchor().issuerCoverageOperationId()) + || !positive(operation, "anchor_operation_fence").equals(evidence.anchor().operationFence()) + || !positive(operation, "anchor_coverage_fence").equals(evidence.anchor().coverageFence()) + || !positive(operation, "anchor_issuer_inventory_snapshot_revision") + .equals(evidence.anchor().inventorySnapshotRevision()) + || !positive(operation, "anchor_control_epoch").equals(evidence.anchor().controlEpoch()) + || !Arrays.equals(bytes(operation, "exact_anchor_bytes"), evidence.anchor().exactBytes()) + || !text(operation, "exact_anchor_digest").equals(evidence.anchor().exactDigest()) + || !Arrays.equals( + bytes(operation, "anchor_layout_descriptor_bytes"), + evidence.anchor().layoutDescriptorBytes()) + || !text(operation, "anchor_layout_descriptor_digest") + .equals(evidence.anchor().layoutDescriptorDigest()) + || !Arrays.equals( + bytes(operation, "anchor_source_checkpoint_bytes"), + evidence.currentSource().checkpointBytes()) + || !text(operation, "anchor_source_checkpoint_digest") + .equals(evidence.currentSource().checkpointDigest()) + || !Arrays.equals( + operation.get("anchor_source_event_bytes", byte[].class), + evidence.currentSource().eventBytes()) + || !Objects.equals( + operation.get("anchor_source_event_digest", String.class), + evidence.currentSource().eventDigest()) + || !Arrays.equals( + bytes(operation, "anchor_incarnation_bytes"), + evidence.currentSource().incarnationBytes()) + || !text(operation, "anchor_incarnation_digest") + .equals(evidence.currentSource().incarnationDigest()) + || !uuid(operation, "operation_id").equals(evidence.memberOperation().operationId()) + || !positive(operation, "operation_fence") + .equals(evidence.memberOperation().operationFence()) + || !positive(operation, "local_member_generation") + .equals(evidence.memberOperation().generation()) + || !nonnegative(operation, "partition_id").equals(evidence.reservation().partitionId()) + || !Arrays.equals(bytes(operation, "member_value_bytes"), evidence.memberValueBytes()) + || !text(operation, "member_value_digest").equals(evidence.memberValueDigest())) { + throw unavailable( + "Stored issuer acknowledgement columns differ from their exact receipt bytes"); + } + return acknowledgement; + } + + private static ReadbackProof validateReadback( + CanonicalGameplayIssuerBindingLocalOperation operation, + CanonicalGameplayIssuerBindingLocalProjectionRepository.PreparedPartitionWork work, + CanonicalGameplayIssuerBindingLocalRedisOwner.Readback readback, + CanonicalGameplayIssuerBootstrapPartitionRedisOwner.CurrentIssuerState currentState) { + var member = operation.memberValue(); + var anchor = operation.anchor(); + if (!sameCurrentIssuerStateForOperation(operation, currentState)) { + throw unavailable("Current issuer source or incarnation differs from the installed anchor"); + } + if (!work.targetEntry().bindingPresent() + || !work.targetEntry().countsTowardCapacity() + || !"PROVISIONAL".equals(work.targetEntry().transitionStatus())) { + throw unavailable("Issuer local acknowledgement requires the current provisional binding"); + } + Map fieldSet = decodeReadback(readback.exactReadbackBytes()); + if (!Arrays.equals( + fieldSet.get( + CanonicalGameplayIssuerBootstrapPartitionPhysicalCodec.MUTATION_REVISION_FIELD), + work.currentRevision().toString().getBytes(StandardCharsets.US_ASCII))) { + throw unavailable("Physical issuer revision differs from the current committed SQL head"); + } + String bindingField = new String(member.owner().bindingRef().bytes(), StandardCharsets.UTF_8); + String capacityField = + CanonicalGameplayIssuerBootstrapPartitionPhysicalCodec.reservationField( + member.reservation().reservationId()); + byte[] bindingBytes = fieldSet.get(bindingField); + byte[] capacityBytes = fieldSet.get(capacityField); + if (!Arrays.equals(bindingBytes, operation.exactMemberValueBytes()) + || !Arrays.equals(capacityBytes, operation.exactMemberValueBytes())) { + throw unavailable("Physical issuer readback lacks the exact member and reservation fields"); + } + + int reservations = 0; + int bindings = 0; + int countedCapacity = 0; + for (Map.Entry entry : fieldSet.entrySet()) { + if (entry + .getKey() + .startsWith( + CanonicalGameplayIssuerBootstrapPartitionPhysicalCodec.RESERVATION_FIELD_PREFIX)) { + var value = CanonicalGameplayIssuerMemberV2Codec.decode(entry.getValue()); + reservations++; + if (value.reservation().lifecycle() + != CanonicalIssuerPartitionReservation.Lifecycle.RELEASED) countedCapacity++; + } else if (!entry + .getKey() + .equals(CanonicalGameplayIssuerBootstrapPartitionPhysicalCodec.METADATA_FIELD) + && !entry + .getKey() + .equals( + CanonicalGameplayIssuerBootstrapPartitionPhysicalCodec.MUTATION_REVISION_FIELD)) { + CanonicalGameplayIssuerMemberV2Codec.decode(entry.getValue()); + bindings++; + } + } + var proof = work.baselineProof(); + byte[] readbackBytes = readback.exactReadbackBytes(); + var physical = + new PhysicalReadback( + bindingBytes, + CanonicalGameplayIssuerMemberV2Codec.sha256(bindingBytes), + capacityBytes, + CanonicalGameplayIssuerMemberV2Codec.sha256(capacityBytes), + CanonicalGameplayIssuerMemberV2Codec.sha256(readbackBytes), + Math.toIntExact(readback.scriptOutcome()), + fieldSet.size(), + reservations, + bindings, + countedCapacity); + var capacity = + new Capacity( + member.reservation().partitionId(), + anchor.partitionCapacity(), + BigInteger.valueOf(proof.physicalCountedCapacityCount()), + BigInteger.valueOf(proof.physicalReservationCount()), + BigInteger.valueOf(proof.physicalBindingCount()), + work.partitionCapacity(), + work.aggregateCapacity(), + work.aggregateBound()); + return new ReadbackProof(physical, capacity); + } + + private static Evidence buildEvidence( + CanonicalGameplayIssuerBindingLocalOperation operation, + CanonicalGameplayIssuerBindingLocalRedisOwner.Readback readback, + CanonicalGameplayIssuerBootstrapPartitionRedisOwner.CurrentIssuerState currentState, + ReadbackProof proof, + BigInteger acknowledgementGeneration) { + var member = operation.memberValue(); + var anchor = operation.anchor(); + var stateSource = currentState.accountCheckpoint(); + byte[] sourceCheckpointBytes = stateSource.exactCheckpointBytes(); + byte[] sourceEventBytes = stateSource.latestIssuerEventBytes(); + byte[] incarnationBytes = + CanonicalGameplayIssuerInstalledAnchor.encodeIncarnation(currentState.incarnation()); + var originalReservation = member.reservation(); + var anchorTuple = member.anchor(); + return new Evidence( + operation.operationId(), + acknowledgementGeneration, + operation.request().requestId(), + operation.request().transitionId(), + operation.candidateAccountIndexFence(), + member.owner().issuerId(), + member.owner().bindingRef().bytes(), + member.bindingGeneration(), + operation.exactMemberValueBytes(), + operation.memberValueDigest(), + new Reservation( + originalReservation.reservationId(), + originalReservation.transitionId(), + originalReservation.reservationFence(), + originalReservation.partitionId(), + originalReservation.lifecycle().name(), + originalReservation.issuerCoverageOperationId(), + originalReservation.issuerCoverageOperationFence(), + originalReservation.coverageFence(), + originalReservation.inventorySnapshotRevision(), + originalReservation.inventoryRevision()), + new Anchor( + anchor.bootstrapOperationId(), + anchorTuple.issuerCoverageOperationId(), + anchorTuple.operationFence(), + anchorTuple.coverageFence(), + anchorTuple.issuerInventorySnapshotRevision(), + anchor.globalCoverageGeneration(), + anchor.controlEpoch(), + anchor.layoutVersion(), + anchor.partitionCount(), + anchor.partitionCapacity(), + anchor.mappingIdentity(), + anchor.layoutDescriptorBytes(), + anchor.layoutDescriptorDigest(), + anchor.exactAnchorBytes(), + anchor.exactAnchorDigest()), + new MemberOperation( + member.memberOperation().operationId(), + member.memberOperation().operationFence(), + member.memberOperation().coverageGeneration()), + new CurrentSource( + stateSource.issuerAuthGeneration(), + sourceCheckpointBytes, + stateSource.checkpointDigest(), + sourceEventBytes, + stateSource.latestIssuerEventDigest(), + incarnationBytes, + CanonicalGameplayIssuerMemberV2Codec.sha256(incarnationBytes)), + proof.physical(), + proof.capacity(), + sha256Hex(readback.sqlCurrentnessDigest())); + } + + private record ReadbackProof(PhysicalReadback physical, Capacity capacity) {} + + private static Map decodeReadback(byte[] readbackBytes) { + Map fields = + CanonicalGameplayIssuerBootstrapCoverageRepository.decodeFieldSet(readbackBytes); + if (fields.isEmpty() || fields.size() > MAX_FIELD_COUNT) { + throw unavailable("Physical issuer readback field count is outside its bound"); + } + return fields; + } + + private static void requireEligibleCandidate( + CanonicalGameplayIssuerBindingLocalProjectionRepository.PreparedPartitionWork work) { + if (!work.targetEntry().bindingPresent() + || !work.targetEntry().countsTowardCapacity() + || !"PROVISIONAL".equals(work.targetEntry().transitionStatus())) { + throw unavailable("Only the original nonterminal binding may receive a local issuer ACK"); + } + } + + private static void requireSameOperation( + Evidence evidence, CanonicalGameplayIssuerBindingLocalOperation operation) { + if (!evidence.operationId().equals(operation.operationId()) + || !evidence.requestId().equals(operation.request().requestId()) + || !evidence.transitionId().equals(operation.request().transitionId()) + || !evidence.reservation().reservationId().equals(operation.reservation().reservationId()) + || !evidence.anchor().exactDigest().equals(operation.anchor().exactAnchorDigest()) + || !Arrays.equals(evidence.memberValueBytes(), operation.exactMemberValueBytes())) { + throw unavailable( + "Retained issuer acknowledgement differs from the exact original operation"); + } + } + + private static void requireSameCurrentSources( + Evidence evidence, + CanonicalGameplayIssuerBindingLocalOperation operation, + CanonicalGameplayIssuerBootstrapPartitionRedisOwner.CurrentIssuerState currentState) { + if (!sameCurrentIssuerStateForOperation(operation, currentState) + || !evidence.anchor().exactDigest().equals(operation.anchor().exactAnchorDigest()) + || !evidence + .currentSource() + .checkpointDigest() + .equals(currentState.accountCheckpoint().checkpointDigest()) + || !Arrays.equals( + evidence.currentSource().checkpointBytes(), + currentState.accountCheckpoint().exactCheckpointBytes()) + || !Objects.equals( + evidence.currentSource().eventDigest(), + currentState.accountCheckpoint().latestIssuerEventDigest()) + || !Arrays.equals( + evidence.currentSource().eventBytes(), + currentState.accountCheckpoint().latestIssuerEventBytes()) + || !Arrays.equals( + evidence.currentSource().incarnationBytes(), + CanonicalGameplayIssuerInstalledAnchor.encodeIncarnation(currentState.incarnation()))) { + throw unavailable( + "Retained issuer acknowledgement is stale for current source or incarnation"); + } + } + + private static void requireReadbackTargetStillMatches( + Evidence evidence, CanonicalGameplayIssuerBindingLocalRedisOwner.Readback readback) { + if (!readback.operationId().equals(evidence.operationId())) { + throw unavailable("Physical issuer readback belongs to a different local operation"); + } + Map fields = decodeReadback(readback.exactReadbackBytes()); + var prior = evidence.physicalReadback(); + var member = CanonicalGameplayIssuerMemberV2Codec.decode(evidence.memberValueBytes()); + byte[] binding = + fields.get(new String(member.owner().bindingRef().bytes(), StandardCharsets.UTF_8)); + byte[] capacity = + fields.get( + CanonicalGameplayIssuerBootstrapPartitionPhysicalCodec.reservationField( + evidence.reservation().reservationId())); + if (!Arrays.equals(binding, prior.bindingValueBytes()) + || !Arrays.equals(capacity, prior.capacityValueBytes())) { + throw unavailable("Physical issuer retry differs from the retained target readback"); + } + } + + private void requireCurrentIssuerSource( + CanonicalGameplayIssuerBindingLocalOperation operation, + CanonicalGameplayIssuerBootstrapPartitionRedisOwner.CurrentIssuerState state) { + if (!sameCurrentIssuerStateForOperation(operation, state)) { + throw unavailable( + "Current Account source or issuer incarnation differs from the installed anchor"); + } + } + + private static boolean sameCurrentIssuerStateForOperation( + CanonicalGameplayIssuerBindingLocalOperation operation, + CanonicalGameplayIssuerBootstrapPartitionRedisOwner.CurrentIssuerState state) { + var anchor = operation.anchor(); + var source = state.accountCheckpoint(); + return source.issuerId().equals(anchor.issuerId()) + && source.issuerAuthGeneration().equals(anchor.issuerAuthGeneration()) + && source.checkpointDigest().equals(anchor.sourceCheckpointDigest()) + && Arrays.equals(source.exactCheckpointBytes(), anchor.sourceCheckpointBytes()) + && Objects.equals(source.latestIssuerEventDigest(), anchor.sourceEventDigest()) + && Arrays.equals(source.latestIssuerEventBytes(), anchor.sourceEventBytes()) + && Arrays.equals( + CanonicalGameplayIssuerInstalledAnchor.encodeIncarnation(state.incarnation()), + anchor.incarnationBytes()); + } + + private boolean sameCurrentIssuerState( + CanonicalGameplayIssuerBootstrapPartitionRedisOwner.CurrentIssuerState left, + CanonicalGameplayIssuerBootstrapPartitionRedisOwner.CurrentIssuerState right) { + return left.accountCheckpoint().issuerId().equals(right.accountCheckpoint().issuerId()) + && left.accountCheckpoint() + .issuerAuthGeneration() + .equals(right.accountCheckpoint().issuerAuthGeneration()) + && Arrays.equals( + left.accountCheckpoint().exactCheckpointBytes(), + right.accountCheckpoint().exactCheckpointBytes()) + && left.accountCheckpoint() + .checkpointDigest() + .equals(right.accountCheckpoint().checkpointDigest()) + && Arrays.equals( + left.accountCheckpoint().latestIssuerEventBytes(), + right.accountCheckpoint().latestIssuerEventBytes()) + && Objects.equals( + left.accountCheckpoint().latestIssuerEventDigest(), + right.accountCheckpoint().latestIssuerEventDigest()) + && Arrays.equals( + CanonicalGameplayIssuerInstalledAnchor.encodeIncarnation(left.incarnation()), + CanonicalGameplayIssuerInstalledAnchor.encodeIncarnation(right.incarnation())); + } + + private CanonicalGameplayIssuerBootstrapPartitionRedisOwner.CurrentIssuerState + readCurrentIssuerState(String boundary) { + try { + requireNoAmbientTransaction(); + var state = currentIssuerStateSource.readFreshCurrentState(); + requireNoAmbientTransaction(); + if (state == null) throw unavailable("Current issuer source returned no state " + boundary); + return state; + } catch (RuntimeException failure) { + if (failure instanceof IllegalStateException state + && state.getMessage() != null + && state.getMessage().contains("Issuer binding-local acknowledgement is unavailable")) { + throw state; + } + throw unavailable("Could not read current issuer source " + boundary, failure); + } + } + + private static BigInteger positive(Record row, String field) { + BigInteger value = number(row, field); + if (value.signum() <= 0) throw unavailable(field + " must be positive"); + return value; + } + + private static BigInteger nonnegative(Record row, String field) { + BigInteger value = number(row, field); + if (value.signum() < 0) throw unavailable(field + " must not be negative"); + return value; + } + + private static BigInteger number(Record row, String field) { + Object value = row.get(field); + if (!(value instanceof Number number)) throw unavailable(field + " is missing or nonnumeric"); + try { + if (number instanceof BigDecimal decimal) return decimal.toBigIntegerExact(); + return BigInteger.valueOf(number.longValue()); + } catch (ArithmeticException malformed) { + throw unavailable(field + " is not an exact integer", malformed); + } + } + + private static UUID uuid(Record row, String field) { + UUID value = row.get(field, UUID.class); + if (value == null || value.equals(new UUID(0L, 0L))) throw unavailable(field + " is missing"); + return value; + } + + private static String text(Record row, String field) { + String value = row.get(field, String.class); + if (value == null || value.isEmpty()) throw unavailable(field + " is missing"); + return value; + } + + private static byte[] bytes(Record row, String field) { + byte[] value = row.get(field, byte[].class); + if (value == null || value.length == 0) throw unavailable(field + " is missing"); + return value.clone(); + } + + private static String sha256Hex(byte[] digestBytes) { + if (digestBytes.length != 32) throw unavailable("SQL currentness digest is not SHA-256"); + return "sha256:" + java.util.HexFormat.of().formatHex(digestBytes); + } + + private void requireNoAmbientTransaction() { + if (TransactionSynchronizationManager.isActualTransactionActive() + || TransactionSynchronizationManager.isSynchronizationActive()) { + throw unavailable("Issuer acknowledgement owner cannot join an ambient SQL transaction"); + } + try { + dsl.connectionResult( + connection -> { + if (!connection.getAutoCommit()) { + throw unavailable("Issuer acknowledgement owner cannot join a jOOQ transaction"); + } + return Boolean.TRUE; + }); + } catch (RuntimeException failure) { + if (failure instanceof IllegalStateException state + && state.getMessage() != null + && state.getMessage().contains("Issuer binding-local acknowledgement is unavailable")) { + throw state; + } + throw unavailable("Issuer acknowledgement SQL connection state is unavailable", failure); + } + } + + private static IllegalStateException unavailable(String message) { + return new IllegalStateException( + "Issuer binding-local acknowledgement is unavailable: " + message); + } + + private static IllegalStateException unavailable(String message, Throwable cause) { + return new IllegalStateException( + "Issuer binding-local acknowledgement is unavailable: " + message, cause); + } +} diff --git a/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/repository/CanonicalGameplayIssuerBindingLocalProjectionRepository.java b/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/repository/CanonicalGameplayIssuerBindingLocalProjectionRepository.java index 36a084d641..f15eb9d991 100644 --- a/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/repository/CanonicalGameplayIssuerBindingLocalProjectionRepository.java +++ b/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/repository/CanonicalGameplayIssuerBindingLocalProjectionRepository.java @@ -94,6 +94,7 @@ private PreparedPartitionWork readPreparedPartitionWork( transaction, target, anchor, + before, prepareAddMutation, requireCurrentTargetAccountControl); }); @@ -103,6 +104,25 @@ private PreparedPartitionWork readPreparedPartitionWork( return work; } + /** + * Rebuilds the exact SQL proof inside a caller-owned transaction that already holds the + * inventory-clock lock. The caller must obtain a fresh issuer source before entering SQL and + * re-read it after commit; this method performs no remote work and never holds SQL over Redis. + */ + PreparedPartitionWork readPreparedPartitionWorkInTransaction( + DSLContext transaction, + CanonicalGameplayIssuerBindingLocalOperation target, + CanonicalGameplayIssuerBootstrapPartitionRedisOwner.CurrentIssuerState currentState) { + Objects.requireNonNull(transaction, "transaction"); + Objects.requireNonNull(target, "target"); + requireCurrentSourceMatches(target.anchor(), currentState); + CanonicalGameplayIssuerInstalledAnchor anchor = + CanonicalGameplayIssuerBootstrapCoverageRepository + .readInstalledAnchorForBindingPreparationInTransaction(transaction, currentState); + requireSameAnchor(target.anchor(), anchor); + return prepareInTransaction(transaction, target, anchor, currentState, false, true); + } + /** Re-reads the durable set and all currentness inputs after the Redis round trip. */ void requireStillCurrent(PreparedPartitionWork expected) { Objects.requireNonNull(expected, "expected"); @@ -131,8 +151,15 @@ private PreparedPartitionWork prepareInTransaction( DSLContext transaction, CanonicalGameplayIssuerBindingLocalOperation target, CanonicalGameplayIssuerInstalledAnchor anchor, + CanonicalGameplayIssuerBootstrapPartitionRedisOwner.CurrentIssuerState currentState, boolean prepareAddMutation, boolean requireCurrentTargetAccountControl) { + if (requireCurrentTargetAccountControl) { + // ADD and admitting ACK join live OPEN control. Historical release/retirement reads + // retain their original source guards without claiming new admission authority. + CanonicalGameplayIssuerAdmissionControlRepository.requireOpenInTransaction( + transaction, anchor, currentState); + } BigInteger targetPartition = target.reservation().partitionId(); CanonicalGameplayIssuerPartitionMutationRepository.PartitionMutationHead mutationHead = CanonicalGameplayIssuerPartitionMutationRepository.readHeadInTransaction( diff --git a/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/repository/CanonicalGameplayIssuerBindingLocalRedisOwner.java b/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/repository/CanonicalGameplayIssuerBindingLocalRedisOwner.java index dec5b5e131..a0277e09fa 100644 --- a/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/repository/CanonicalGameplayIssuerBindingLocalRedisOwner.java +++ b/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/repository/CanonicalGameplayIssuerBindingLocalRedisOwner.java @@ -109,7 +109,7 @@ public Readback projectAndRead(CanonicalGameplayIssuerBindingLocalOperation oper readExactPhysicalState(exactPartitionKey(work), work, work.currentRevision()); requireFreshCurrentState(work); projectionRepository.requireStillCurrent(work); - return new Readback(operation, 3L, currentReadback); + return new Readback(operation, 3L, currentReadback, work.sqlCurrentnessDigest()); } if (!work.targetEntry().operationId().equals(operation.operationId())) throw unavailable(); if (!mutation.mutationId().equals(work.pendingMutationId()) @@ -129,7 +129,8 @@ public Readback projectAndRead(CanonicalGameplayIssuerBindingLocalOperation oper requireFreshCurrentState(work); projectionRepository.requireStillCurrent(work); projectionRepository.completePhysicalMutation(mutation, readbackBytes); - return new Readback(operation, result, readbackBytes); + var completedWork = projectionRepository.readPreparedPartitionWork(operation); + return new Readback(operation, result, readbackBytes, completedWork.sqlCurrentnessDigest()); } catch (RuntimeException failure) { if (failure instanceof IllegalStateException state && state.getMessage() != null @@ -409,15 +410,22 @@ public static final class Readback { private final CanonicalGameplayIssuerBindingLocalOperation operation; private final long scriptOutcome; private final byte[] exactReadbackBytes; + private final byte[] sqlCurrentnessDigest; private Readback( CanonicalGameplayIssuerBindingLocalOperation operation, long scriptOutcome, - byte[] exactReadbackBytes) { + byte[] exactReadbackBytes, + byte[] sqlCurrentnessDigest) { this.operation = Objects.requireNonNull(operation, "operation"); this.scriptOutcome = scriptOutcome; this.exactReadbackBytes = Objects.requireNonNull(exactReadbackBytes, "exactReadbackBytes").clone(); + this.sqlCurrentnessDigest = + Objects.requireNonNull(sqlCurrentnessDigest, "sqlCurrentnessDigest").clone(); + if (this.sqlCurrentnessDigest.length != 32) { + throw new IllegalArgumentException("SQL issuer currentness digest must be SHA-256"); + } } public CanonicalGameplayIssuerBindingLocalOperation operation() { @@ -435,5 +443,9 @@ public long scriptOutcome() { public byte[] exactReadbackBytes() { return exactReadbackBytes.clone(); } + + byte[] sqlCurrentnessDigest() { + return sqlCurrentnessDigest.clone(); + } } } diff --git a/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/repository/CanonicalGameplayProtectedIncarnationReceiver.java b/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/repository/CanonicalGameplayProtectedIncarnationReceiver.java index 7f7b2c1d95..8f590f928d 100644 --- a/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/repository/CanonicalGameplayProtectedIncarnationReceiver.java +++ b/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/repository/CanonicalGameplayProtectedIncarnationReceiver.java @@ -38,6 +38,8 @@ */ final class CanonicalGameplayProtectedIncarnationReceiver { private static final String OBSERVATION_SCHEMA = "firemud.gs.protected-incarnation-read/v1"; + private static final String INITIAL_OBSERVATION_SCHEMA = + "firemud.gs.protected-initial-account-barrier-read/v1"; private static final String INCARNATION_BINDING_SCHEMA = "firemud.gs.protected-incarnation-binding/v1"; private static final Pattern KEY_ID = Pattern.compile("[A-Za-z0-9_-]{1,64}"); @@ -67,6 +69,20 @@ final class CanonicalGameplayProtectedIncarnationReceiver { "inventorySnapshotRevision", "cohortDigest", "barrierTargetDigest"); + private static final Set INITIAL_OWNER_FIELDS = + Set.of( + "ownerKind", + "initializerId", + "originalRequestId", + "originalCallerContextId", + "originalAttemptFence", + "accountId", + "sourceControlState", + "sourceControlEpoch", + "inventorySnapshotRevision", + "accountLoginEvidenceDigest", + "sourceControlDigest", + "targetDigest"); private static final Set TARGET_FIELDS = Set.of( "targetOrdinal", @@ -95,6 +111,7 @@ final class CanonicalGameplayProtectedIncarnationReceiver { .build(); private final CanonicalGameplayAccountAdmissionBarrierRepository intentRepository; + private final CanonicalGameplayAccountInitialBarrierInitializerRepository initialRepository; private final CanonicalGameplayTenantGameplayTagRepository tenantTagRepository; private final ProtectedObservationChannel observationChannel; private final TrustedConfiguration trustedConfiguration; @@ -109,6 +126,7 @@ final class CanonicalGameplayProtectedIncarnationReceiver { Clock clock) { this( intentRepository, + null, tenantTagRepository, observationChannel, trustedConfiguration, @@ -123,7 +141,42 @@ final class CanonicalGameplayProtectedIncarnationReceiver { TrustedConfiguration trustedConfiguration, Clock clock, SecureRandom secureRandom) { + this( + intentRepository, + null, + tenantTagRepository, + observationChannel, + trustedConfiguration, + clock, + secureRandom); + } + + CanonicalGameplayProtectedIncarnationReceiver( + CanonicalGameplayAccountInitialBarrierInitializerRepository initialRepository, + CanonicalGameplayTenantGameplayTagRepository tenantTagRepository, + ProtectedObservationChannel observationChannel, + TrustedConfiguration trustedConfiguration, + Clock clock) { + this( + null, + initialRepository, + tenantTagRepository, + observationChannel, + trustedConfiguration, + clock, + new SecureRandom()); + } + + private CanonicalGameplayProtectedIncarnationReceiver( + CanonicalGameplayAccountAdmissionBarrierRepository intentRepository, + CanonicalGameplayAccountInitialBarrierInitializerRepository initialRepository, + CanonicalGameplayTenantGameplayTagRepository tenantTagRepository, + ProtectedObservationChannel observationChannel, + TrustedConfiguration trustedConfiguration, + Clock clock, + SecureRandom secureRandom) { this.intentRepository = intentRepository; + this.initialRepository = initialRepository; this.tenantTagRepository = tenantTagRepository; this.observationChannel = observationChannel; this.trustedConfiguration = trustedConfiguration; @@ -143,9 +196,24 @@ VerifiedIncarnation observeForFenceTarget(UUID operationId, long targetOrdinal) if (targetOrdinal < 0) { throw new IllegalArgumentException("targetOrdinal must not be negative"); } - requireAvailable(); - + requireAvailable(OwnerKind.ACCOUNT_FENCE); CurrentContext before = loadCurrentContext(operationId, targetOrdinal); + return observeCurrentContext(before, () -> loadCurrentContext(operationId, targetOrdinal)); + } + + /** + * Reads a separate INITIAL original-attempt context under the same trusted signature verifier. + */ + VerifiedIncarnation observeForInitialAccountBarrier(UUID originalRequestId) { + requireNoAmbientTransaction(); + requireNonNil(originalRequestId, "originalRequestId"); + requireAvailable(OwnerKind.INITIAL_ACCOUNT_BARRIER); + CurrentContext before = loadInitialCurrentContext(originalRequestId); + return observeCurrentContext(before, () -> loadInitialCurrentContext(originalRequestId)); + } + + private VerifiedIncarnation observeCurrentContext( + CurrentContext before, java.util.function.Supplier reload) { long issuedAt = clock.millis(); if (issuedAt <= 0L) { throw new ObservationUnavailableException("Protected observation clock is unavailable"); @@ -184,9 +252,8 @@ VerifiedIncarnation observeForFenceTarget(UUID operationId, long targetOrdinal) if (signed == null) { throw new ObservationUnavailableException("Protected observation source returned no bytes"); } - VerifiedPayload payload = verifyObservation(signed, request, before); - CurrentContext after = loadCurrentContext(operationId, targetOrdinal); + CurrentContext after = reload.get(); if (!before.equals(after)) { throw new ObservationRejectedException("Protected observation owner context changed"); } @@ -198,7 +265,6 @@ VerifiedIncarnation observeForFenceTarget(UUID operationId, long targetOrdinal) || payload.expiresAtEpochMillis() != expiresAt) { throw new ObservationRejectedException("Protected observation is expired or out of window"); } - String incarnationDigest = incarnationDigest(trustedConfiguration); return new VerifiedIncarnation( before, trustedConfiguration.acceptedAttestationDigest(), @@ -208,11 +274,12 @@ VerifiedIncarnation observeForFenceTarget(UUID operationId, long targetOrdinal) payload.observedAtEpochMillis(), expiresAt, payload.payloadDigest(), - incarnationDigest); + incarnationDigest(trustedConfiguration)); } - private void requireAvailable() { - if (intentRepository == null + private void requireAvailable(OwnerKind ownerKind) { + if ((ownerKind == OwnerKind.ACCOUNT_FENCE && intentRepository == null) + || (ownerKind == OwnerKind.INITIAL_ACCOUNT_BARRIER && initialRepository == null) || tenantTagRepository == null || observationChannel == null || trustedConfiguration == null @@ -260,6 +327,7 @@ private CurrentContext loadCurrentContext(UUID operationId, long targetOrdinal) } CanonicalGameplaySessionRedisKeys.accountAdmissionBarrier(assignment); return new CurrentContext( + OwnerKind.ACCOUNT_FENCE, intent.operationId(), intent.requestId(), intent.accountId(), @@ -273,7 +341,54 @@ private CurrentContext loadCurrentContext(UUID operationId, long targetOrdinal) target.playableStateNamespaceId(), assignment.tenantGameplayTag(), assignment.workloadNamespace(), - assignment.allocationVersion()); + assignment.allocationVersion(), + null, + 0L, + null, + null, + null, + null); + } + + private CurrentContext loadInitialCurrentContext(UUID originalRequestId) { + requireNoAmbientTransaction(); + CanonicalGameplayAccountInitialBarrierInitializerRepository.InitialObservationContext context = + initialRepository.readCurrentObservationContext(originalRequestId); + CanonicalGameplayTenantGameplayTagRepository.Assignment assignment = + tenantTagRepository.assignmentForInitialBarrierTarget(originalRequestId); + CanonicalGameplayAccountInitialBarrierKey.forTarget( + assignment, context.initializerId(), context.originalRequestId()); + if (!assignment.isInitialBarrierTarget() + || !context.initializerId().equals(assignment.initialBarrierInitializerId()) + || !context.originalRequestId().equals(assignment.initialBarrierOriginalRequestId()) + || !context.accountId().equals(assignment.accountId()) + || !context.tenantId().equals(assignment.tenantId()) + || !context.playableStateNamespaceId().equals(assignment.playableStateNamespaceId())) { + throw new ObservationRejectedException( + "Protected INITIAL observation target differs from current SQL source"); + } + return new CurrentContext( + OwnerKind.INITIAL_ACCOUNT_BARRIER, + context.initializerId(), + context.originalRequestId(), + context.accountId(), + null, + null, + context.inventorySnapshotRevision().toString(), + null, + context.targetDigest(), + 0L, + context.tenantId(), + context.playableStateNamespaceId(), + assignment.tenantGameplayTag(), + assignment.workloadNamespace(), + assignment.allocationVersion(), + context.originalCallerContextId(), + context.originalAttemptFence(), + context.sourceControlState(), + context.sourceControlEpoch().toString(), + context.accountLoginEvidenceDigest(), + context.sourceControlDigest()); } private VerifiedPayload verifyObservation( @@ -306,7 +421,11 @@ private VerifiedPayload verifyObservation( verifyDetachedSignature(publicKey, canonical, signatureBytes); requireExactFields(root, ROOT_FIELDS); - requireText(root, "schema", OBSERVATION_SCHEMA); + String expectedSchema = + expected.ownerKind() == OwnerKind.ACCOUNT_FENCE + ? OBSERVATION_SCHEMA + : INITIAL_OBSERVATION_SCHEMA; + requireText(root, "schema", expectedSchema); requireText(root, "attestorBinding", trustedConfiguration.attestorBinding()); requireText(root, "attestorKeyId", keyId); requireText(root, "acceptedAttestationDigest", request.acceptedAttestationDigest()); @@ -322,16 +441,36 @@ private VerifiedPayload verifyObservation( } JsonNode owner = requiredObject(root, "owner"); - requireExactFields(owner, OWNER_FIELDS); - requireText(owner, "operationId", expected.operationId().toString()); - requireText(owner, "requestId", expected.requestId().toString()); - requireText(owner, "accountId", expected.accountId().toString()); - requireText(owner, "operationFence", expected.operationFence()); - requireText( - owner, "plannedAccountAdmissionFence", expected.plannedAccountAdmissionFence().toString()); - requireText(owner, "inventorySnapshotRevision", expected.inventorySnapshotRevision()); - requireText(owner, "cohortDigest", expected.cohortDigest()); - requireText(owner, "barrierTargetDigest", expected.barrierTargetDigest()); + if (expected.ownerKind() == OwnerKind.ACCOUNT_FENCE) { + requireExactFields(owner, OWNER_FIELDS); + requireText(owner, "operationId", expected.operationId().toString()); + requireText(owner, "requestId", expected.requestId().toString()); + requireText(owner, "accountId", expected.accountId().toString()); + requireText(owner, "operationFence", expected.operationFence()); + requireText( + owner, + "plannedAccountAdmissionFence", + expected.plannedAccountAdmissionFence().toString()); + requireText(owner, "inventorySnapshotRevision", expected.inventorySnapshotRevision()); + requireText(owner, "cohortDigest", expected.cohortDigest()); + requireText(owner, "barrierTargetDigest", expected.barrierTargetDigest()); + } else { + requireExactFields(owner, INITIAL_OWNER_FIELDS); + requireText(owner, "ownerKind", OwnerKind.INITIAL_ACCOUNT_BARRIER.name()); + requireText(owner, "initializerId", expected.operationId().toString()); + requireText(owner, "originalRequestId", expected.requestId().toString()); + requireText(owner, "originalCallerContextId", expected.originalCallerContextId().toString()); + if (requiredPositiveLong(owner, "originalAttemptFence") != expected.originalAttemptFence()) { + throw new ObservationRejectedException("Protected INITIAL attempt fence differs"); + } + requireText(owner, "accountId", expected.accountId().toString()); + requireText(owner, "sourceControlState", expected.sourceControlState()); + requireText(owner, "sourceControlEpoch", expected.sourceControlEpoch()); + requireText(owner, "inventorySnapshotRevision", expected.inventorySnapshotRevision()); + requireText(owner, "accountLoginEvidenceDigest", expected.accountLoginEvidenceDigest()); + requireText(owner, "sourceControlDigest", expected.sourceControlDigest()); + requireText(owner, "targetDigest", expected.barrierTargetDigest()); + } JsonNode target = requiredObject(root, "target"); requireExactFields(target, TARGET_FIELDS); @@ -403,7 +542,11 @@ private static boolean isCanonicalNodeOrder(List nodes) { return sorted.equals(nodes); } - private static void requireNoAmbientTransaction() { + private void requireNoAmbientTransaction() { + if (initialRepository != null) { + initialRepository.requireNoAmbientTransaction(); + return; + } if (TransactionSynchronizationManager.isActualTransactionActive() || TransactionSynchronizationManager.isSynchronizationActive()) { throw new IllegalStateException( @@ -798,8 +941,14 @@ private static void requireDigestValue(String value, String field) { } } - /** Current owner and exact target tuple obtained from the actual SQL owners. */ + enum OwnerKind { + ACCOUNT_FENCE, + INITIAL_ACCOUNT_BARRIER + } + + /** Discriminated current owner and exact target tuple obtained from the actual SQL owners. */ record CurrentContext( + OwnerKind ownerKind, UUID operationId, UUID requestId, UUID accountId, @@ -813,7 +962,44 @@ record CurrentContext( UUID playableStateNamespaceId, String tenantGameplayTag, String workloadNamespace, - int allocationVersion) {} + int allocationVersion, + UUID originalCallerContextId, + long originalAttemptFence, + String sourceControlState, + String sourceControlEpoch, + String accountLoginEvidenceDigest, + String sourceControlDigest) { + CurrentContext { + Objects.requireNonNull(ownerKind, "ownerKind"); + Objects.requireNonNull(operationId, "operationId"); + Objects.requireNonNull(requestId, "requestId"); + Objects.requireNonNull(accountId, "accountId"); + Objects.requireNonNull(tenantId, "tenantId"); + Objects.requireNonNull(playableStateNamespaceId, "playableStateNamespaceId"); + Objects.requireNonNull(tenantGameplayTag, "tenantGameplayTag"); + Objects.requireNonNull(workloadNamespace, "workloadNamespace"); + if (ownerKind == OwnerKind.ACCOUNT_FENCE) { + Objects.requireNonNull(plannedAccountAdmissionFence, "plannedAccountAdmissionFence"); + Objects.requireNonNull(operationFence, "operationFence"); + Objects.requireNonNull(cohortDigest, "cohortDigest"); + Objects.requireNonNull(barrierTargetDigest, "barrierTargetDigest"); + } else { + Objects.requireNonNull(originalCallerContextId, "originalCallerContextId"); + Objects.requireNonNull(sourceControlState, "sourceControlState"); + Objects.requireNonNull(accountLoginEvidenceDigest, "accountLoginEvidenceDigest"); + Objects.requireNonNull(sourceControlDigest, "sourceControlDigest"); + if (originalAttemptFence <= 0L + || operationFence != null + || plannedAccountAdmissionFence != null + || !"NO_ACTIVE_ACCOUNT_WIDE_FLOW".equals(sourceControlState) + || sourceControlEpoch == null + || !sourceControlEpoch.matches("0|[1-9][0-9]{0,255}")) { + throw new IllegalArgumentException( + "INITIAL owner context is not the positively read NO_ACTIVE arm"); + } + } + } + } private record VerifiedPayload( String observationNonce, @@ -858,6 +1044,42 @@ UUID operationId() { return context.operationId(); } + OwnerKind ownerKind() { + return context.ownerKind(); + } + + UUID requestId() { + return context.requestId(); + } + + UUID originalCallerContextId() { + return context.originalCallerContextId(); + } + + long originalAttemptFence() { + return context.originalAttemptFence(); + } + + String sourceControlState() { + return context.sourceControlState(); + } + + String sourceControlEpoch() { + return context.sourceControlEpoch(); + } + + String inventorySnapshotRevision() { + return context.inventorySnapshotRevision(); + } + + String accountLoginEvidenceDigest() { + return context.accountLoginEvidenceDigest(); + } + + String sourceControlDigest() { + return context.sourceControlDigest(); + } + long targetOrdinal() { return context.targetOrdinal(); } diff --git a/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/repository/CanonicalGameplaySessionRedisKeys.java b/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/repository/CanonicalGameplaySessionRedisKeys.java index bdcdeb62a1..abc6adbe8e 100644 --- a/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/repository/CanonicalGameplaySessionRedisKeys.java +++ b/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/repository/CanonicalGameplaySessionRedisKeys.java @@ -53,6 +53,28 @@ public static String accountAdmissionBarrier( throw new IllegalArgumentException( "Account admission barrier keys require a persisted acquisition-intent target"); } + return accountAdmissionBarrierKey(assignment); + } + + /** Builds the same canonical key only for one persisted original-attempt INITIAL target. */ + static String initialAccountAdmissionBarrier( + CanonicalGameplayTenantGameplayTagRepository.Assignment assignment, + java.util.UUID expectedInitializerId, + java.util.UUID expectedOriginalRequestId) { + Objects.requireNonNull(assignment, "assignment"); + Objects.requireNonNull(expectedInitializerId, "expected initializer id"); + Objects.requireNonNull(expectedOriginalRequestId, "expected original request id"); + if (!assignment.isInitialBarrierTarget() + || !expectedInitializerId.equals(assignment.initialBarrierInitializerId()) + || !expectedOriginalRequestId.equals(assignment.initialBarrierOriginalRequestId())) { + throw new IllegalArgumentException( + "INITIAL account admission barrier keys require their persisted original target"); + } + return accountAdmissionBarrierKey(assignment); + } + + private static String accountAdmissionBarrierKey( + CanonicalGameplayTenantGameplayTagRepository.Assignment assignment) { return "session:game:account-admission:{" + tag(assignment) + "}:" diff --git a/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/repository/CanonicalGameplayTenantGameplayTagRepository.java b/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/repository/CanonicalGameplayTenantGameplayTagRepository.java index 9a34cf46f7..ee3723df96 100644 --- a/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/repository/CanonicalGameplayTenantGameplayTagRepository.java +++ b/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/repository/CanonicalGameplayTenantGameplayTagRepository.java @@ -128,6 +128,92 @@ public Assignment assignmentForBarrierTarget(UUID operationId, long targetOrdina }); } + /** Resolves topology only for the persisted exact original-attempt INITIAL target. */ + Assignment assignmentForInitialBarrierTarget(UUID originalRequestId) { + requireNonNil(originalRequestId, "originalRequestId"); + return dsl.transactionResult( + configuration -> { + DSLContext transaction = DSL.using(configuration); + // Match the initializer owner: inventory clock, account control, initializer/target. + Record inventoryClock = + transaction.fetchOne( + "SELECT inventory_revision FROM game_session_canonical_binding_inventory_clock" + + " WHERE singleton_id = 1 FOR UPDATE"); + if (inventoryClock == null) + throw conflict("Canonical binding inventory clock is missing"); + Record locator = + transaction.fetchOne( + "SELECT account_id FROM game_session_canonical_initial_account_barrier_initializer" + + " WHERE original_request_id = ?", + originalRequestId); + if (locator == null) throw conflict("Exact original INITIAL account target is missing"); + UUID locatedAccountId = requiredUuid(locator, "account_id"); + Record control = + transaction.fetchOne( + "SELECT account_id FROM game_session_canonical_account_coverage_control" + + " WHERE account_id = ? FOR UPDATE", + locatedAccountId); + if (control == null) throw conflict("Account coverage control row is missing"); + Record row = + transaction.fetchOne( + "SELECT i.initializer_id, i.account_id, i.source_control_epoch," + + " t.target_ordinal, t.tenant_id," + + " t.playable_state_namespace_id, t.target_state, control.state AS control_state," + + " control.last_operation_fence, control.current_operation_id," + + " control.current_fence_intent_id, control.current_operation_fence," + + " control.account_admission_fence, control.historical_account_admission_fence," + + " control.coverage_fence, control.inventory_snapshot_revision," + + " control.coverage_generation" + + " FROM game_session_canonical_initial_account_barrier_initializer i" + + " JOIN game_session_canonical_initial_account_barrier_target t" + + " ON t.initializer_id = i.initializer_id" + + " AND t.original_request_id = i.original_request_id" + + " JOIN game_session_canonical_account_coverage_control control" + + " ON control.account_id = i.account_id" + + " WHERE i.original_request_id = ? AND t.target_ordinal = 0" + + " FOR UPDATE OF i, t, control", + originalRequestId); + if (row == null + || !"NO_ACTIVE_ACCOUNT_WIDE_FLOW".equals(row.get("control_state", String.class)) + || row.get("last_operation_fence", java.math.BigDecimal.class) == null + || row.get("last_operation_fence", java.math.BigDecimal.class) + .toBigIntegerExact() + .signum() + < 0 + || row.get("source_control_epoch", java.math.BigDecimal.class) == null + || !row.get("source_control_epoch", java.math.BigDecimal.class) + .toBigIntegerExact() + .equals( + row.get("last_operation_fence", java.math.BigDecimal.class) + .toBigIntegerExact()) + || row.get("current_operation_id", UUID.class) != null + || row.get("current_fence_intent_id", UUID.class) != null + || row.get("current_operation_fence") != null + || row.get("account_admission_fence", UUID.class) != null + || row.get("historical_account_admission_fence", UUID.class) != null + || row.get("coverage_fence", UUID.class) != null + || row.get("inventory_snapshot_revision") != null + || row.get("coverage_generation") != null) { + throw conflict( + "The exact INITIAL target or its positive NO_ACTIVE control is unavailable"); + } + UUID initializerId = requiredUuid(row, "initializer_id"); + UUID accountId = requiredUuid(row, "account_id"); + UUID tenantId = requiredUuid(row, "tenant_id"); + UUID namespaceId = requiredUuid(row, "playable_state_namespace_id"); + if (requiredLong(row, "target_ordinal") != 0L + || !Set.of("NEVER_DISPATCHED", "DISPATCH_POSSIBLE", "OPEN_INSTALLED") + .contains(requiredString(row, "target_state"))) { + throw conflict("The INITIAL target state is not a retained original-attempt state"); + } + requireTenantClaim(transaction, tenantId); + InitialTarget source = + new InitialTarget(initializerId, originalRequestId, accountId, tenantId, namespaceId); + return resolveMapping( + transaction, source, allocationVersion, tagFor(tenantId, allocationVersion)); + }); + } + /** * Narrow package-private collision path for native database proof. The tenant still comes from * the exact persisted transition; only the candidate output is controlled to exercise the global @@ -387,7 +473,7 @@ private static CanonicalGameplayBindingInventoryConflictException conflict(Strin return new CanonicalGameplayBindingInventoryConflictException(message); } - private sealed interface Target permits BindingTarget, BarrierTarget { + private sealed interface Target permits BindingTarget, BarrierTarget, InitialTarget { UUID tenantId(); UUID accountId(); @@ -410,6 +496,10 @@ private record BarrierTarget( UUID sourceId, long ordinal, UUID accountId, UUID tenantId, UUID namespaceId) implements Target {} + private record InitialTarget( + UUID initializerId, UUID originalRequestId, UUID accountId, UUID tenantId, UUID namespaceId) + implements Target {} + /** Owner-issued immutable mapping plus the exact SQL source needed by the key builder. */ public static final class Assignment { private final Target source; @@ -453,6 +543,18 @@ public boolean isBindingTransition() { return source instanceof BindingTarget; } + boolean isInitialBarrierTarget() { + return source instanceof InitialTarget; + } + + UUID initialBarrierInitializerId() { + return source instanceof InitialTarget initial ? initial.initializerId() : null; + } + + UUID initialBarrierOriginalRequestId() { + return source instanceof InitialTarget initial ? initial.originalRequestId() : null; + } + public UUID transitionId() { return source instanceof BindingTarget binding ? binding.sourceId() : null; } diff --git a/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/service/CanonicalGameplayAccountInitialBarrierRedisScriptContribution.java b/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/service/CanonicalGameplayAccountInitialBarrierRedisScriptContribution.java new file mode 100644 index 0000000000..d815d68614 --- /dev/null +++ b/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/service/CanonicalGameplayAccountInitialBarrierRedisScriptContribution.java @@ -0,0 +1,28 @@ +package net.firedevops.firemud.gamesession.service; + +import java.util.Collection; +import java.util.List; +import net.firedevops.firemud.common.redis.contracts.RedisScriptContribution; +import net.firedevops.firemud.common.redis.contracts.RedisScriptDescriptor; + +/** Passive descriptor for the one-key create-only INITIAL OPEN barrier script. */ +public final class CanonicalGameplayAccountInitialBarrierRedisScriptContribution + implements RedisScriptContribution { + public static final String SCRIPT_ID = "game-session.account-admission-barrier-initial-open.v1"; + public static final String RESOURCE_PATH = + "redis/lua/game-session-account-admission-barrier-initial-open.lua"; + private static final String DESCRIPTOR_PATH = + "/redis/scripts/game-session-account-admission-barrier-initial-open.json"; + + @Override + public String ownerId() { + return "game-session-service"; + } + + @Override + public Collection descriptors() { + return List.of( + CanonicalGameplayAdmissionBarrierRedisScriptDescriptorLoader.read( + DESCRIPTOR_PATH, SCRIPT_ID, "INITIAL account barrier descriptor is unavailable")); + } +} diff --git a/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/service/CanonicalGameplayAdmissionBarrierRedisScriptDescriptorLoader.java b/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/service/CanonicalGameplayAdmissionBarrierRedisScriptDescriptorLoader.java new file mode 100644 index 0000000000..74b72f2e93 --- /dev/null +++ b/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/service/CanonicalGameplayAdmissionBarrierRedisScriptDescriptorLoader.java @@ -0,0 +1,43 @@ +package net.firedevops.firemud.gamesession.service; + +import java.io.IOException; +import java.io.InputStream; +import net.firedevops.firemud.common.redis.contracts.RedisScriptDescriptor; +import tools.jackson.core.StreamReadFeature; +import tools.jackson.databind.DeserializationFeature; +import tools.jackson.databind.json.JsonMapper; + +/** + * Bounded strict descriptor reader for the manual Account INITIAL and issuer admission barriers. + */ +final class CanonicalGameplayAdmissionBarrierRedisScriptDescriptorLoader { + private static final int MAX_DESCRIPTOR_BYTES = 16 * 1024; + private static final JsonMapper JSON = + JsonMapper.builder() + .enable(StreamReadFeature.STRICT_DUPLICATE_DETECTION) + .enable(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES) + .enable(DeserializationFeature.FAIL_ON_TRAILING_TOKENS) + .build(); + + private CanonicalGameplayAdmissionBarrierRedisScriptDescriptorLoader() {} + + static RedisScriptDescriptor read(String path, String scriptId, String unavailableMessage) { + try (InputStream input = + CanonicalGameplayAdmissionBarrierRedisScriptDescriptorLoader.class.getResourceAsStream( + path)) { + if (input == null) throw new IllegalStateException(unavailableMessage); + byte[] bytes = input.readNBytes(MAX_DESCRIPTOR_BYTES + 1); + if (bytes.length == 0 || bytes.length > MAX_DESCRIPTOR_BYTES) { + throw new IllegalStateException(unavailableMessage); + } + RedisScriptDescriptor descriptor = JSON.readValue(bytes, RedisScriptDescriptor.class); + if (!"game-session-service".equals(descriptor.owner()) + || !scriptId.equals(descriptor.scriptId())) { + throw new IllegalStateException(unavailableMessage); + } + return descriptor; + } catch (IOException | RuntimeException failure) { + throw new IllegalStateException(unavailableMessage, failure); + } + } +} diff --git a/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/service/CanonicalGameplayIssuerAdmissionBarrierRedisScriptContribution.java b/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/service/CanonicalGameplayIssuerAdmissionBarrierRedisScriptContribution.java new file mode 100644 index 0000000000..ec40a8c006 --- /dev/null +++ b/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/service/CanonicalGameplayIssuerAdmissionBarrierRedisScriptContribution.java @@ -0,0 +1,39 @@ +package net.firedevops.firemud.gamesession.service; + +import java.util.Collection; +import java.util.List; +import net.firedevops.firemud.common.redis.contracts.RedisScriptContribution; +import net.firedevops.firemud.common.redis.contracts.RedisScriptDescriptor; + +/** Passive manual descriptor contribution for one-key issuer tenant barrier scripts. */ +public final class CanonicalGameplayIssuerAdmissionBarrierRedisScriptContribution + implements RedisScriptContribution { + public static final String OPEN_SCRIPT_ID = "game-session.issuer-admission-barrier-open.v1"; + public static final String CLOSE_SCRIPT_ID = "game-session.issuer-admission-barrier-close.v1"; + public static final String OPEN_RESOURCE_PATH = + "redis/lua/game-session-issuer-admission-barrier-open.lua"; + public static final String CLOSE_RESOURCE_PATH = + "redis/lua/game-session-issuer-admission-barrier-close.lua"; + private static final String OPEN_DESCRIPTOR_PATH = + "/redis/scripts/game-session-issuer-admission-barrier-open.json"; + private static final String CLOSE_DESCRIPTOR_PATH = + "/redis/scripts/game-session-issuer-admission-barrier-close.json"; + + @Override + public String ownerId() { + return "game-session-service"; + } + + @Override + public Collection descriptors() { + return List.of( + CanonicalGameplayAdmissionBarrierRedisScriptDescriptorLoader.read( + OPEN_DESCRIPTOR_PATH, + OPEN_SCRIPT_ID, + "Issuer admission barrier descriptors are unavailable"), + CanonicalGameplayAdmissionBarrierRedisScriptDescriptorLoader.read( + CLOSE_DESCRIPTOR_PATH, + CLOSE_SCRIPT_ID, + "Issuer admission barrier descriptors are unavailable")); + } +} diff --git a/services/game-session-service/src/main/resources/db/migration/V1045__canonical_issuer_binding_local_acknowledgement.sql b/services/game-session-service/src/main/resources/db/migration/V1045__canonical_issuer_binding_local_acknowledgement.sql new file mode 100644 index 0000000000..b2bf5e58ee --- /dev/null +++ b/services/game-session-service/src/main/resources/db/migration/V1045__canonical_issuer_binding_local_acknowledgement.sql @@ -0,0 +1,244 @@ +-- This receipt is separate from the immutable SQL preparation and physical schema-v2 member. +-- It acknowledges one original binding-local member/reservation readback only; it does not +-- publish issuer-wide coverage, initialize a tenant barrier, or authorize admission. +CREATE TABLE game_session_canonical_issuer_binding_local_ack_gen_counter ( + issuer_id character varying(64) NOT NULL, + last_issued_binding_local_acknowledgement_generation numeric NOT NULL, + counter_version bigint NOT NULL, + updated_at timestamp with time zone NOT NULL DEFAULT CURRENT_TIMESTAMP, + CONSTRAINT pk_gs_issuer_binding_local_ack_generation_counter PRIMARY KEY (issuer_id), + CONSTRAINT chk_gs_issuer_binding_local_ack_generation_counter CHECK ( + issuer_id COLLATE "C" = 'firemud-account-service'::character varying COLLATE "C" + AND last_issued_binding_local_acknowledgement_generation >= 0 + AND last_issued_binding_local_acknowledgement_generation = floor(last_issued_binding_local_acknowledgement_generation) + AND length(CAST(last_issued_binding_local_acknowledgement_generation AS varchar)) <= 256 + AND counter_version >= 0 + AND ((counter_version = 0 AND last_issued_binding_local_acknowledgement_generation = 0) + OR (counter_version > 0 AND last_issued_binding_local_acknowledgement_generation > 0))) +); + +CREATE TABLE game_session_canonical_issuer_binding_local_acknowledgement ( + operation_id uuid NOT NULL, + acknowledgement_generation numeric NOT NULL, + issuer_id character varying(64) NOT NULL, + request_id uuid NOT NULL, + transition_id uuid NOT NULL, + binding_ref bytea NOT NULL, + binding_generation numeric NOT NULL, + reservation_id uuid NOT NULL, + reservation_fence uuid NOT NULL, + original_issuer_coverage_operation_id uuid NOT NULL, + original_issuer_coverage_operation_fence numeric NOT NULL, + original_coverage_fence numeric NOT NULL, + original_inventory_snapshot_revision numeric NOT NULL, + original_inventory_revision numeric NOT NULL, + anchor_bootstrap_operation_id uuid NOT NULL, + anchor_issuer_coverage_operation_id uuid NOT NULL, + anchor_operation_fence numeric NOT NULL, + anchor_coverage_fence numeric NOT NULL, + anchor_inventory_snapshot_revision numeric NOT NULL, + anchor_global_coverage_generation numeric NOT NULL, + issuer_control_epoch numeric NOT NULL, + local_member_operation_id uuid NOT NULL, + local_member_operation_fence numeric NOT NULL, + local_member_generation numeric NOT NULL, + physical_partition_id numeric NOT NULL, + physical_field_set_digest character varying(71) NOT NULL, + sql_currentness_digest character varying(71) NOT NULL, + acknowledgement_schema_version smallint NOT NULL, + acknowledgement_bytes bytea NOT NULL, + acknowledgement_digest character varying(71) NOT NULL, + created_at timestamp with time zone NOT NULL DEFAULT CURRENT_TIMESTAMP, + CONSTRAINT pk_gs_issuer_binding_local_ack PRIMARY KEY (operation_id), + CONSTRAINT uq_gs_issuer_binding_local_ack_generation UNIQUE (issuer_id, acknowledgement_generation), + CONSTRAINT fk_gs_issuer_binding_local_ack_operation + FOREIGN KEY (operation_id) + REFERENCES game_session_canonical_issuer_binding_local_operation (operation_id), + CONSTRAINT uq_gs_issuer_binding_local_ack_transition UNIQUE (issuer_id, transition_id), + CONSTRAINT uq_gs_issuer_binding_local_ack_reservation UNIQUE (reservation_id), + CONSTRAINT chk_gs_issuer_binding_local_ack CHECK ( + issuer_id COLLATE "C" = 'firemud-account-service'::character varying COLLATE "C" + AND operation_id <> '00000000-0000-0000-0000-000000000000'::uuid + AND acknowledgement_generation > 0 + AND acknowledgement_generation = floor(acknowledgement_generation) + AND length(CAST(acknowledgement_generation AS varchar)) <= 256 + AND request_id <> '00000000-0000-0000-0000-000000000000'::uuid + AND transition_id <> '00000000-0000-0000-0000-000000000000'::uuid + AND request_id <> transition_id + AND octet_length(binding_ref) > 0 + AND binding_generation > 0 + AND reservation_id <> '00000000-0000-0000-0000-000000000000'::uuid + AND reservation_fence <> '00000000-0000-0000-0000-000000000000'::uuid + AND original_issuer_coverage_operation_id <> '00000000-0000-0000-0000-000000000000'::uuid + AND original_issuer_coverage_operation_fence > 0 + AND original_coverage_fence > 0 + AND original_inventory_snapshot_revision > 0 + AND original_inventory_revision > 0 + AND anchor_bootstrap_operation_id <> '00000000-0000-0000-0000-000000000000'::uuid + AND anchor_issuer_coverage_operation_id = anchor_bootstrap_operation_id + AND anchor_operation_fence > 0 + AND anchor_coverage_fence > 0 + AND anchor_operation_fence <> anchor_coverage_fence + AND anchor_inventory_snapshot_revision > 0 + AND anchor_global_coverage_generation > 0 + AND issuer_control_epoch = anchor_operation_fence + AND local_member_operation_id = operation_id + AND local_member_operation_fence > 0 + AND local_member_generation > 0 + AND physical_partition_id >= 0 + AND physical_partition_id = floor(physical_partition_id) + AND physical_field_set_digest ~ '^sha256:[0-9a-f]{64}$' + AND sql_currentness_digest ~ '^sha256:[0-9a-f]{64}$' + AND acknowledgement_schema_version = 1 + AND octet_length(acknowledgement_bytes) BETWEEN 1 AND 1048576 + AND acknowledgement_digest ~ '^sha256:[0-9a-f]{64}$') +); + +-- [jooq ignore start] +CREATE FUNCTION game_session_validate_issuer_binding_local_acknowledgement() +RETURNS trigger +LANGUAGE plpgsql +AS $$ +DECLARE + source_operation game_session_canonical_issuer_binding_local_operation%ROWTYPE; + installed_anchor game_session_canonical_issuer_installed_anchor%ROWTYPE; + generation_counter game_session_canonical_issuer_binding_local_ack_gen_counter%ROWTYPE; +BEGIN + SELECT * INTO source_operation + FROM game_session_canonical_issuer_binding_local_operation + WHERE operation_id = NEW.operation_id + FOR KEY SHARE; + IF NOT FOUND + OR source_operation.issuer_id <> NEW.issuer_id + OR source_operation.request_id <> NEW.request_id + OR source_operation.transition_id <> NEW.transition_id + OR source_operation.binding_ref <> NEW.binding_ref + OR source_operation.binding_generation <> NEW.binding_generation + OR source_operation.reservation_id <> NEW.reservation_id + OR source_operation.reservation_fence <> NEW.reservation_fence + OR source_operation.original_issuer_coverage_operation_id <> NEW.original_issuer_coverage_operation_id + OR source_operation.original_issuer_coverage_operation_fence <> NEW.original_issuer_coverage_operation_fence + OR source_operation.original_coverage_fence <> NEW.original_coverage_fence + OR source_operation.original_inventory_snapshot_revision <> NEW.original_inventory_snapshot_revision + OR source_operation.local_inventory_snapshot_revision <> NEW.original_inventory_revision + OR source_operation.anchor_bootstrap_operation_id <> NEW.anchor_bootstrap_operation_id + OR source_operation.anchor_issuer_coverage_operation_id <> NEW.anchor_issuer_coverage_operation_id + OR source_operation.anchor_operation_fence <> NEW.anchor_operation_fence + OR source_operation.anchor_coverage_fence <> NEW.anchor_coverage_fence + OR source_operation.anchor_issuer_inventory_snapshot_revision <> NEW.anchor_inventory_snapshot_revision + OR source_operation.anchor_control_epoch <> NEW.issuer_control_epoch + OR source_operation.operation_id <> NEW.local_member_operation_id + OR source_operation.operation_fence <> NEW.local_member_operation_fence + OR source_operation.local_member_generation <> NEW.local_member_generation + OR source_operation.partition_id <> NEW.physical_partition_id + OR source_operation.member_status <> 'PENDING_PHYSICAL_PROOF' + OR source_operation.member_schema_version <> 2 THEN + RAISE EXCEPTION 'issuer binding-local acknowledgement differs from its immutable original operation' + USING ERRCODE = 'check_violation'; + END IF; + + SELECT * INTO installed_anchor + FROM game_session_canonical_issuer_installed_anchor + WHERE issuer_id = NEW.issuer_id + FOR KEY SHARE; + IF NOT FOUND + OR installed_anchor.bootstrap_operation_id <> NEW.anchor_bootstrap_operation_id + OR installed_anchor.global_coverage_generation <> NEW.anchor_global_coverage_generation + OR installed_anchor.exact_anchor_bytes <> source_operation.exact_anchor_bytes THEN + RAISE EXCEPTION 'issuer binding-local acknowledgement differs from the immutable installed anchor' + USING ERRCODE = 'check_violation'; + END IF; + + SELECT * INTO generation_counter + FROM game_session_canonical_issuer_binding_local_ack_gen_counter + WHERE issuer_id = NEW.issuer_id + FOR KEY SHARE; + IF NOT FOUND + OR generation_counter.last_issued_binding_local_acknowledgement_generation <> NEW.acknowledgement_generation THEN + RAISE EXCEPTION 'issuer binding-local acknowledgement generation was not issued by its owner counter' + USING ERRCODE = 'check_violation'; + END IF; + RETURN NEW; +END; +$$; + +CREATE TRIGGER trg_gs_issuer_binding_local_ack_validate + BEFORE INSERT ON game_session_canonical_issuer_binding_local_acknowledgement + FOR EACH ROW EXECUTE FUNCTION game_session_validate_issuer_binding_local_acknowledgement(); + +CREATE FUNCTION game_session_reject_issuer_binding_local_acknowledgement_change() +RETURNS trigger +LANGUAGE plpgsql +AS $$ +BEGIN + RAISE EXCEPTION 'issuer binding-local acknowledgements are immutable' + USING ERRCODE = 'check_violation'; +END; +$$; + +CREATE TRIGGER trg_gs_issuer_binding_local_ack_immutable + BEFORE UPDATE OR DELETE ON game_session_canonical_issuer_binding_local_acknowledgement + FOR EACH ROW EXECUTE FUNCTION game_session_reject_issuer_binding_local_acknowledgement_change(); +CREATE TRIGGER trg_gs_issuer_binding_local_ack_no_truncate + BEFORE TRUNCATE ON game_session_canonical_issuer_binding_local_acknowledgement + FOR EACH STATEMENT EXECUTE FUNCTION game_session_reject_issuer_binding_local_acknowledgement_change(); + +CREATE FUNCTION game_session_reject_issuer_local_ack_gen_counter_change() +RETURNS trigger +LANGUAGE plpgsql +AS $$ +BEGIN + RAISE EXCEPTION 'issuer binding-local acknowledgement generation counter cannot be truncated' + USING ERRCODE = 'check_violation'; +END; +$$; + +CREATE FUNCTION game_session_guard_issuer_local_ack_gen_counter() +RETURNS trigger +LANGUAGE plpgsql +AS $$ +BEGIN + IF TG_OP = 'DELETE' THEN + RAISE EXCEPTION 'issuer binding-local acknowledgement generation counter cannot be deleted' + USING ERRCODE = 'check_violation'; + END IF; + IF NEW.issuer_id IS DISTINCT FROM OLD.issuer_id + OR NEW.counter_version <> OLD.counter_version + 1 + OR NEW.last_issued_binding_local_acknowledgement_generation + <> OLD.last_issued_binding_local_acknowledgement_generation + 1 THEN + RAISE EXCEPTION 'issuer binding-local acknowledgement generation counter must advance its own domain by one' + USING ERRCODE = 'check_violation'; + END IF; + RETURN NEW; +END; +$$; + +CREATE FUNCTION game_session_guard_issuer_local_ack_gen_counter_insert() +RETURNS trigger +LANGUAGE plpgsql +AS $$ +BEGIN + IF NEW.counter_version <> 0 + OR NEW.last_issued_binding_local_acknowledgement_generation <> 0 THEN + RAISE EXCEPTION 'issuer binding-local acknowledgement generation counter must start unissued' + USING ERRCODE = 'check_violation'; + END IF; + RETURN NEW; +END; +$$; + +CREATE TRIGGER trg_gs_issuer_binding_local_ack_generation_counter_initial + BEFORE INSERT ON game_session_canonical_issuer_binding_local_ack_gen_counter + FOR EACH ROW EXECUTE FUNCTION game_session_guard_issuer_local_ack_gen_counter_insert(); +CREATE TRIGGER trg_gs_issuer_binding_local_ack_generation_counter_guard + BEFORE UPDATE OR DELETE ON game_session_canonical_issuer_binding_local_ack_gen_counter + FOR EACH ROW EXECUTE FUNCTION game_session_guard_issuer_local_ack_gen_counter(); +CREATE TRIGGER trg_gs_issuer_binding_local_ack_generation_counter_no_truncate + BEFORE TRUNCATE ON game_session_canonical_issuer_binding_local_ack_gen_counter + FOR EACH STATEMENT EXECUTE FUNCTION game_session_reject_issuer_local_ack_gen_counter_change(); +-- [jooq ignore stop] + +COMMENT ON TABLE game_session_canonical_issuer_binding_local_acknowledgement IS + 'Immutable versioned exact local issuer binding/reservation readback receipt; not issuer-wide coverage or admission.'; +COMMENT ON TABLE game_session_canonical_issuer_binding_local_ack_gen_counter IS + 'Independent owner-issued per-transition issuer binding-local acknowledgement generation; distinct from local member-operation and global issuer coverage generations.'; diff --git a/services/game-session-service/src/main/resources/db/migration/V1046__canonical_issuer_live_admission_control.sql b/services/game-session-service/src/main/resources/db/migration/V1046__canonical_issuer_live_admission_control.sql new file mode 100644 index 0000000000..e30e4a576b --- /dev/null +++ b/services/game-session-service/src/main/resources/db/migration/V1046__canonical_issuer_live_admission_control.sql @@ -0,0 +1,290 @@ +-- The live tenant-barrier epoch belongs to a separate issuer control domain. The immutable +-- V1030 initial-layout control and installed anchor remain provenance only; neither is reused as +-- a live admission state or epoch. +CREATE TABLE game_session_canonical_issuer_admission_epoch_counter ( + issuer_id character varying(64) NOT NULL, + last_live_barrier_epoch numeric NOT NULL, + updated_at timestamp with time zone NOT NULL DEFAULT CURRENT_TIMESTAMP, + CONSTRAINT pk_gs_issuer_admission_epoch_counter PRIMARY KEY (issuer_id), + CONSTRAINT chk_gs_issuer_admission_epoch_counter CHECK ( + issuer_id COLLATE "C" = 'firemud-account-service'::character varying COLLATE "C" + AND last_live_barrier_epoch >= 0) +); + +INSERT INTO game_session_canonical_issuer_admission_epoch_counter + (issuer_id, last_live_barrier_epoch) +VALUES ('firemud-account-service', 0); + +CREATE TABLE game_session_canonical_issuer_admission_control ( + issuer_id character varying(64) NOT NULL, + state character varying(32) NOT NULL, + live_barrier_epoch numeric NOT NULL, + current_operation_id uuid NOT NULL, + current_operation_kind character varying(32) NOT NULL, + bootstrap_operation_id uuid NOT NULL, + bootstrap_request_id uuid NOT NULL, + bootstrap_control_epoch numeric NOT NULL, + anchor_exact_bytes bytea NOT NULL, + anchor_exact_digest character varying(71) NOT NULL, + account_issuer_auth_generation numeric NOT NULL, + account_checkpoint_bytes bytea NOT NULL, + account_checkpoint_digest character varying(71) NOT NULL, + account_source_event_bytes bytea, + account_source_event_digest character varying(71), + stable_incarnation_bytes bytea NOT NULL, + stable_incarnation_digest character varying(71) NOT NULL, + inventory_snapshot_revision numeric NOT NULL, + cohort_row_count bigint NOT NULL, + cohort_digest character varying(71) NOT NULL, + control_exact_bytes bytea NOT NULL, + control_exact_digest character varying(71) NOT NULL, + created_at timestamp with time zone NOT NULL DEFAULT CURRENT_TIMESTAMP, + updated_at timestamp with time zone NOT NULL DEFAULT CURRENT_TIMESTAMP, + CONSTRAINT pk_gs_issuer_admission_control PRIMARY KEY (issuer_id), + CONSTRAINT fk_gs_issuer_admission_control_epoch + FOREIGN KEY (issuer_id) + REFERENCES game_session_canonical_issuer_admission_epoch_counter (issuer_id), + CONSTRAINT chk_gs_issuer_admission_control CHECK ( + issuer_id COLLATE "C" = 'firemud-account-service'::character varying COLLATE "C" + AND state IN ('OPEN', 'CUTOFF_PENDING', 'INSTALLED') + AND live_barrier_epoch > 0 + AND current_operation_id <> '00000000-0000-0000-0000-000000000000'::uuid + AND current_operation_kind IN ('INITIAL_ANCHOR_INSTALL', 'CUTOFF') + AND bootstrap_operation_id <> '00000000-0000-0000-0000-000000000000'::uuid + AND bootstrap_request_id <> '00000000-0000-0000-0000-000000000000'::uuid + AND bootstrap_control_epoch > 0 + AND octet_length(anchor_exact_bytes) BETWEEN 1 AND 524288 + AND anchor_exact_digest ~ '^sha256:[0-9a-f]{64}$' + AND account_issuer_auth_generation > 0 + AND octet_length(account_checkpoint_bytes) BETWEEN 1 AND 524288 + AND account_checkpoint_digest ~ '^sha256:[0-9a-f]{64}$' + AND ((account_source_event_bytes IS NULL AND account_source_event_digest IS NULL) + OR (account_source_event_bytes IS NOT NULL + AND octet_length(account_source_event_bytes) BETWEEN 1 AND 524288 + AND account_source_event_digest ~ '^sha256:[0-9a-f]{64}$')) + AND octet_length(stable_incarnation_bytes) BETWEEN 1 AND 524288 + AND stable_incarnation_digest ~ '^sha256:[0-9a-f]{64}$' + AND inventory_snapshot_revision > 0 + AND cohort_row_count >= 0 + AND cohort_digest ~ '^sha256:[0-9a-f]{64}$' + AND octet_length(control_exact_bytes) BETWEEN 1 AND 524288 + AND control_exact_digest ~ '^sha256:[0-9a-f]{64}$' + AND ((state = 'OPEN' AND current_operation_kind = 'INITIAL_ANCHOR_INSTALL') + OR (state IN ('CUTOFF_PENDING', 'INSTALLED') + AND current_operation_kind = 'CUTOFF'))) +); + +CREATE TABLE game_session_canonical_issuer_admission_operation ( + operation_id uuid NOT NULL, + request_id uuid NOT NULL, + issuer_id character varying(64) NOT NULL, + operation_kind character varying(32) NOT NULL, + operation_state character varying(32) NOT NULL, + live_barrier_epoch numeric NOT NULL, + prior_live_barrier_epoch numeric, + bootstrap_operation_id uuid NOT NULL, + bootstrap_request_id uuid NOT NULL, + bootstrap_control_epoch numeric NOT NULL, + anchor_exact_bytes bytea NOT NULL, + anchor_exact_digest character varying(71) NOT NULL, + account_issuer_auth_generation numeric NOT NULL, + account_checkpoint_bytes bytea NOT NULL, + account_checkpoint_digest character varying(71) NOT NULL, + account_source_event_bytes bytea, + account_source_event_digest character varying(71), + stable_incarnation_bytes bytea NOT NULL, + stable_incarnation_digest character varying(71) NOT NULL, + inventory_snapshot_revision numeric NOT NULL, + cohort_row_count bigint NOT NULL, + cohort_digest character varying(71) NOT NULL, + created_at timestamp with time zone NOT NULL DEFAULT CURRENT_TIMESTAMP, + installed_at timestamp with time zone, + CONSTRAINT pk_gs_issuer_admission_operation PRIMARY KEY (operation_id), + CONSTRAINT uq_gs_issuer_admission_operation_pair UNIQUE (operation_id, issuer_id), + CONSTRAINT uq_gs_issuer_admission_operation_request UNIQUE (issuer_id, request_id), + CONSTRAINT uq_gs_issuer_admission_operation_epoch UNIQUE (issuer_id, live_barrier_epoch), + CONSTRAINT chk_gs_issuer_admission_operation CHECK ( + operation_id <> '00000000-0000-0000-0000-000000000000'::uuid + AND request_id <> '00000000-0000-0000-0000-000000000000'::uuid + AND operation_id <> request_id + AND issuer_id COLLATE "C" = 'firemud-account-service'::character varying COLLATE "C" + AND operation_kind IN ('INITIAL_ANCHOR_INSTALL', 'CUTOFF') + AND operation_state IN ('OPEN', 'CUTOFF_PENDING', 'INSTALLED') + AND live_barrier_epoch > 0 + AND ((operation_kind = 'INITIAL_ANCHOR_INSTALL' + AND operation_state = 'OPEN' + AND prior_live_barrier_epoch IS NULL + AND installed_at IS NOT NULL) + OR (operation_kind = 'CUTOFF' + AND operation_state IN ('CUTOFF_PENDING', 'INSTALLED') + AND prior_live_barrier_epoch > 0 + AND live_barrier_epoch > prior_live_barrier_epoch + AND ((operation_state = 'CUTOFF_PENDING' AND installed_at IS NULL) + OR (operation_state = 'INSTALLED' AND installed_at IS NOT NULL)))) + AND bootstrap_operation_id <> '00000000-0000-0000-0000-000000000000'::uuid + AND bootstrap_request_id <> '00000000-0000-0000-0000-000000000000'::uuid + AND bootstrap_control_epoch > 0 + AND octet_length(anchor_exact_bytes) BETWEEN 1 AND 524288 + AND anchor_exact_digest ~ '^sha256:[0-9a-f]{64}$' + AND account_issuer_auth_generation > 0 + AND octet_length(account_checkpoint_bytes) BETWEEN 1 AND 524288 + AND account_checkpoint_digest ~ '^sha256:[0-9a-f]{64}$' + AND ((account_source_event_bytes IS NULL AND account_source_event_digest IS NULL) + OR (account_source_event_bytes IS NOT NULL + AND octet_length(account_source_event_bytes) BETWEEN 1 AND 524288 + AND account_source_event_digest ~ '^sha256:[0-9a-f]{64}$')) + AND octet_length(stable_incarnation_bytes) BETWEEN 1 AND 524288 + AND stable_incarnation_digest ~ '^sha256:[0-9a-f]{64}$' + AND inventory_snapshot_revision > 0 + AND cohort_row_count >= 0 + AND cohort_digest ~ '^sha256:[0-9a-f]{64}$') +); + +ALTER TABLE game_session_canonical_issuer_admission_control + ADD CONSTRAINT fk_gs_issuer_admission_control_operation + FOREIGN KEY (current_operation_id, issuer_id) + REFERENCES game_session_canonical_issuer_admission_operation (operation_id, issuer_id); + +CREATE TABLE game_session_canonical_issuer_admission_cohort_row ( + operation_id uuid NOT NULL, + issuer_id character varying(64) NOT NULL, + row_ordinal bigint NOT NULL, + source_kind character varying(48) NOT NULL, + source_key text NOT NULL, + source_inventory_revision numeric NOT NULL, + source_row_json text NOT NULL, + source_row_digest character varying(71) NOT NULL, + CONSTRAINT pk_gs_issuer_admission_cohort_row PRIMARY KEY (operation_id, row_ordinal), + -- [jooq ignore start] + CONSTRAINT uq_gs_issuer_admission_cohort_source UNIQUE (operation_id, source_kind, source_key), + -- [jooq ignore stop] + CONSTRAINT fk_gs_issuer_admission_cohort_operation + FOREIGN KEY (operation_id, issuer_id) + REFERENCES game_session_canonical_issuer_admission_operation (operation_id, issuer_id), + CONSTRAINT chk_gs_issuer_admission_cohort_row CHECK ( + row_ordinal >= 0 + AND issuer_id COLLATE "C" = 'firemud-account-service'::character varying COLLATE "C" + AND source_kind IN ( + 'BINDING', 'TRANSITION', 'RESERVATION', 'ACCOUNT_OBLIGATION', + 'ISSUER_OBLIGATION', 'REGION_OBLIGATION', 'LOCAL_OPERATION', + 'BOOTSTRAP_MEMBER_OPERATION', 'PENDING_INITIALIZER') + AND length(source_key) > 0 + AND source_inventory_revision > 0 + AND length(source_row_json) > 1 + AND source_row_digest ~ '^sha256:[0-9a-f]{64}$') +); + +-- The complete original OPEN payload is committed before its one-key Redis operation. It is +-- immutable across retries and remains available to a later cutoff even after a lost reply. +CREATE TABLE game_session_canonical_issuer_admission_initializer ( + operation_id uuid NOT NULL, + issuer_id character varying(64) NOT NULL, + tenant_id uuid NOT NULL, + playable_state_namespace_id uuid NOT NULL, + tenant_gameplay_tag character varying(44) NOT NULL, + live_barrier_epoch numeric NOT NULL, + initialization_state character varying(24) NOT NULL, + initializer_exact_bytes bytea NOT NULL, + initializer_digest character varying(71) NOT NULL, + open_payload_bytes bytea NOT NULL, + open_payload_digest character varying(71) NOT NULL, + created_at timestamp with time zone NOT NULL DEFAULT CURRENT_TIMESTAMP, + CONSTRAINT pk_gs_issuer_admission_initializer PRIMARY KEY (operation_id), + CONSTRAINT uq_gs_issuer_admission_initializer_target_epoch + UNIQUE (issuer_id, tenant_id, playable_state_namespace_id, live_barrier_epoch), + CONSTRAINT uq_gs_issuer_admission_initializer_operation_pair UNIQUE (operation_id, issuer_id), + CONSTRAINT fk_gs_issuer_admission_initializer_operation + FOREIGN KEY (operation_id) + REFERENCES game_session_canonical_issuer_binding_local_operation (operation_id), + CONSTRAINT chk_gs_issuer_admission_initializer CHECK ( + issuer_id COLLATE "C" = 'firemud-account-service'::character varying COLLATE "C" + AND tenant_id <> '00000000-0000-0000-0000-000000000000'::uuid + AND playable_state_namespace_id <> '00000000-0000-0000-0000-000000000000'::uuid + AND tenant_gameplay_tag ~ '^g[1-9][0-9]{0,9}-[0-9a-f]{32}$' + AND live_barrier_epoch > 0 + AND initialization_state IN ('PREPARED', 'INITIALIZING', 'OPEN_CONFIRMED') + AND octet_length(initializer_exact_bytes) BETWEEN 1 AND 524288 + AND initializer_digest ~ '^sha256:[0-9a-f]{64}$' + AND octet_length(open_payload_bytes) BETWEEN 1 AND 524288 + AND open_payload_digest ~ '^sha256:[0-9a-f]{64}$') +); + +CREATE TABLE game_session_canonical_issuer_admission_initializer_receipt ( + operation_id uuid NOT NULL, + issuer_id character varying(64) NOT NULL, + exact_open_payload_bytes bytea NOT NULL, + exact_open_payload_digest character varying(71) NOT NULL, + script_outcome smallint NOT NULL, + readback_at timestamp with time zone NOT NULL DEFAULT CURRENT_TIMESTAMP, + CONSTRAINT pk_gs_issuer_admission_initializer_receipt PRIMARY KEY (operation_id), + CONSTRAINT fk_gs_issuer_admission_initializer_receipt_initializer + FOREIGN KEY (operation_id, issuer_id) + REFERENCES game_session_canonical_issuer_admission_initializer (operation_id, issuer_id), + CONSTRAINT chk_gs_issuer_admission_initializer_receipt CHECK ( + octet_length(exact_open_payload_bytes) BETWEEN 1 AND 524288 + AND exact_open_payload_digest ~ '^sha256:[0-9a-f]{64}$' + AND script_outcome IN (1, 2)) +); + +CREATE TABLE game_session_canonical_issuer_admission_cutoff_target ( + operation_id uuid NOT NULL, + issuer_id character varying(64) NOT NULL, + target_ordinal bigint NOT NULL, + tenant_id uuid NOT NULL, + playable_state_namespace_id uuid NOT NULL, + tenant_gameplay_tag character varying(44) NOT NULL, + target_source_digest character varying(71) NOT NULL, + captured_initializer_operation_id uuid, + captured_initializer_epoch numeric, + captured_initializer_digest character varying(71), + captured_open_payload_bytes bytea, + captured_open_payload_digest character varying(71), + closed_payload_bytes bytea NOT NULL, + closed_payload_digest character varying(71) NOT NULL, + exact_closed_readback_bytes bytea, + exact_closed_readback_digest character varying(71), + script_outcome smallint, + target_state character varying(24) NOT NULL, + CONSTRAINT pk_gs_issuer_admission_cutoff_target PRIMARY KEY (operation_id, target_ordinal), + CONSTRAINT uq_gs_issuer_admission_cutoff_target UNIQUE + (operation_id, tenant_id, playable_state_namespace_id), + CONSTRAINT fk_gs_issuer_admission_cutoff_target_operation + FOREIGN KEY (operation_id, issuer_id) + REFERENCES game_session_canonical_issuer_admission_operation (operation_id, issuer_id), + CONSTRAINT fk_gs_issuer_admission_cutoff_target_initializer + FOREIGN KEY (captured_initializer_operation_id) + REFERENCES game_session_canonical_issuer_admission_initializer (operation_id), + CONSTRAINT chk_gs_issuer_admission_cutoff_target CHECK ( + target_ordinal >= 0 + AND issuer_id COLLATE "C" = 'firemud-account-service'::character varying COLLATE "C" + AND tenant_id <> '00000000-0000-0000-0000-000000000000'::uuid + AND playable_state_namespace_id <> '00000000-0000-0000-0000-000000000000'::uuid + AND tenant_gameplay_tag ~ '^g[1-9][0-9]{0,9}-[0-9a-f]{32}$' + AND target_source_digest ~ '^sha256:[0-9a-f]{64}$' + AND ((captured_initializer_operation_id IS NULL + AND captured_initializer_epoch IS NULL + AND captured_initializer_digest IS NULL + AND captured_open_payload_bytes IS NULL + AND captured_open_payload_digest IS NULL) + OR (captured_initializer_operation_id IS NOT NULL + AND captured_initializer_epoch > 0 + AND captured_initializer_digest ~ '^sha256:[0-9a-f]{64}$' + AND octet_length(captured_open_payload_bytes) BETWEEN 1 AND 524288 + AND captured_open_payload_digest ~ '^sha256:[0-9a-f]{64}$')) + AND octet_length(closed_payload_bytes) BETWEEN 1 AND 524288 + AND closed_payload_digest ~ '^sha256:[0-9a-f]{64}$' + AND ((target_state = 'REQUIRED' + AND exact_closed_readback_bytes IS NULL + AND exact_closed_readback_digest IS NULL + AND script_outcome IS NULL) + OR (target_state = 'CLOSED' + AND octet_length(exact_closed_readback_bytes) BETWEEN 1 AND 524288 + AND exact_closed_readback_digest ~ '^sha256:[0-9a-f]{64}$' + AND script_outcome IN (1, 2, 3)))) +); + +CREATE INDEX ix_gs_issuer_admission_cutoff_target_state + ON game_session_canonical_issuer_admission_cutoff_target (operation_id, target_state, target_ordinal); + +-- One issuer-wide live control must be positively installed before any ordinary issuer write can +-- proceed. The row is immutable provenance plus monotone control; absence is always closed. diff --git a/services/game-session-service/src/main/resources/db/migration/V1047.1__issuer_admission_retained_evidence_guards.sql b/services/game-session-service/src/main/resources/db/migration/V1047.1__issuer_admission_retained_evidence_guards.sql new file mode 100644 index 0000000000..955c235a9f --- /dev/null +++ b/services/game-session-service/src/main/resources/db/migration/V1047.1__issuer_admission_retained_evidence_guards.sql @@ -0,0 +1,104 @@ +-- Retain original issuer admission evidence. Only the existing owner's one-way completion +-- updates are allowed; insertion and current control authority remain with their existing owners. +-- [jooq ignore start] +CREATE FUNCTION guard_gs_issuer_admission_immutable_evidence() RETURNS trigger AS $$ +BEGIN + RAISE EXCEPTION 'Retained issuer admission evidence is immutable: %', TG_TABLE_NAME + USING ERRCODE = '23514'; +END; +$$ LANGUAGE plpgsql; + +CREATE FUNCTION guard_gs_issuer_admission_initializer() RETURNS trigger AS $$ +BEGIN + IF TG_OP IN ('DELETE', 'TRUNCATE') THEN + RAISE EXCEPTION 'Retained issuer admission initializer cannot be removed' + USING ERRCODE = '23514'; + END IF; + IF (to_jsonb(NEW) - 'initialization_state') + IS DISTINCT FROM (to_jsonb(OLD) - 'initialization_state') + OR NOT ((OLD.initialization_state = 'PREPARED' AND NEW.initialization_state = 'INITIALIZING') + OR (OLD.initialization_state = 'INITIALIZING' AND NEW.initialization_state = 'OPEN_CONFIRMED')) THEN + RAISE EXCEPTION 'Retained issuer admission initializer permits only original forward completion' + USING ERRCODE = '23514'; + END IF; + RETURN NEW; +END; +$$ LANGUAGE plpgsql; + +CREATE FUNCTION guard_gs_issuer_admission_cutoff_target() RETURNS trigger AS $$ +BEGIN + IF TG_OP IN ('DELETE', 'TRUNCATE') THEN + RAISE EXCEPTION 'Retained issuer admission cutoff target cannot be removed' + USING ERRCODE = '23514'; + END IF; + IF (to_jsonb(NEW) - ARRAY['target_state', 'exact_closed_readback_bytes', + 'exact_closed_readback_digest', 'script_outcome']) + IS DISTINCT FROM + (to_jsonb(OLD) - ARRAY['target_state', 'exact_closed_readback_bytes', + 'exact_closed_readback_digest', 'script_outcome']) + OR OLD.target_state <> 'REQUIRED' OR NEW.target_state <> 'CLOSED' + OR OLD.exact_closed_readback_bytes IS NOT NULL + OR OLD.exact_closed_readback_digest IS NOT NULL OR OLD.script_outcome IS NOT NULL + OR NEW.exact_closed_readback_bytes IS DISTINCT FROM OLD.closed_payload_bytes + OR NEW.exact_closed_readback_digest IS DISTINCT FROM OLD.closed_payload_digest + OR NEW.script_outcome IS NULL OR NEW.script_outcome NOT IN (1, 2, 3) THEN + RAISE EXCEPTION 'Retained issuer admission cutoff target requires its one exact original readback' + USING ERRCODE = '23514'; + END IF; + RETURN NEW; +END; +$$ LANGUAGE plpgsql; + +CREATE FUNCTION guard_gs_issuer_admission_operation() RETURNS trigger AS $$ +BEGIN + IF TG_OP IN ('DELETE', 'TRUNCATE') THEN + RAISE EXCEPTION 'Retained issuer admission operation cannot be removed' + USING ERRCODE = '23514'; + END IF; + IF (to_jsonb(NEW) - ARRAY['operation_state', 'installed_at']) + IS DISTINCT FROM (to_jsonb(OLD) - ARRAY['operation_state', 'installed_at']) + OR OLD.operation_kind <> 'CUTOFF' + OR OLD.operation_state <> 'CUTOFF_PENDING' OR NEW.operation_state <> 'INSTALLED' + OR OLD.installed_at IS NOT NULL OR NEW.installed_at IS NULL THEN + RAISE EXCEPTION 'Retained issuer admission operation permits only original cutoff installation' + USING ERRCODE = '23514'; + END IF; + RETURN NEW; +END; +$$ LANGUAGE plpgsql; + +CREATE TRIGGER gs_issuer_admission_initializer_guard + BEFORE UPDATE OR DELETE ON game_session_canonical_issuer_admission_initializer + FOR EACH ROW EXECUTE FUNCTION guard_gs_issuer_admission_initializer(); +CREATE TRIGGER gs_issuer_admission_initializer_retention + BEFORE TRUNCATE ON game_session_canonical_issuer_admission_initializer + FOR EACH STATEMENT EXECUTE FUNCTION guard_gs_issuer_admission_initializer(); + +CREATE TRIGGER gs_issuer_admission_receipt_guard + BEFORE UPDATE OR DELETE ON game_session_canonical_issuer_admission_initializer_receipt + FOR EACH ROW EXECUTE FUNCTION guard_gs_issuer_admission_immutable_evidence(); +CREATE TRIGGER gs_issuer_admission_receipt_retention + BEFORE TRUNCATE ON game_session_canonical_issuer_admission_initializer_receipt + FOR EACH STATEMENT EXECUTE FUNCTION guard_gs_issuer_admission_immutable_evidence(); + +CREATE TRIGGER gs_issuer_admission_cohort_guard + BEFORE UPDATE OR DELETE ON game_session_canonical_issuer_admission_cohort_row + FOR EACH ROW EXECUTE FUNCTION guard_gs_issuer_admission_immutable_evidence(); +CREATE TRIGGER gs_issuer_admission_cohort_retention + BEFORE TRUNCATE ON game_session_canonical_issuer_admission_cohort_row + FOR EACH STATEMENT EXECUTE FUNCTION guard_gs_issuer_admission_immutable_evidence(); + +CREATE TRIGGER gs_issuer_admission_cutoff_target_guard + BEFORE UPDATE OR DELETE ON game_session_canonical_issuer_admission_cutoff_target + FOR EACH ROW EXECUTE FUNCTION guard_gs_issuer_admission_cutoff_target(); +CREATE TRIGGER gs_issuer_admission_cutoff_target_retention + BEFORE TRUNCATE ON game_session_canonical_issuer_admission_cutoff_target + FOR EACH STATEMENT EXECUTE FUNCTION guard_gs_issuer_admission_cutoff_target(); + +CREATE TRIGGER gs_issuer_admission_operation_guard + BEFORE UPDATE OR DELETE ON game_session_canonical_issuer_admission_operation + FOR EACH ROW EXECUTE FUNCTION guard_gs_issuer_admission_operation(); +CREATE TRIGGER gs_issuer_admission_operation_retention + BEFORE TRUNCATE ON game_session_canonical_issuer_admission_operation + FOR EACH STATEMENT EXECUTE FUNCTION guard_gs_issuer_admission_operation(); +-- [jooq ignore stop] diff --git a/services/game-session-service/src/main/resources/db/migration/V1047.2__issuer_admission_live_control_guards.sql b/services/game-session-service/src/main/resources/db/migration/V1047.2__issuer_admission_live_control_guards.sql new file mode 100644 index 0000000000..243b36664e --- /dev/null +++ b/services/game-session-service/src/main/resources/db/migration/V1047.2__issuer_admission_live_control_guards.sql @@ -0,0 +1,118 @@ +-- Live issuer admission authority has its own retained epoch domain. These guards constrain +-- existing owner updates; initial insertion does not gain any new activation authority. +-- [jooq ignore start] +-- A never-installed issuer starts at zero without a control row. Every allocated live epoch +-- otherwise has its matching control in the same committed transaction. Reject incompatible +-- retained data rather than manufacturing or resetting current authority during this upgrade. +DO $$ +BEGIN + IF EXISTS ( + SELECT 1 + FROM game_session_canonical_issuer_admission_epoch_counter counter + FULL JOIN game_session_canonical_issuer_admission_control control USING (issuer_id) + WHERE counter.issuer_id IS NULL + OR (control.issuer_id IS NULL AND counter.last_live_barrier_epoch <> 0) + OR (control.issuer_id IS NOT NULL + AND counter.last_live_barrier_epoch <> control.live_barrier_epoch) + ) THEN + RAISE EXCEPTION 'Live issuer admission epoch counter and control must retain the same current epoch' + USING ERRCODE = '23514'; + END IF; +END; +$$; + +CREATE FUNCTION guard_gs_issuer_admission_current_epoch_pair() RETURNS trigger AS $$ +BEGIN + IF EXISTS ( + SELECT 1 + FROM game_session_canonical_issuer_admission_epoch_counter counter + FULL JOIN game_session_canonical_issuer_admission_control control USING (issuer_id) + WHERE COALESCE(counter.issuer_id, control.issuer_id) = NEW.issuer_id + AND (counter.issuer_id IS NULL + OR (control.issuer_id IS NULL AND counter.last_live_barrier_epoch <> 0) + OR (control.issuer_id IS NOT NULL + AND counter.last_live_barrier_epoch <> control.live_barrier_epoch)) + ) THEN + RAISE EXCEPTION 'Live issuer admission epoch counter and control must retain the same current epoch' + USING ERRCODE = '23514'; + END IF; + RETURN NEW; +END; +$$ LANGUAGE plpgsql; + +-- The owner allocates before writing control. Validate the final pair at commit, not the +-- intermediate allocation, and cover inserts as well as updates of either side. +CREATE CONSTRAINT TRIGGER gs_issuer_admission_epoch_counter_current_pair + AFTER INSERT OR UPDATE ON game_session_canonical_issuer_admission_epoch_counter + DEFERRABLE INITIALLY DEFERRED + FOR EACH ROW EXECUTE FUNCTION guard_gs_issuer_admission_current_epoch_pair(); +CREATE CONSTRAINT TRIGGER gs_issuer_admission_live_control_current_pair + AFTER INSERT OR UPDATE ON game_session_canonical_issuer_admission_control + DEFERRABLE INITIALLY DEFERRED + FOR EACH ROW EXECUTE FUNCTION guard_gs_issuer_admission_current_epoch_pair(); + +CREATE FUNCTION guard_gs_issuer_admission_epoch_counter() RETURNS trigger AS $$ +BEGIN + IF TG_OP IN ('DELETE', 'TRUNCATE') THEN + RAISE EXCEPTION 'Live issuer admission epoch counter cannot be removed' + USING ERRCODE = '23514'; + END IF; + -- Both initial installation and cutoff allocate exactly one epoch in the existing owner. + IF (to_jsonb(NEW) - ARRAY['last_live_barrier_epoch', 'updated_at']) + IS DISTINCT FROM (to_jsonb(OLD) - ARRAY['last_live_barrier_epoch', 'updated_at']) + OR NEW.last_live_barrier_epoch <> OLD.last_live_barrier_epoch + 1 THEN + RAISE EXCEPTION 'Live issuer admission epoch counter must advance its original domain by one' + USING ERRCODE = '23514'; + END IF; + RETURN NEW; +END; +$$ LANGUAGE plpgsql; + +CREATE FUNCTION guard_gs_issuer_admission_live_control() RETURNS trigger AS $$ +BEGIN + IF TG_OP IN ('DELETE', 'TRUNCATE') THEN + RAISE EXCEPTION 'Live issuer admission control cannot be removed' + USING ERRCODE = '23514'; + END IF; + IF OLD.state = 'OPEN' AND NEW.state = 'CUTOFF_PENDING' + AND OLD.current_operation_kind = 'INITIAL_ANCHOR_INSTALL' + AND NEW.current_operation_kind = 'CUTOFF' + AND NEW.current_operation_id IS DISTINCT FROM OLD.current_operation_id + AND NEW.live_barrier_epoch = OLD.live_barrier_epoch + 1 + AND NEW.inventory_snapshot_revision >= OLD.inventory_snapshot_revision + AND (to_jsonb(NEW) - ARRAY['state', 'live_barrier_epoch', 'current_operation_id', + 'current_operation_kind', 'inventory_snapshot_revision', 'cohort_row_count', + 'cohort_digest', 'control_exact_bytes', 'control_exact_digest', 'updated_at']) + IS NOT DISTINCT FROM + (to_jsonb(OLD) - ARRAY['state', 'live_barrier_epoch', 'current_operation_id', + 'current_operation_kind', 'inventory_snapshot_revision', 'cohort_row_count', + 'cohort_digest', 'control_exact_bytes', 'control_exact_digest', 'updated_at']) THEN + RETURN NEW; + END IF; + -- Completion publishes the captured cutoff, retaining its epoch, operation and whole cohort. + IF OLD.state = 'CUTOFF_PENDING' AND NEW.state = 'INSTALLED' + AND OLD.current_operation_kind = 'CUTOFF' + AND (to_jsonb(NEW) - ARRAY['state', 'control_exact_bytes', 'control_exact_digest', 'updated_at']) + IS NOT DISTINCT FROM + (to_jsonb(OLD) - ARRAY['state', 'control_exact_bytes', 'control_exact_digest', 'updated_at']) THEN + RETURN NEW; + END IF; + RAISE EXCEPTION 'Live issuer admission control permits only original forward cutoff transitions' + USING ERRCODE = '23514'; +END; +$$ LANGUAGE plpgsql; + +CREATE TRIGGER gs_issuer_admission_epoch_counter_guard + BEFORE UPDATE OR DELETE ON game_session_canonical_issuer_admission_epoch_counter + FOR EACH ROW EXECUTE FUNCTION guard_gs_issuer_admission_epoch_counter(); +CREATE TRIGGER gs_issuer_admission_epoch_counter_retention + BEFORE TRUNCATE ON game_session_canonical_issuer_admission_epoch_counter + FOR EACH STATEMENT EXECUTE FUNCTION guard_gs_issuer_admission_epoch_counter(); + +CREATE TRIGGER gs_issuer_admission_live_control_guard + BEFORE UPDATE OR DELETE ON game_session_canonical_issuer_admission_control + FOR EACH ROW EXECUTE FUNCTION guard_gs_issuer_admission_live_control(); +CREATE TRIGGER gs_issuer_admission_live_control_retention + BEFORE TRUNCATE ON game_session_canonical_issuer_admission_control + FOR EACH STATEMENT EXECUTE FUNCTION guard_gs_issuer_admission_live_control(); +-- [jooq ignore stop] diff --git a/services/game-session-service/src/main/resources/db/migration/V1047.3__issuer_local_ack_counter_scope_comment.sql b/services/game-session-service/src/main/resources/db/migration/V1047.3__issuer_local_ack_counter_scope_comment.sql new file mode 100644 index 0000000000..05b52925dd --- /dev/null +++ b/services/game-session-service/src/main/resources/db/migration/V1047.3__issuer_local_ack_counter_scope_comment.sql @@ -0,0 +1,2 @@ +COMMENT ON TABLE game_session_canonical_issuer_binding_local_ack_gen_counter IS + 'Independent owner-issued per-issuer binding-local acknowledgement generation; distinct from local member-operation and global issuer coverage generations.'; diff --git a/services/game-session-service/src/main/resources/db/migration/V1047__canonical_initial_account_admission_barrier.sql b/services/game-session-service/src/main/resources/db/migration/V1047__canonical_initial_account_admission_barrier.sql new file mode 100644 index 0000000000..a6bea2e81b --- /dev/null +++ b/services/game-session-service/src/main/resources/db/migration/V1047__canonical_initial_account_admission_barrier.sql @@ -0,0 +1,295 @@ +-- Durable original-attempt source for the first shard-local Account admission OPEN value. +-- The initial path is separate from account-wide CLOSED acquisition and never reopens a key. + +ALTER TABLE game_session_canonical_account_admission_fence_intent_cohort_row + DROP CONSTRAINT chk_gs_canonical_account_admission_fence_intent_cohort_row; + +ALTER TABLE game_session_canonical_account_admission_fence_intent_cohort_row + ADD CONSTRAINT chk_gs_canonical_account_admission_fence_intent_cohort_row CHECK ( + row_ordinal >= 0 + AND account_id <> '00000000-0000-0000-0000-000000000000'::uuid + AND source_kind IN ( + 'BINDING', 'TRANSITION', 'RESERVATION', 'ACCOUNT_OBLIGATION', + 'ISSUER_OBLIGATION', 'REGION_OBLIGATION', 'MEMBER_REPAIR_CONTROL', + 'MEMBER_REPAIR_OPERATION', 'INITIALIZER', 'INITIAL_TARGET') + AND length(source_key) > 0 + AND ((tenant_id IS NULL AND playable_state_namespace_id IS NULL) + OR (tenant_id IS NOT NULL + AND tenant_id <> '00000000-0000-0000-0000-000000000000'::uuid + AND playable_state_namespace_id IS NOT NULL + AND playable_state_namespace_id <> '00000000-0000-0000-0000-000000000000'::uuid)) + AND jsonb_typeof(source_row) = 'object'); + +CREATE TABLE game_session_canonical_initial_account_barrier_initializer ( + initializer_id uuid NOT NULL, + original_request_id uuid NOT NULL, + original_caller_context_id uuid NOT NULL, + original_attempt_fence bigint NOT NULL, + account_id uuid NOT NULL, + account_login_evidence_digest character varying(71) NOT NULL, + source_control_state character varying(32) NOT NULL, + source_control_epoch numeric NOT NULL, + inventory_snapshot_revision numeric NOT NULL, + source_control_digest character varying(71) NOT NULL, + created_at timestamp with time zone NOT NULL DEFAULT CURRENT_TIMESTAMP, + CONSTRAINT pk_gs_initial_account_barrier_initializer PRIMARY KEY (initializer_id), + CONSTRAINT uq_gs_initial_account_barrier_initializer_request UNIQUE (original_request_id), + CONSTRAINT uq_gs_initial_account_barrier_initializer_scope + UNIQUE (initializer_id, original_request_id, account_id), + CONSTRAINT fk_gs_initial_account_barrier_initializer_control + FOREIGN KEY (account_id) + REFERENCES game_session_canonical_account_coverage_control (account_id), + CONSTRAINT fk_gs_initial_account_barrier_initializer_original + FOREIGN KEY (original_request_id) + REFERENCES game_session_initial_gameplay_login_journal (request_id), + CONSTRAINT chk_gs_initial_account_barrier_initializer CHECK ( + initializer_id <> '00000000-0000-0000-0000-000000000000'::uuid + AND original_request_id <> '00000000-0000-0000-0000-000000000000'::uuid + AND original_caller_context_id <> '00000000-0000-0000-0000-000000000000'::uuid + AND original_attempt_fence > 0 + AND account_id <> '00000000-0000-0000-0000-000000000000'::uuid + AND account_login_evidence_digest ~ '^sha256:[0-9a-f]{64}$' + AND source_control_state = 'NO_ACTIVE_ACCOUNT_WIDE_FLOW' + AND source_control_epoch >= 0 + AND length(source_control_epoch::text) <= 256 + AND inventory_snapshot_revision > 0 + AND source_control_digest ~ '^sha256:[0-9a-f]{64}$') +); + +CREATE TABLE game_session_canonical_initial_account_barrier_target ( + initializer_id uuid NOT NULL, + original_request_id uuid NOT NULL, + account_id uuid NOT NULL, + target_ordinal bigint NOT NULL, + tenant_id uuid NOT NULL, + playable_state_namespace_id uuid NOT NULL, + target_state character varying(32) NOT NULL, + before_accepted_attestation_digest character varying(71), + before_incarnation_digest character varying(71), + before_source_payload_digest character varying(71), + before_observation_issued_at_epoch_millis bigint, + before_observation_observed_at_epoch_millis bigint, + before_observation_expires_at_epoch_millis bigint, + installed_fields_digest character varying(71), + completed_at timestamp with time zone, + CONSTRAINT pk_gs_initial_account_barrier_target + PRIMARY KEY (initializer_id, target_ordinal), + CONSTRAINT uq_gs_initial_account_barrier_target_scope + UNIQUE (initializer_id, target_ordinal, account_id, tenant_id, playable_state_namespace_id), + CONSTRAINT uq_gs_initial_account_barrier_never_retarget + UNIQUE (account_id, tenant_id, playable_state_namespace_id), + CONSTRAINT fk_gs_initial_account_barrier_target_initializer + FOREIGN KEY (initializer_id, original_request_id, account_id) + REFERENCES game_session_canonical_initial_account_barrier_initializer + (initializer_id, original_request_id, account_id), + CONSTRAINT chk_gs_initial_account_barrier_target CHECK ( + target_ordinal = 0 + AND tenant_id <> '00000000-0000-0000-0000-000000000000'::uuid + AND playable_state_namespace_id <> '00000000-0000-0000-0000-000000000000'::uuid + AND ((target_state = 'NEVER_DISPATCHED' + AND before_accepted_attestation_digest IS NULL + AND before_incarnation_digest IS NULL + AND before_source_payload_digest IS NULL + AND before_observation_issued_at_epoch_millis IS NULL + AND before_observation_observed_at_epoch_millis IS NULL + AND before_observation_expires_at_epoch_millis IS NULL + AND installed_fields_digest IS NULL AND completed_at IS NULL) + OR (target_state = 'DISPATCH_POSSIBLE' + AND before_accepted_attestation_digest IS NOT NULL + AND before_accepted_attestation_digest ~ '^sha256:[0-9a-f]{64}$' + AND before_incarnation_digest IS NOT NULL + AND before_incarnation_digest ~ '^sha256:[0-9a-f]{64}$' + AND before_source_payload_digest IS NOT NULL + AND before_source_payload_digest ~ '^sha256:[0-9a-f]{64}$' + AND before_observation_issued_at_epoch_millis IS NOT NULL + AND before_observation_issued_at_epoch_millis > 0 + AND before_observation_observed_at_epoch_millis IS NOT NULL + AND before_observation_observed_at_epoch_millis + >= before_observation_issued_at_epoch_millis + AND before_observation_expires_at_epoch_millis IS NOT NULL + AND before_observation_expires_at_epoch_millis + > before_observation_observed_at_epoch_millis + AND installed_fields_digest IS NULL AND completed_at IS NULL) + OR (target_state = 'OPEN_INSTALLED' + AND before_accepted_attestation_digest IS NOT NULL + AND before_accepted_attestation_digest ~ '^sha256:[0-9a-f]{64}$' + AND before_incarnation_digest IS NOT NULL + AND before_incarnation_digest ~ '^sha256:[0-9a-f]{64}$' + AND before_source_payload_digest IS NOT NULL + AND before_source_payload_digest ~ '^sha256:[0-9a-f]{64}$' + AND before_observation_issued_at_epoch_millis IS NOT NULL + AND before_observation_issued_at_epoch_millis > 0 + AND before_observation_observed_at_epoch_millis IS NOT NULL + AND before_observation_observed_at_epoch_millis + >= before_observation_issued_at_epoch_millis + AND before_observation_expires_at_epoch_millis IS NOT NULL + AND before_observation_expires_at_epoch_millis + > before_observation_observed_at_epoch_millis + AND installed_fields_digest IS NOT NULL + AND installed_fields_digest ~ '^sha256:[0-9a-f]{64}$' + AND completed_at IS NOT NULL))) +); + +-- [jooq ignore start] +CREATE FUNCTION guard_gs_initial_account_barrier_initializer() RETURNS trigger AS $$ +BEGIN + IF TG_OP IN ('DELETE', 'TRUNCATE') THEN + RAISE EXCEPTION 'Initial account barrier initializer retention is held' USING ERRCODE = '23514'; + END IF; + IF TG_OP = 'INSERT' THEN + IF NEW.created_at IS NULL THEN + RAISE EXCEPTION 'Initial account barrier initializer creation time is required' + USING ERRCODE = '23514'; + END IF; + IF NOT EXISTS ( + SELECT 1 FROM game_session_initial_gameplay_login_journal original + WHERE original.request_id = NEW.original_request_id + AND original.caller_context_id = NEW.original_caller_context_id + AND original.expected_attempt_fence = NEW.original_attempt_fence + AND original.abandoned = FALSE + AND original.verified_token_jti IS NOT NULL + AND original.verified_token_sha256 IS NOT NULL + AND original.verified_token_generation IS NOT NULL + AND original.verified_issuance_fence IS NOT NULL) THEN + RAISE EXCEPTION 'Initial account barrier initializer differs from retained original LOGIN' + USING ERRCODE = '23514'; + END IF; + IF NOT EXISTS ( + SELECT 1 FROM game_session_canonical_account_coverage_control control + WHERE control.account_id = NEW.account_id + AND control.state = 'NO_ACTIVE_ACCOUNT_WIDE_FLOW' + AND control.last_operation_fence = NEW.source_control_epoch + AND control.current_operation_id IS NULL + AND control.current_fence_intent_id IS NULL + AND control.current_operation_fence IS NULL + AND control.account_admission_fence IS NULL + AND control.historical_account_admission_fence IS NULL + AND control.coverage_fence IS NULL + AND control.inventory_snapshot_revision IS NULL + AND control.coverage_generation IS NULL) + OR NOT EXISTS ( + SELECT 1 FROM game_session_canonical_binding_inventory_clock inventory_clock + WHERE inventory_clock.singleton_id = 1 + AND inventory_clock.inventory_revision = NEW.inventory_snapshot_revision + AND inventory_clock.inventory_revision > 0) THEN + RAISE EXCEPTION 'Initial account barrier requires positive current SQL and inventory sources' + USING ERRCODE = '23514'; + END IF; + RETURN NEW; + END IF; + IF ROW(NEW.initializer_id, NEW.original_request_id, NEW.original_caller_context_id, + NEW.original_attempt_fence, NEW.account_id, NEW.source_control_state, + NEW.account_login_evidence_digest, NEW.source_control_epoch, NEW.inventory_snapshot_revision, + NEW.source_control_digest, NEW.created_at) + IS DISTINCT FROM + ROW(OLD.initializer_id, OLD.original_request_id, OLD.original_caller_context_id, + OLD.original_attempt_fence, OLD.account_id, OLD.source_control_state, + OLD.account_login_evidence_digest, OLD.source_control_epoch, OLD.inventory_snapshot_revision, + OLD.source_control_digest, OLD.created_at) THEN + RAISE EXCEPTION 'Initial account barrier initializer source is immutable' + USING ERRCODE = '23514'; + END IF; + RETURN NEW; +END; +$$ LANGUAGE plpgsql; + +CREATE TRIGGER gs_initial_account_barrier_initializer_guard + BEFORE INSERT OR UPDATE OR DELETE ON game_session_canonical_initial_account_barrier_initializer + FOR EACH ROW EXECUTE FUNCTION guard_gs_initial_account_barrier_initializer(); +CREATE TRIGGER gs_initial_account_barrier_initializer_retention + BEFORE TRUNCATE ON game_session_canonical_initial_account_barrier_initializer + FOR EACH STATEMENT EXECUTE FUNCTION guard_gs_initial_account_barrier_initializer(); + +CREATE FUNCTION guard_gs_initial_account_barrier_target() RETURNS trigger AS $$ +BEGIN + IF TG_OP IN ('DELETE', 'TRUNCATE') THEN + RAISE EXCEPTION 'Initial account barrier target retention is held' USING ERRCODE = '23514'; + END IF; + IF TG_OP = 'INSERT' THEN + IF NEW.target_state <> 'NEVER_DISPATCHED' + OR NEW.before_incarnation_digest IS NOT NULL + OR NEW.installed_fields_digest IS NOT NULL THEN + RAISE EXCEPTION 'Initial account barrier target must begin never-installed' + USING ERRCODE = '23514'; + END IF; + IF NOT EXISTS ( + SELECT 1 + FROM game_session_canonical_account_coverage_control control + JOIN game_session_canonical_initial_account_barrier_initializer initializer + ON initializer.initializer_id = NEW.initializer_id + AND initializer.original_request_id = NEW.original_request_id + AND initializer.account_id = NEW.account_id + WHERE control.account_id = NEW.account_id + AND control.state = 'NO_ACTIVE_ACCOUNT_WIDE_FLOW' + AND control.last_operation_fence = initializer.source_control_epoch + AND control.current_operation_id IS NULL + AND control.current_fence_intent_id IS NULL + AND control.current_operation_fence IS NULL + AND control.account_admission_fence IS NULL + AND control.historical_account_admission_fence IS NULL + AND control.coverage_fence IS NULL + AND control.inventory_snapshot_revision IS NULL + AND control.coverage_generation IS NULL) THEN + RAISE EXCEPTION 'Initial account target requires its positive captured NO_ACTIVE SQL source' + USING ERRCODE = '23514'; + END IF; + RETURN NEW; + END IF; + IF ROW(NEW.initializer_id, NEW.original_request_id, NEW.account_id, NEW.target_ordinal, + NEW.tenant_id, NEW.playable_state_namespace_id) + IS DISTINCT FROM + ROW(OLD.initializer_id, OLD.original_request_id, OLD.account_id, OLD.target_ordinal, + OLD.tenant_id, OLD.playable_state_namespace_id) THEN + RAISE EXCEPTION 'Initial account barrier target identity is immutable' + USING ERRCODE = '23514'; + END IF; + IF OLD.target_state = 'NEVER_DISPATCHED' AND NEW.target_state = 'DISPATCH_POSSIBLE' + AND NEW.before_incarnation_digest IS NOT NULL + AND NEW.installed_fields_digest IS NULL AND NEW.completed_at IS NULL + AND EXISTS ( + SELECT 1 + FROM game_session_canonical_account_coverage_control control + JOIN game_session_canonical_initial_account_barrier_initializer initializer + ON initializer.initializer_id = NEW.initializer_id + AND initializer.original_request_id = NEW.original_request_id + AND initializer.account_id = NEW.account_id + WHERE control.account_id = NEW.account_id + AND control.state = 'NO_ACTIVE_ACCOUNT_WIDE_FLOW' + AND control.last_operation_fence = initializer.source_control_epoch) THEN + RETURN NEW; + END IF; + IF OLD.target_state = 'DISPATCH_POSSIBLE' AND NEW.target_state = 'OPEN_INSTALLED' + AND ROW(NEW.before_accepted_attestation_digest, NEW.before_incarnation_digest, + NEW.before_source_payload_digest, NEW.before_observation_issued_at_epoch_millis, + NEW.before_observation_observed_at_epoch_millis, + NEW.before_observation_expires_at_epoch_millis) + IS NOT DISTINCT FROM + ROW(OLD.before_accepted_attestation_digest, OLD.before_incarnation_digest, + OLD.before_source_payload_digest, OLD.before_observation_issued_at_epoch_millis, + OLD.before_observation_observed_at_epoch_millis, + OLD.before_observation_expires_at_epoch_millis) + AND NEW.installed_fields_digest IS NOT NULL AND NEW.completed_at IS NOT NULL + AND EXISTS ( + SELECT 1 + FROM game_session_canonical_account_coverage_control control + JOIN game_session_canonical_initial_account_barrier_initializer initializer + ON initializer.initializer_id = NEW.initializer_id + AND initializer.original_request_id = NEW.original_request_id + AND initializer.account_id = NEW.account_id + WHERE control.account_id = NEW.account_id + AND control.state = 'NO_ACTIVE_ACCOUNT_WIDE_FLOW' + AND control.last_operation_fence = initializer.source_control_epoch) THEN + RETURN NEW; + END IF; + RAISE EXCEPTION 'Initial account barrier target cannot reset or change its original attempt' + USING ERRCODE = '23514'; +END; +$$ LANGUAGE plpgsql; + +CREATE TRIGGER gs_initial_account_barrier_target_guard + BEFORE INSERT OR UPDATE OR DELETE ON game_session_canonical_initial_account_barrier_target + FOR EACH ROW EXECUTE FUNCTION guard_gs_initial_account_barrier_target(); +CREATE TRIGGER gs_initial_account_barrier_target_retention + BEFORE TRUNCATE ON game_session_canonical_initial_account_barrier_target + FOR EACH STATEMENT EXECUTE FUNCTION guard_gs_initial_account_barrier_target(); +-- [jooq ignore stop] diff --git a/services/game-session-service/src/main/resources/redis/lua/game-session-account-admission-barrier-initial-open.lua b/services/game-session-service/src/main/resources/redis/lua/game-session-account-admission-barrier-initial-open.lua new file mode 100644 index 0000000000..e89bd72a34 --- /dev/null +++ b/services/game-session-service/src/main/resources/redis/lua/game-session-account-admission-barrier-initial-open.lua @@ -0,0 +1,57 @@ +-- Create the one INITIAL OPEN account barrier at its exact captured NO_ACTIVE control epoch. +-- This script is create-only. Retries after a possible dispatch must verify by readback instead. +local prefix = 'session:game:account-admission:' +local fields = { + 'schema', 'accountId', 'tenantId', 'playableStateNamespaceId', 'tenantGameplayTag', + 'ownerOperationId', 'ownerFenceEpoch', 'incarnationDigest', 'state' +} +local function uuid(value) + return type(value) == 'string' and #value == 36 + and string.match(value, '^%x%x%x%x%x%x%x%x%-%x%x%x%x%-%x%x%x%x%-%x%x%x%x%-%x%x%x%x%x%x%x%x%x%x%x%x$') + and value == string.lower(value) + and value ~= '00000000-0000-0000-0000-000000000000' +end +local function tag(value) + if type(value) ~= 'string' or #value > 44 then return false end + local version, opaque = string.match(value, '^g([1-9][0-9]*)%-([0-9a-f]+)$') + return version ~= nil and #version <= 10 and #opaque == 32 +end +local function digest(value) + return type(value) == 'string' and #value == 71 + and string.match(value, '^sha256:[0-9a-f]+$') ~= nil +end +local function epoch(value) + if type(value) ~= 'string' or #value == 0 or #value > 256 then return false end + return value == '0' or string.match(value, '^[1-9][0-9]*$') ~= nil +end + +if #KEYS ~= 1 or #ARGV ~= 9 then return -2 end +local schema = ARGV[1] +local accountId = ARGV[2] +local tenantId = ARGV[3] +local namespaceId = ARGV[4] +local gameplayTag = ARGV[5] +local initializerId = ARGV[6] +local ownerFenceEpoch = ARGV[7] +local incarnationDigest = ARGV[8] +local state = ARGV[9] +if schema ~= 'gs_account_admission_barrier/v1' + or not uuid(accountId) or not uuid(tenantId) or not uuid(namespaceId) + or not tag(gameplayTag) or not uuid(initializerId) or not epoch(ownerFenceEpoch) + or not digest(incarnationDigest) or state ~= 'OPEN' then return -2 end +local expectedKey = prefix .. '{' .. gameplayTag .. '}:' .. accountId .. ':' .. namespaceId +if KEYS[1] ~= expectedKey then return -2 end + +local kind = redis.call('TYPE', KEYS[1]).ok +if kind ~= 'none' or redis.call('PTTL', KEYS[1]) ~= -2 then return 0 end +redis.call('HSET', KEYS[1], + fields[1], schema, + fields[2], accountId, + fields[3], tenantId, + fields[4], namespaceId, + fields[5], gameplayTag, + fields[6], initializerId, + fields[7], ownerFenceEpoch, + fields[8], incarnationDigest, + fields[9], 'OPEN') +return 1 diff --git a/services/game-session-service/src/main/resources/redis/lua/game-session-issuer-admission-barrier-close.lua b/services/game-session-service/src/main/resources/redis/lua/game-session-issuer-admission-barrier-close.lua new file mode 100644 index 0000000000..9505f80010 --- /dev/null +++ b/services/game-session-service/src/main/resources/redis/lua/game-session-issuer-admission-barrier-close.lua @@ -0,0 +1,133 @@ +-- Install one exact SQL-prepared CLOSED issuer barrier for a selected-A cutoff target. +-- One tenant-slot key only; only the exact captured OPEN initializer can be replaced. +local prefix = 'session:game:issuer-admission:' +local schemaValue = 'gs_issuer_admission_barrier/v1' +local fields = { + 'schema', 'issuerId', 'tenantId', 'playableStateNamespaceId', 'tenantGameplayTag', + 'state', 'admissionEpoch', 'ownerOperationId', 'initializerOperationId', + 'initializerEpoch', 'initializerDigest', 'payloadDigest', 'payload' +} +local maxValueBytes = 524288 +local maxDecimalBytes = 256 + +local function uuid(value) + return type(value) == 'string' and #value == 36 + and string.match(value, '^%x%x%x%x%x%x%x%x%-%x%x%x%x%-%x%x%x%x%-%x%x%x%x%-%x%x%x%x%x%x%x%x%x%x%x%x$') + and value == string.lower(value) + and value ~= '00000000-0000-0000-0000-000000000000' +end + +local function positive(value) + return type(value) == 'string' and #value > 0 and #value <= maxDecimalBytes + and string.match(value, '^[1-9][0-9]*$') ~= nil +end + +local function digest(value) + return type(value) == 'string' and #value == 71 + and string.match(value, '^sha256:[0-9a-f]+$') ~= nil +end + +local function decimalLess(left, right) + if #left ~= #right then return #left < #right end + return left < right +end + +if #KEYS ~= 1 or #ARGV ~= 14 then return -2 end +local issuerId = ARGV[1] +local tenantId = ARGV[2] +local namespaceId = ARGV[3] +local gameplayTag = ARGV[4] +local cutoffOperationId = ARGV[5] +local cutoffEpoch = ARGV[6] +local cutoffPayloadDigest = ARGV[7] +local cutoffPayload = ARGV[8] +local initializerOperationId = ARGV[9] +local initializerEpoch = ARGV[10] +local initializerDigest = ARGV[11] +local expectedOpenPayloadDigest = ARGV[12] +local expectedOpenPayload = ARGV[13] +local state = ARGV[14] +local version, opaque +if type(gameplayTag) == 'string' then + version, opaque = string.match(gameplayTag, '^g([1-9][0-9]*)%-([0-9a-f]+)$') +end +if issuerId ~= 'firemud-account-service' or not uuid(tenantId) or not uuid(namespaceId) + or version == nil or #version > 10 or opaque == nil or #opaque ~= 32 or #gameplayTag > 44 + or not uuid(cutoffOperationId) or not positive(cutoffEpoch) + or not digest(cutoffPayloadDigest) or type(cutoffPayload) ~= 'string' + or #cutoffPayload == 0 or #cutoffPayload > maxValueBytes + or (initializerOperationId ~= 'none' and not uuid(initializerOperationId)) + or (initializerEpoch ~= '0' and not positive(initializerEpoch)) + or (initializerDigest ~= 'none' and not digest(initializerDigest)) + or (expectedOpenPayloadDigest ~= 'none' and not digest(expectedOpenPayloadDigest)) + or type(expectedOpenPayload) ~= 'string' or #expectedOpenPayload > maxValueBytes + or state ~= 'CLOSED' then return -2 end +if initializerOperationId == 'none' then + if initializerEpoch ~= '0' or initializerDigest ~= 'none' + or expectedOpenPayloadDigest ~= 'none' or #expectedOpenPayload ~= 0 then return -2 end +else + if initializerEpoch == '0' or initializerDigest == 'none' + or expectedOpenPayloadDigest == 'none' or #expectedOpenPayload == 0 + or not decimalLess(initializerEpoch, cutoffEpoch) then return -2 end +end +local expectedKey = prefix .. '{' .. gameplayTag .. '}:' .. issuerId .. ':' .. tenantId .. ':' .. namespaceId +if KEYS[1] ~= expectedKey then return -2 end + +local function writeClosed() + redis.call('HSET', KEYS[1], + fields[1], schemaValue, + fields[2], issuerId, + fields[3], tenantId, + fields[4], namespaceId, + fields[5], gameplayTag, + fields[6], 'CLOSED', + fields[7], cutoffEpoch, + fields[8], cutoffOperationId, + fields[9], initializerOperationId, + fields[10], initializerEpoch, + fields[11], initializerDigest, + fields[12], cutoffPayloadDigest, + fields[13], cutoffPayload) +end + +local kind = redis.call('TYPE', KEYS[1]).ok +if kind == 'none' then + if redis.call('PTTL', KEYS[1]) ~= -2 then return -1 end + writeClosed() + return 1 +end +if kind ~= 'hash' or redis.call('PTTL', KEYS[1]) ~= -1 then return -1 end +local existing = redis.call('HGETALL', KEYS[1]) +if #existing ~= 2 * #fields then return -1 end +local values = {} +for index = 1, #existing, 2 do + local field = existing[index] + local value = existing[index + 1] + if values[field] ~= nil then return -1 end + local known = false + for fieldIndex = 1, #fields do + if field == fields[fieldIndex] then known = true break end + end + if not known then return -1 end + values[field] = value +end +for fieldIndex = 1, #fields do + if values[fields[fieldIndex]] == nil then return -1 end +end +if values.schema ~= schemaValue or values.issuerId ~= issuerId or values.tenantId ~= tenantId + or values.playableStateNamespaceId ~= namespaceId or values.tenantGameplayTag ~= gameplayTag then return -1 end +if values.state == 'CLOSED' then + if values.admissionEpoch == cutoffEpoch and values.ownerOperationId == cutoffOperationId + and values.initializerOperationId == initializerOperationId + and values.initializerEpoch == initializerEpoch and values.initializerDigest == initializerDigest + and values.payloadDigest == cutoffPayloadDigest and values.payload == cutoffPayload then return 2 end + return -3 +end +if values.state ~= 'OPEN' or initializerOperationId == 'none' + or values.admissionEpoch ~= initializerEpoch or values.ownerOperationId ~= initializerOperationId + or values.initializerOperationId ~= initializerOperationId + or values.initializerEpoch ~= initializerEpoch or values.initializerDigest ~= initializerDigest + or values.payloadDigest ~= expectedOpenPayloadDigest or values.payload ~= expectedOpenPayload + or not decimalLess(values.admissionEpoch, cutoffEpoch) then return -3 end +writeClosed() +return 3 diff --git a/services/game-session-service/src/main/resources/redis/lua/game-session-issuer-admission-barrier-open.lua b/services/game-session-service/src/main/resources/redis/lua/game-session-issuer-admission-barrier-open.lua new file mode 100644 index 0000000000..09e9b1a1fd --- /dev/null +++ b/services/game-session-service/src/main/resources/redis/lua/game-session-issuer-admission-barrier-open.lua @@ -0,0 +1,106 @@ +-- Install one exact SQL-prepared initial OPEN issuer admission barrier. +-- This one tenant-slot key only; absence is usable only for this exact original initializer. +local prefix = 'session:game:issuer-admission:' +local schemaValue = 'gs_issuer_admission_barrier/v1' +local fields = { + 'schema', 'issuerId', 'tenantId', 'playableStateNamespaceId', 'tenantGameplayTag', + 'state', 'admissionEpoch', 'ownerOperationId', 'initializerOperationId', + 'initializerEpoch', 'initializerDigest', 'payloadDigest', 'payload' +} +local maxValueBytes = 524288 +local maxDecimalBytes = 256 + +local function uuid(value) + return type(value) == 'string' and #value == 36 + and string.match(value, '^%x%x%x%x%x%x%x%x%-%x%x%x%x%-%x%x%x%x%-%x%x%x%x%-%x%x%x%x%x%x%x%x%x%x%x%x$') + and value == string.lower(value) + and value ~= '00000000-0000-0000-0000-000000000000' +end + +local function positive(value) + return type(value) == 'string' and #value > 0 and #value <= maxDecimalBytes + and string.match(value, '^[1-9][0-9]*$') ~= nil +end + +local function digest(value) + return type(value) == 'string' and #value == 71 + and string.match(value, '^sha256:[0-9a-f]+$') ~= nil +end + +local function tag(value) + if type(value) ~= 'string' or #value > 44 then return false end + local version, opaque = string.match(value, '^g([1-9][0-9]*)%-([0-9a-f]+)$') + return version ~= nil and #version <= 10 and opaque ~= nil and #opaque == 32 +end + +if #KEYS ~= 1 or #ARGV ~= 11 then return -2 end +local issuerId = ARGV[1] +local tenantId = ARGV[2] +local namespaceId = ARGV[3] +local gameplayTag = ARGV[4] +local operationId = ARGV[5] +local admissionEpoch = ARGV[6] +local initializerDigest = ARGV[7] +local payloadDigest = ARGV[8] +local payload = ARGV[9] +local state = ARGV[10] +local createMode = ARGV[11] +if issuerId ~= 'firemud-account-service' or not uuid(tenantId) or not uuid(namespaceId) + or not tag(gameplayTag) + or not uuid(operationId) or not positive(admissionEpoch) + or not digest(initializerDigest) or not digest(payloadDigest) + or type(payload) ~= 'string' or #payload == 0 or #payload > maxValueBytes + or state ~= 'OPEN' + or (createMode ~= 'CREATE_ONCE' and createMode ~= 'REPLAY_ONLY') then return -2 end +local expectedKey = prefix .. '{' .. gameplayTag .. '}:' .. issuerId .. ':' .. tenantId .. ':' .. namespaceId +if KEYS[1] ~= expectedKey then return -2 end + +local function writeOpen() + redis.call('HSET', KEYS[1], + fields[1], schemaValue, + fields[2], issuerId, + fields[3], tenantId, + fields[4], namespaceId, + fields[5], gameplayTag, + fields[6], 'OPEN', + fields[7], admissionEpoch, + fields[8], operationId, + fields[9], operationId, + fields[10], admissionEpoch, + fields[11], initializerDigest, + fields[12], payloadDigest, + fields[13], payload) +end + +local kind = redis.call('TYPE', KEYS[1]).ok +if kind == 'none' then + if redis.call('PTTL', KEYS[1]) ~= -2 then return -1 end + if createMode ~= 'CREATE_ONCE' then return -1 end + writeOpen() + return 1 +end +if kind ~= 'hash' or redis.call('PTTL', KEYS[1]) ~= -1 then return -1 end +local existing = redis.call('HGETALL', KEYS[1]) +if #existing ~= 2 * #fields then return -1 end +local values = {} +for index = 1, #existing, 2 do + local field = existing[index] + local value = existing[index + 1] + if values[field] ~= nil then return -1 end + local known = false + for fieldIndex = 1, #fields do + if field == fields[fieldIndex] then known = true break end + end + if not known then return -1 end + values[field] = value +end +for fieldIndex = 1, #fields do + if values[fields[fieldIndex]] == nil then return -1 end +end +if values.schema ~= schemaValue or values.issuerId ~= issuerId or values.tenantId ~= tenantId + or values.playableStateNamespaceId ~= namespaceId or values.tenantGameplayTag ~= gameplayTag + or values.state ~= 'OPEN' or values.admissionEpoch ~= admissionEpoch + or values.ownerOperationId ~= operationId or values.initializerOperationId ~= operationId + or values.initializerEpoch ~= admissionEpoch or values.initializerDigest ~= initializerDigest + or values.payloadDigest ~= payloadDigest or values.payload ~= payload then return -3 end +return 2 diff --git a/services/game-session-service/src/main/resources/redis/scripts/game-session-account-admission-barrier-initial-open.json b/services/game-session-service/src/main/resources/redis/scripts/game-session-account-admission-barrier-initial-open.json new file mode 100644 index 0000000000..0241ec76de --- /dev/null +++ b/services/game-session-service/src/main/resources/redis/scripts/game-session-account-admission-barrier-initial-open.json @@ -0,0 +1,40 @@ +{ + "scriptId": "game-session.account-admission-barrier-initial-open.v1", + "resourcePath": "redis/lua/game-session-account-admission-barrier-initial-open.lua", + "sha256": "472d1dc1097f67e35fedf7cd658694b29c9827604e3093c1426b5ed46bb8c20e", + "owner": "game-session-service", + "principal": "gamesession_coord_app", + "role": "COORDINATION", + "keys": [ + { + "name": "accountAdmissionBarrier", + "ownedPrefix": "session:game:account-admission:", + "hashTagDeclaration": "REQUIRED" + } + ], + "arguments": [ + {"name": "schema"}, + {"name": "accountId"}, + {"name": "tenantId"}, + {"name": "playableStateNamespaceId"}, + {"name": "tenantGameplayTag"}, + {"name": "initializerId"}, + {"name": "ownerFenceEpoch"}, + {"name": "incarnationDigest"}, + {"name": "state"} + ], + "category": "SESSION_CAS", + "outcomes": [ + {"code": "OPEN_CREATED", "category": "SUCCESS", "effect": "MUTATING"}, + {"code": "TARGET_ALREADY_PRESENT", "category": "STALE", "effect": "NON_MUTATING"}, + {"code": "INVALID_ARGUMENTS", "category": "VALIDATION_FAILURE", "effect": "NON_MUTATING"} + ], + "resetSensitivity": "CLUSTER", + "lossClass": "EMPTY_REDIS_COLD_START_OR_RESET", + "tailLossBehavior": "The INITIAL OPEN barrier may be created once only for the persisted original request while the positive SQL account-control source remains at its exact captured NO_ACTIVE_ACCOUNT_WIDE_FLOW epoch. SQL records possible dispatch before the one-key call. Every retry after that point is read-only and requires exact original OPEN readback plus protected incarnation observation. A missing key after a possible dispatch is reset or unknown-outcome evidence and remains non-admitting; it is never a fresh OPEN source. Every existing key, including CLOSED, newer, malformed, expiring, or conflicting values, is refused without mutation. This local proof does not supply Account lease/currentness, issuer or region acknowledgements, final binding CAS, or gameplay admission.", + "compatibilityLevel": "REQUIRES_CLUSTER_RESET", + "supportedCoexistence": [ + {"callerVersion": "v1", "payloadVersion": "none"} + ], + "legacyPayloadShape": null +} diff --git a/services/game-session-service/src/main/resources/redis/scripts/game-session-issuer-admission-barrier-close.json b/services/game-session-service/src/main/resources/redis/scripts/game-session-issuer-admission-barrier-close.json new file mode 100644 index 0000000000..6b51240ef8 --- /dev/null +++ b/services/game-session-service/src/main/resources/redis/scripts/game-session-issuer-admission-barrier-close.json @@ -0,0 +1,48 @@ +{ + "scriptId": "game-session.issuer-admission-barrier-close.v1", + "resourcePath": "redis/lua/game-session-issuer-admission-barrier-close.lua", + "sha256": "ab75bdcc1f157af3c78e954a57512f3815fd81ccae1c4f7a9ace02beced15323", + "owner": "game-session-service", + "principal": "gamesession_coord_app", + "role": "COORDINATION", + "keys": [ + { + "name": "issuerAdmissionBarrier", + "ownedPrefix": "session:game:issuer-admission:", + "hashTagDeclaration": "REQUIRED" + } + ], + "arguments": [ + {"name": "issuerId"}, + {"name": "tenantId"}, + {"name": "playableStateNamespaceId"}, + {"name": "tenantGameplayTag"}, + {"name": "cutoffOperationId"}, + {"name": "cutoffAdmissionBarrierEpoch"}, + {"name": "exactClosedPayloadDigest"}, + {"name": "exactClosedPayload"}, + {"name": "capturedInitializerOperationIdOrNone"}, + {"name": "capturedInitializerAdmissionBarrierEpochOrZero"}, + {"name": "capturedInitializerTupleDigestOrNone"}, + {"name": "expectedOriginalOpenPayloadDigestOrNone"}, + {"name": "expectedOriginalOpenPayloadOrEmpty"}, + {"name": "state"} + ], + "category": "SESSION_CAS", + "outcomes": [ + {"code": "CLOSED_CREATED", "category": "SUCCESS", "effect": "MUTATING"}, + {"code": "CLOSED_REPLAY", "category": "REPLAY", "effect": "NON_MUTATING"}, + {"code": "CAPTURED_OPEN_CLOSED", "category": "SUCCESS", "effect": "MUTATING"}, + {"code": "TYPE_TTL_OR_FIELDSET_REFUSED", "category": "VALIDATION_FAILURE", "effect": "NON_MUTATING"}, + {"code": "INVALID_ARGUMENTS_OR_TARGET", "category": "VALIDATION_FAILURE", "effect": "NON_MUTATING"}, + {"code": "NEWER_CLOSED_OR_UNEXPECTED_STATE", "category": "STALE", "effect": "NON_MUTATING"} + ], + "resetSensitivity": "CLUSTER", + "tailLossBehavior": "A selected issuer cutoff closes only its exact tenant target under the captured cutoff epoch and tuple. It may create CLOSED from absence or replace the exact captured original OPEN payload with a higher cutoff epoch. Existing CLOSED, newer or conflicting state, malformed/reset state, or a different OPEN initializer remains unresolved and non-admitting. Exact CLOSED readback is required before the SQL cohort may become INSTALLED. This script never opens admission or touches the global issuer index/capacity key.", + "lossClass": "EMPTY_REDIS_COLD_START_OR_RESET", + "compatibilityLevel": "REQUIRES_CLUSTER_RESET", + "supportedCoexistence": [ + {"callerVersion": "v1", "payloadVersion": "none"} + ], + "legacyPayloadShape": null +} diff --git a/services/game-session-service/src/main/resources/redis/scripts/game-session-issuer-admission-barrier-open.json b/services/game-session-service/src/main/resources/redis/scripts/game-session-issuer-admission-barrier-open.json new file mode 100644 index 0000000000..39a007457e --- /dev/null +++ b/services/game-session-service/src/main/resources/redis/scripts/game-session-issuer-admission-barrier-open.json @@ -0,0 +1,44 @@ +{ + "scriptId": "game-session.issuer-admission-barrier-open.v1", + "resourcePath": "redis/lua/game-session-issuer-admission-barrier-open.lua", + "sha256": "93c6c553ed9a4c245982448f90b34c2c2b03dace8a7a78a58545375edd5888eb", + "owner": "game-session-service", + "principal": "gamesession_coord_app", + "role": "COORDINATION", + "keys": [ + { + "name": "issuerAdmissionBarrier", + "ownedPrefix": "session:game:issuer-admission:", + "hashTagDeclaration": "REQUIRED" + } + ], + "arguments": [ + {"name": "issuerId"}, + {"name": "tenantId"}, + {"name": "playableStateNamespaceId"}, + {"name": "tenantGameplayTag"}, + {"name": "initializerOperationId"}, + {"name": "admissionBarrierEpoch"}, + {"name": "initializerTupleDigest"}, + {"name": "exactBarrierPayloadDigest"}, + {"name": "exactBarrierPayload"}, + {"name": "state"}, + {"name": "createMode"} + ], + "category": "SESSION_CAS", + "outcomes": [ + {"code": "OPEN_CREATED", "category": "SUCCESS", "effect": "MUTATING"}, + {"code": "OPEN_REPLAY", "category": "REPLAY", "effect": "NON_MUTATING"}, + {"code": "TYPE_TTL_OR_FIELDSET_REFUSED", "category": "VALIDATION_FAILURE", "effect": "NON_MUTATING"}, + {"code": "INVALID_ARGUMENTS_OR_TARGET", "category": "VALIDATION_FAILURE", "effect": "NON_MUTATING"}, + {"code": "CLOSED_OR_CONFLICTING_STATE", "category": "STALE", "effect": "NON_MUTATING"} + ], + "resetSensitivity": "CLUSTER", + "tailLossBehavior": "An issuer tenant barrier opens from absent Redis only with the one-use SQL-issued CREATE_ONCE permit consumed by the first initializer attempt. Later retries use REPLAY_ONLY and can confirm only the complete exact original OPEN tuple already present; absent, reset, CLOSED, malformed, changed source, or conflicting target state is non-admitting. The initializer and physical result remain pending for controlled recovery; this script does not recreate, reopen, renew, acknowledge issuer-wide coverage, or touch a global issuer key.", + "lossClass": "EMPTY_REDIS_COLD_START_OR_RESET", + "compatibilityLevel": "REQUIRES_CLUSTER_RESET", + "supportedCoexistence": [ + {"callerVersion": "v1", "payloadVersion": "none"} + ], + "legacyPayloadShape": null +} diff --git a/services/game-session-service/src/test/java/integration/net/firedevops/firemud/gamesession/repository/CanonicalGameplayAccountAdmissionBarrierRepositoryIntegrationTest.java b/services/game-session-service/src/test/java/integration/net/firedevops/firemud/gamesession/repository/CanonicalGameplayAccountAdmissionBarrierRepositoryIntegrationTest.java index 784342800f..138f45bf30 100644 --- a/services/game-session-service/src/test/java/integration/net/firedevops/firemud/gamesession/repository/CanonicalGameplayAccountAdmissionBarrierRepositoryIntegrationTest.java +++ b/services/game-session-service/src/test/java/integration/net/firedevops/firemud/gamesession/repository/CanonicalGameplayAccountAdmissionBarrierRepositoryIntegrationTest.java @@ -2,7 +2,10 @@ import static org.assertj.core.api.Assertions.assertThat; import static org.assertj.core.api.Assertions.assertThatThrownBy; +import static org.mockito.Mockito.mock; +import static org.mockito.Mockito.when; +import com.google.protobuf.ByteString; import java.math.BigDecimal; import java.math.BigInteger; import java.nio.charset.StandardCharsets; @@ -211,6 +214,178 @@ void intentCapturesEveryExistingTenantNamespaceForTheAccountOnly() { } } + @Test + void pendingInitialAccountTargetIsFrozenIntoCutoffAndItsTargetSet() { + TestSchema testSchema = newTestSchema("gs_account_fence_initial_target_"); + try { + establishActualLegacyDisposition(testSchema.dsl()); + var inventory = new CanonicalGameplayBindingInventoryRepository(testSchema.dsl()); + prepare(inventory, ACCOUNT_ID, TENANT_ID, NAMESPACE_ID, 1); + var initial = + insertControlledInitialTarget( + testSchema.dsl(), ACCOUNT_ID, OTHER_TENANT_ID, OTHER_NAMESPACE_ID); + + var cutoff = + new CanonicalGameplayAccountAdmissionBarrierRepository(testSchema.dsl()) + .beginFenceIntent(ACCOUNT_ID, UUID.randomUUID()); + + assertThat(cutoff.cohortRows()) + .anySatisfy( + row -> { + assertThat(row.kind()) + .isEqualTo(CanonicalGameplayAccountAdmissionFenceIntent.CohortKind.INITIALIZER); + assertThat(row.sourceKey()).isEqualTo(initial.originalRequestId().toString()); + assertThat(row.sourceRecordJson()).contains(initial.initializerId().toString()); + }); + assertThat(cutoff.cohortRows()) + .anySatisfy( + row -> { + assertThat(row.kind()) + .isEqualTo( + CanonicalGameplayAccountAdmissionFenceIntent.CohortKind.INITIAL_TARGET); + assertThat(row.sourceKey()).isEqualTo(initial.initializerId() + ":0"); + assertThat(row.tenantId()).isEqualTo(OTHER_TENANT_ID); + assertThat(row.playableStateNamespaceId()).isEqualTo(OTHER_NAMESPACE_ID); + }); + assertThat(cutoff.barrierTargets()) + .extracting( + CanonicalGameplayAccountAdmissionFenceIntent.BarrierTarget::tenantId, + CanonicalGameplayAccountAdmissionFenceIntent.BarrierTarget::playableStateNamespaceId) + .contains(org.assertj.core.groups.Tuple.tuple(OTHER_TENANT_ID, OTHER_NAMESPACE_ID)); + assertThatThrownBy( + () -> + insertControlledInitialTarget( + testSchema.dsl(), ACCOUNT_ID, TENANT_ID, OTHER_NAMESPACE_ID)) + .isInstanceOfSatisfying( + org.jooq.exception.DataAccessException.class, + failure -> assertThat(failure.sqlState()).isEqualTo("23514")); + } finally { + dropSchema(testSchema.schema()); + } + } + + @Test + void accountCutoffThatWinsInventoryClockOrderBlocksAnInitialTargetInsert() { + TestSchema testSchema = newTestSchema("gs_account_fence_initial_cutoff_wins_"); + try { + establishActualLegacyDisposition(testSchema.dsl()); + var inventory = new CanonicalGameplayBindingInventoryRepository(testSchema.dsl()); + prepare(inventory, ACCOUNT_ID, TENANT_ID, NAMESPACE_ID, 1); + var cutoff = + new CanonicalGameplayAccountAdmissionBarrierRepository(testSchema.dsl()) + .beginFenceIntent(ACCOUNT_ID, UUID.randomUUID()); + + assertThat(cutoff.cohortRows()) + .noneSatisfy( + row -> + assertThat(row.kind()) + .isIn( + CanonicalGameplayAccountAdmissionFenceIntent.CohortKind.INITIALIZER, + CanonicalGameplayAccountAdmissionFenceIntent.CohortKind.INITIAL_TARGET)); + assertThatThrownBy( + () -> + insertControlledInitialTarget( + testSchema.dsl(), ACCOUNT_ID, OTHER_TENANT_ID, OTHER_NAMESPACE_ID)) + .isInstanceOfSatisfying( + org.jooq.exception.DataAccessException.class, + failure -> assertThat(failure.sqlState()).isEqualTo("23514")); + assertThat( + testSchema + .dsl() + .fetchSingle( + "SELECT count(*) AS row_count FROM" + + " game_session_canonical_initial_account_barrier_initializer" + + " WHERE account_id = ?", + ACCOUNT_ID) + .get("row_count", Long.class)) + .isZero(); + } finally { + dropSchema(testSchema.schema()); + } + } + + @Test + void initialSourceRequiresPresentNoActiveControlAndPreservesItsActualEpochIncludingZero() { + TestSchema missingControlSchema = newTestSchema("gs_account_initial_missing_control_"); + try { + establishActualLegacyDisposition(missingControlSchema.dsl()); + missingControlSchema + .dsl() + .execute( + "UPDATE game_session_canonical_binding_inventory_clock" + + " SET inventory_revision = 1 WHERE singleton_id = 1"); + var original = + new net.firedevops.firemud.gamesession.dto.InitialGameplayLoginAttemptCoordinates( + UUID.randomUUID(), UUID.randomUUID(), 17L); + var login = mockLoginResult(original, UUID.randomUUID(), UUID.randomUUID()); + + assertThatThrownBy( + () -> + new CanonicalGameplayAccountInitialBarrierInitializerRepository( + missingControlSchema.dsl()) + .beginOrRead(original, login, OTHER_TENANT_ID, OTHER_NAMESPACE_ID)) + .isInstanceOf(CanonicalGameplayBindingInventoryConflictException.class) + .hasMessageContaining("Account coverage control row is missing"); + } finally { + dropSchema(missingControlSchema.schema()); + } + + TestSchema nonzeroEpochSchema = newTestSchema("gs_account_initial_nonzero_epoch_"); + try { + establishActualLegacyDisposition(nonzeroEpochSchema.dsl()); + var inventory = new CanonicalGameplayBindingInventoryRepository(nonzeroEpochSchema.dsl()); + prepare(inventory, ACCOUNT_ID, TENANT_ID, NAMESPACE_ID, 1); + var original = + new net.firedevops.firemud.gamesession.dto.InitialGameplayLoginAttemptCoordinates( + UUID.randomUUID(), UUID.randomUUID(), 17L); + var login = mockLoginResult(original, ACCOUNT_ID, UUID.randomUUID()); + insertCommittedOriginalLogin(nonzeroEpochSchema.dsl(), original, login.evidence()); + nonzeroEpochSchema + .dsl() + .execute( + "UPDATE game_session_canonical_account_coverage_control" + + " SET last_operation_fence = 8 WHERE account_id = ?", + ACCOUNT_ID); + + var initializer = + new CanonicalGameplayAccountInitialBarrierInitializerRepository(nonzeroEpochSchema.dsl()) + .beginOrRead(original, login, OTHER_TENANT_ID, OTHER_NAMESPACE_ID); + + assertThat(initializer.sourceControlState()).isEqualTo("NO_ACTIVE_ACCOUNT_WIDE_FLOW"); + assertThat(initializer.sourceControlEpoch()).isEqualTo(BigInteger.valueOf(8)); + assertThat(initializer.state()) + .isEqualTo( + CanonicalGameplayAccountInitialBarrierInitializerRepository.State.NEVER_DISPATCHED); + } finally { + dropSchema(nonzeroEpochSchema.schema()); + } + + TestSchema zeroEpochSchema = newTestSchema("gs_account_initial_zero_epoch_"); + try { + establishActualLegacyDisposition(zeroEpochSchema.dsl()); + prepare( + new CanonicalGameplayBindingInventoryRepository(zeroEpochSchema.dsl()), + ACCOUNT_ID, + TENANT_ID, + NAMESPACE_ID, + 1); + var original = + new net.firedevops.firemud.gamesession.dto.InitialGameplayLoginAttemptCoordinates( + UUID.randomUUID(), UUID.randomUUID(), 17L); + var login = mockLoginResult(original, ACCOUNT_ID, UUID.randomUUID()); + insertCommittedOriginalLogin(zeroEpochSchema.dsl(), original, login.evidence()); + + var initializer = + new CanonicalGameplayAccountInitialBarrierInitializerRepository(zeroEpochSchema.dsl()) + .beginOrRead(original, login, OTHER_TENANT_ID, OTHER_NAMESPACE_ID); + + assertThat(initializer.sourceControlState()).isEqualTo("NO_ACTIVE_ACCOUNT_WIDE_FLOW"); + assertThat(initializer.sourceControlEpoch()).isEqualTo(BigInteger.ZERO); + } finally { + dropSchema(zeroEpochSchema.schema()); + } + } + @Test void preparationRacingIntentIsEitherCapturedOrRefused() throws Exception { TestSchema testSchema = newTestSchema("gs_account_fence_race_"); @@ -405,6 +580,123 @@ private static CanonicalGameplayBindingTransitionSnapshot prepare( transitionId, UUID.randomUUID(), candidate, reservation, null, null)); } + /** + * Controlled durable SQL source used only to exercise the existing inventory/control lock order. + */ + private static ControlledInitialTarget insertControlledInitialTarget( + DSLContext dsl, UUID accountId, UUID tenantId, UUID namespaceId) { + UUID originalRequestId = UUID.randomUUID(); + UUID callerContextId = UUID.randomUUID(); + UUID initializerId = UUID.randomUUID(); + UUID tokenJti = UUID.randomUUID(); + String accountEvidenceDigest = "sha256:" + "a".repeat(64); + String sourceControlDigest = "sha256:" + "b".repeat(64); + dsl.transaction( + configuration -> { + var transaction = org.jooq.impl.DSL.using(configuration); + var inventoryClock = + transaction.fetchOne( + "SELECT inventory_revision FROM game_session_canonical_binding_inventory_clock" + + " WHERE singleton_id = 1 FOR UPDATE"); + var control = + transaction.fetchOne( + "SELECT state, last_operation_fence FROM" + + " game_session_canonical_account_coverage_control" + + " WHERE account_id = ? FOR UPDATE", + accountId); + if (inventoryClock == null || control == null) { + throw new IllegalStateException("Controlled source lacks positive SQL owners"); + } + transaction.execute( + "INSERT INTO game_session_initial_gameplay_login_journal" + + " (request_id, caller_context_id, expected_attempt_fence) VALUES (?, ?, 7)", + originalRequestId, + callerContextId); + transaction.execute( + "UPDATE game_session_initial_gameplay_login_journal" + + " SET verified_token_jti = ?, verified_token_sha256 = ?," + + " verified_token_generation = 1, verified_issuance_fence = 1" + + " WHERE request_id = ?", + tokenJti, + "c".repeat(64), + originalRequestId); + transaction.execute( + "INSERT INTO game_session_canonical_initial_account_barrier_initializer" + + " (initializer_id, original_request_id, original_caller_context_id," + + " original_attempt_fence, account_id, account_login_evidence_digest," + + " source_control_state, source_control_epoch, inventory_snapshot_revision," + + " source_control_digest) VALUES (?, ?, ?, 7, ?, ?, ?, 0, ?, ?)", + initializerId, + originalRequestId, + callerContextId, + accountId, + accountEvidenceDigest, + "NO_ACTIVE_ACCOUNT_WIDE_FLOW", + inventoryClock.get("inventory_revision"), + sourceControlDigest); + transaction.execute( + "INSERT INTO game_session_canonical_initial_account_barrier_target" + + " (initializer_id, original_request_id, account_id, target_ordinal, tenant_id," + + " playable_state_namespace_id, target_state)" + + " VALUES (?, ?, ?, 0, ?, ?, 'NEVER_DISPATCHED')", + initializerId, + originalRequestId, + accountId, + tenantId, + namespaceId); + }); + return new ControlledInitialTarget(initializerId, originalRequestId); + } + + private static net.firedevops.firemud.gamesession.dto.CanonicalGameplayLoginResult + mockLoginResult( + net.firedevops.firemud.gamesession.dto.InitialGameplayLoginAttemptCoordinates coordinates, + UUID accountId, + UUID tokenJti) { + var evidence = + new net.firedevops.firemud.gamesession.dto.CanonicalGameplayLoginResult.NonSecretEvidence( + accountId, + coordinates.requestId(), + coordinates.callerContextId(), + tokenJti, + "d".repeat(64), + GameSessionAccountDelegationProfile.PROFILE, + 1_000L, + 1_000L, + 2_000L, + "1", + "1", + ByteString.copyFromUtf8("{}"), + ByteString.copyFromUtf8("[]"), + ByteString.copyFromUtf8("[]")); + var result = mock(net.firedevops.firemud.gamesession.dto.CanonicalGameplayLoginResult.class); + when(result.evidence()).thenReturn(evidence); + return result; + } + + private static void insertCommittedOriginalLogin( + DSLContext dsl, + net.firedevops.firemud.gamesession.dto.InitialGameplayLoginAttemptCoordinates original, + net.firedevops.firemud.gamesession.dto.CanonicalGameplayLoginResult.NonSecretEvidence + evidence) { + dsl.execute( + "INSERT INTO game_session_initial_gameplay_login_journal" + + " (request_id, caller_context_id, expected_attempt_fence) VALUES (?, ?, ?)", + original.requestId(), + original.callerContextId(), + original.expectedAttemptFence()); + dsl.execute( + "UPDATE game_session_initial_gameplay_login_journal" + + " SET verified_token_jti = ?, verified_token_sha256 = ?," + + " verified_token_generation = ?, verified_issuance_fence = ?" + + " WHERE request_id = ?", + evidence.tokenJti(), + evidence.tokenSha256(), + Long.parseLong(evidence.tokenGeneration()), + Long.parseLong(evidence.issuanceFence()), + original.requestId()); + } + private static void establishActualLegacyDisposition(DSLContext dsl) { var inventory = new CanonicalGameplayBindingInventoryRepository(dsl); var migration = new CanonicalGameplayLegacyMigrationRepository(dsl, inventory); @@ -495,7 +787,9 @@ public CanonicalGameplayLegacyMigrationReadback readBackExact( } private static TestSchema newTestSchema(String prefix) { - String schema = prefix + UUID.randomUUID().toString().replace("-", ""); + String schema = + prefix.substring(0, Math.min(prefix.length(), 31)) + + UUID.randomUUID().toString().replace("-", ""); DriverManagerDataSource dataSource = dataSource(schema); Flyway.configure() .dataSource(dataSource) @@ -538,4 +832,6 @@ private static void assertCheckConstraintViolation( } private record TestSchema(String schema, DSLContext dsl) {} + + private record ControlledInitialTarget(UUID initializerId, UUID originalRequestId) {} } diff --git a/services/game-session-service/src/test/java/integration/net/firedevops/firemud/gamesession/repository/CanonicalGameplayAccountClosedBarrierRedisOwnerIntegrationTest.java b/services/game-session-service/src/test/java/integration/net/firedevops/firemud/gamesession/repository/CanonicalGameplayAccountClosedBarrierRedisOwnerIntegrationTest.java index 0f7dd2425f..1b141876b5 100644 --- a/services/game-session-service/src/test/java/integration/net/firedevops/firemud/gamesession/repository/CanonicalGameplayAccountClosedBarrierRedisOwnerIntegrationTest.java +++ b/services/game-session-service/src/test/java/integration/net/firedevops/firemud/gamesession/repository/CanonicalGameplayAccountClosedBarrierRedisOwnerIntegrationTest.java @@ -12,16 +12,19 @@ import io.lettuce.core.codec.ByteArrayCodec; import io.lettuce.core.protocol.CommandKeyword; import io.lettuce.core.protocol.CommandType; +import java.nio.ByteBuffer; import java.nio.charset.StandardCharsets; import java.nio.file.Path; import java.security.KeyPair; import java.security.KeyPairGenerator; +import java.security.MessageDigest; import java.security.Signature; import java.sql.SQLException; import java.time.Clock; import java.time.Duration; import java.time.Instant; import java.time.ZoneOffset; +import java.util.HexFormat; import java.util.LinkedHashMap; import java.util.List; import java.util.Map; @@ -1162,8 +1165,10 @@ static Fixture open(java.math.BigInteger lastOperationFence, String migrationTar lastOperationFence, accountId); CanonicalGameplayAccountAdmissionFenceIntent intent = - new CanonicalGameplayAccountAdmissionBarrierRepository(dsl) - .beginFenceIntent(accountId, UUID.randomUUID()); + retainedIdentity == null + ? new CanonicalGameplayAccountAdmissionBarrierRepository(dsl) + .beginFenceIntent(accountId, UUID.randomUUID()) + : seedHistoricalV1028Intent(dsl, retainedIdentity, lastOperationFence); if (!intent.operationFence().equals(lastOperationFence.add(java.math.BigInteger.ONE))) { throw new IllegalStateException("Test fixture did not establish the intended fence epoch"); } @@ -1188,6 +1193,153 @@ static Fixture open(java.math.BigInteger lastOperationFence, String migrationTar schema, dataSource, dsl, intent, runtime.targetNamespace(), keyPair, evidence); } + private static CanonicalGameplayAccountAdmissionFenceIntent seedHistoricalV1028Intent( + DSLContext dsl, + CanonicalGameplayBindingIdentity identity, + java.math.BigInteger lastOperationFence) + throws Exception { + // TEST ONLY: seed the populated historical V1027/V1028 storage contract. The live intent + // producer captures INITIAL rows added in V1047 and must not run against this old schema. + // seedActiveSource creates exactly one binding, committed transition, and bound reservation; + // capture all three in the canonical kind order using their actual PostgreSQL JSONB images. + var rows = + dsl.fetch( + "SELECT 0 AS row_ordinal, 'BINDING' AS source_kind," + + " encode(i.binding_ref, 'hex') AS source_key, i.tenant_id," + + " i.playable_state_namespace_id, to_jsonb(i)::text AS source_record_json" + + " FROM game_session_canonical_gameplay_binding_inventory i" + + " WHERE i.account_id = ?" + + " UNION ALL SELECT 1, 'TRANSITION', t.transition_id::text, t.tenant_id," + + " t.playable_state_namespace_id, to_jsonb(t)::text" + + " FROM game_session_canonical_binding_transition t" + + " JOIN game_session_canonical_gameplay_binding_inventory i" + + " ON i.binding_ref = t.candidate_binding_ref WHERE i.account_id = ?" + + " UNION ALL SELECT 2, 'RESERVATION', r.reservation_id::text, r.tenant_id," + + " r.playable_state_namespace_id, to_jsonb(r)::text" + + " FROM game_session_canonical_issuer_partition_reservation r" + + " WHERE r.account_id = ? ORDER BY row_ordinal", + identity.accountId(), + identity.accountId(), + identity.accountId()) + .map( + row -> + CanonicalGameplayAccountAdmissionFenceIntent.cohortRow( + row.get("row_ordinal", Long.class), + CanonicalGameplayAccountAdmissionFenceIntent.CohortKind.valueOf( + row.get("source_kind", String.class)), + row.get("source_key", String.class), + row.get("tenant_id", UUID.class), + row.get("playable_state_namespace_id", UUID.class), + row.get("source_record_json", String.class))); + if (rows.size() != 3 + || rows.stream() + .anyMatch( + row -> + !identity.tenantId().equals(row.tenantId()) + || !identity + .playableStateNamespaceId() + .equals(row.playableStateNamespaceId()))) { + throw new IllegalStateException("Historical fixture must retain its three scoped sources"); + } + var target = + CanonicalGameplayAccountAdmissionFenceIntent.barrierTarget( + 0L, identity.tenantId(), identity.playableStateNamespaceId()); + MessageDigest cohortDigest = MessageDigest.getInstance("SHA-256"); + for (var row : rows) { + updateHistoricalDigest( + cohortDigest, + Long.toString(row.ordinal()), + row.kind().name(), + row.sourceKey(), + row.tenantId().toString(), + row.playableStateNamespaceId().toString(), + row.sourceRecordJson()); + } + MessageDigest targetDigest = MessageDigest.getInstance("SHA-256"); + updateHistoricalDigest( + targetDigest, + Long.toString(target.ordinal()), + target.tenantId().toString(), + target.playableStateNamespaceId().toString()); + UUID operationId = UUID.randomUUID(); + UUID requestId = UUID.randomUUID(); + UUID plannedFence = UUID.randomUUID(); + var operationFence = lastOperationFence.add(java.math.BigInteger.ONE); + dsl.execute( + "INSERT INTO game_session_canonical_account_admission_fence_intent" + + " (operation_id, request_id, account_id, operation_fence," + + " planned_account_admission_fence, inventory_snapshot_revision," + + " legacy_cohort_id, legacy_owner_operation_id, legacy_writer_fence," + + " legacy_source_snapshot_revision, legacy_canonical_inventory_revision," + + " legacy_namespace_index_readback_revision, legacy_evidence_digest, intent_state," + + " cohort_row_count, cohort_digest, barrier_target_count, barrier_target_digest)" + + " SELECT ?, ?, ?, ?, ?, clock.inventory_revision, legacy.cohort_id," + + " legacy.owner_operation_id, legacy.legacy_writer_fence," + + " legacy.source_snapshot_revision, legacy.canonical_inventory_revision," + + " legacy.namespace_index_readback_revision, legacy.evidence_digest," + + " 'ACQUISITION_INTENT', 3, ?, 1, ?" + + " FROM game_session_canonical_binding_inventory_clock clock" + + " CROSS JOIN game_session_canonical_binding_legacy_disposition legacy" + + " WHERE clock.singleton_id = 1 AND legacy.singleton_id = 1", + operationId, + requestId, + identity.accountId(), + operationFence, + plannedFence, + "sha256:" + HexFormat.of().formatHex(cohortDigest.digest()), + "sha256:" + HexFormat.of().formatHex(targetDigest.digest())); + dsl.execute( + "INSERT INTO game_session_canonical_account_admission_fence_intent_barrier_target" + + " (operation_id, account_id, target_ordinal, tenant_id," + + " playable_state_namespace_id, target_state) VALUES (?, ?, 0, ?, ?, 'REQUIRED')", + operationId, + identity.accountId(), + target.tenantId(), + target.playableStateNamespaceId()); + for (var row : rows) { + dsl.execute( + "INSERT INTO game_session_canonical_account_admission_fence_intent_cohort_row" + + " (operation_id, account_id, row_ordinal, source_kind, source_key, tenant_id," + + " playable_state_namespace_id, source_row)" + + " VALUES (?, ?, ?, ?, ?, ?, ?, CAST(? AS jsonb))", + operationId, + identity.accountId(), + row.ordinal(), + row.kind().name(), + row.sourceKey(), + row.tenantId(), + row.playableStateNamespaceId(), + row.sourceRecordJson()); + } + dsl.execute( + "UPDATE game_session_canonical_account_coverage_control control" + + " SET state = 'ACQUISITION_INTENT', last_operation_fence = intent.operation_fence," + + " current_fence_intent_id = intent.operation_id," + + " current_operation_fence = intent.operation_fence," + + " account_admission_fence = intent.planned_account_admission_fence," + + " inventory_snapshot_revision = intent.inventory_snapshot_revision," + + " updated_at = CURRENT_TIMESTAMP" + + " FROM game_session_canonical_account_admission_fence_intent intent" + + " WHERE control.account_id = intent.account_id AND intent.operation_id = ?" + + " AND control.state = 'NO_ACTIVE_ACCOUNT_WIDE_FLOW'" + + " AND control.last_operation_fence = ?", + operationId, + lastOperationFence); + // Use the real immutable read model to verify the seeded tuple, counts, digests and control. + return new CanonicalGameplayAccountAdmissionBarrierRepository(dsl) + .readFenceIntent(identity.accountId(), requestId); + } + + private static void updateHistoricalDigest(MessageDigest digest, String... values) { + // V1027 hashes UTF-8 fields framed by their four-byte big-endian lengths. These three + // historical sources all have resolved non-null scopes; no newer source kinds are seeded. + for (String value : values) { + byte[] encoded = value.getBytes(StandardCharsets.UTF_8); + digest.update(ByteBuffer.allocate(Integer.BYTES).putInt(encoded.length).array()); + digest.update(encoded); + } + } + private static void seedNoActiveAccountCoverageControl(DSLContext dsl, UUID accountId) { // Controlled retained-row input only; this is not owner-produced no-active authority. dsl.execute( diff --git a/services/game-session-service/src/test/java/integration/net/firedevops/firemud/gamesession/repository/CanonicalGameplayAccountInitialBarrierRedisScriptIntegrationTest.java b/services/game-session-service/src/test/java/integration/net/firedevops/firemud/gamesession/repository/CanonicalGameplayAccountInitialBarrierRedisScriptIntegrationTest.java new file mode 100644 index 0000000000..4e09cd01d4 --- /dev/null +++ b/services/game-session-service/src/test/java/integration/net/firedevops/firemud/gamesession/repository/CanonicalGameplayAccountInitialBarrierRedisScriptIntegrationTest.java @@ -0,0 +1,229 @@ +package integration.net.firedevops.firemud.gamesession.repository; + +import static org.assertj.core.api.Assertions.assertThat; + +import io.lettuce.core.AclSetuserArgs; +import io.lettuce.core.ClientOptions; +import io.lettuce.core.RedisClient; +import io.lettuce.core.RedisURI; +import io.lettuce.core.ScriptOutputType; +import io.lettuce.core.api.StatefulRedisConnection; +import io.lettuce.core.api.sync.RedisCommands; +import io.lettuce.core.codec.ByteArrayCodec; +import io.lettuce.core.protocol.CommandKeyword; +import io.lettuce.core.protocol.CommandType; +import java.io.InputStream; +import java.nio.charset.StandardCharsets; +import java.security.MessageDigest; +import java.time.Duration; +import java.util.HashMap; +import java.util.List; +import java.util.Map; +import java.util.UUID; +import net.firedevops.firemud.common.redis.contracts.RedisScriptCatalog; +import net.firedevops.firemud.common.redis.contracts.RedisScriptDescriptor; +import net.firedevops.firemud.gamesession.service.CanonicalGameplayAccountInitialBarrierRedisScriptContribution; +import net.firedevops.firemud.test.TestContainerImages; +import org.junit.jupiter.api.AfterEach; +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Test; +import org.testcontainers.containers.GenericContainer; +import org.testcontainers.junit.jupiter.Container; +import org.testcontainers.junit.jupiter.Testcontainers; + +/** Native Redis proof of create-only OPEN, exact physical readback, and CLOSED precedence. */ +@Testcontainers(disabledWithoutDocker = true) +@SuppressWarnings("resource") +class CanonicalGameplayAccountInitialBarrierRedisScriptIntegrationTest { + private static final String PRINCIPAL = "gamesession_coord_app"; + private static final String SCHEMA = "gs_account_admission_barrier/v1"; + private static final String INCARNATION = "sha256:" + "a".repeat(64); + + @Container + private static final GenericContainer REDIS = + new GenericContainer<>(TestContainerImages.redis()).withExposedPorts(6379); + + private RedisClient administrator; + private StatefulRedisConnection administratorConnection; + private RedisCommands administratorCommands; + private RedisClient ownerClient; + + @BeforeEach + void configureOwnerPrincipal() { + String password = UUID.randomUUID().toString(); + administrator = createClient(null, null); + administratorConnection = administrator.connect(ByteArrayCodec.INSTANCE); + administratorCommands = administratorConnection.sync(); + administratorCommands.flushdb(); + administratorCommands.aclSetuser( + PRINCIPAL, + new AclSetuserArgs() + .reset() + .on() + .addPassword(password) + .keyPattern("session:game:*") + .addCommand(CommandType.HELLO) + .addCommand(CommandType.PING) + .addCommand(CommandType.CLIENT, CommandKeyword.SETINFO) + .addCommand(CommandType.ACL, CommandKeyword.WHOAMI) + .addCommand(CommandType.SCRIPT, CommandKeyword.LOAD) + .addCommand(CommandType.EVALSHA) + .addCommand(CommandType.TYPE) + .addCommand(CommandType.PTTL) + .addCommand(CommandType.HLEN) + .addCommand(CommandType.HGETALL) + .addCommand(CommandType.HSET)); + ownerClient = createClient(PRINCIPAL, password); + } + + @AfterEach + void closeOwnedClients() { + if (administratorConnection != null) administratorConnection.close(); + if (ownerClient != null) ownerClient.shutdown(Duration.ZERO, Duration.ofSeconds(2)); + if (administrator != null) administrator.shutdown(Duration.ZERO, Duration.ofSeconds(2)); + } + + @Test + void oneKeyOpenIsReadBackExactlyAndEveryExistingClosedTargetWins() throws Exception { + UUID accountId = UUID.randomUUID(); + UUID tenantId = UUID.randomUUID(); + UUID namespaceId = UUID.randomUUID(); + UUID initializerId = UUID.randomUUID(); + String gameplayTag = "g8-" + "b".repeat(32); + String key = + "session:game:account-admission:{" + gameplayTag + "}:" + accountId + ":" + namespaceId; + Map expectedOpen = + Map.of( + "schema", + SCHEMA, + "accountId", + accountId.toString(), + "tenantId", + tenantId.toString(), + "playableStateNamespaceId", + namespaceId.toString(), + "tenantGameplayTag", + gameplayTag, + "ownerOperationId", + initializerId.toString(), + "ownerFenceEpoch", + "8", + "incarnationDigest", + INCARNATION, + "state", + "OPEN"); + RedisScriptDescriptor descriptor = + RedisScriptCatalog.fromContributions( + List.of(new CanonicalGameplayAccountInitialBarrierRedisScriptContribution())) + .require(CanonicalGameplayAccountInitialBarrierRedisScriptContribution.SCRIPT_ID); + byte[] script; + try (InputStream input = + getClass().getClassLoader().getResourceAsStream(descriptor.resourcePath())) { + assertThat(input).isNotNull(); + script = input.readAllBytes(); + } + assertThat(hexSha256(script)).isEqualTo(descriptor.sha256()); + + try (StatefulRedisConnection ownerConnection = + ownerClient.connect(ByteArrayCodec.INSTANCE)) { + RedisCommands commands = ownerConnection.sync(); + assertThat(commands.aclWhoami()).isEqualTo(PRINCIPAL); + String sha = commands.scriptLoad(script); + assertThat(sha).isEqualTo(hexSha1(script)); + byte[][] arguments = + openArguments(accountId, tenantId, namespaceId, gameplayTag, initializerId, "8"); + + Long createReply = + commands.evalsha(sha, ScriptOutputType.INTEGER, new byte[][] {ascii(key)}, arguments); + assertThat(createReply).isEqualTo(1L); + assertThat(commands.type(ascii(key))).isEqualTo("hash"); + assertThat(commands.pttl(ascii(key))).isEqualTo(-1L); + assertThat(commands.hlen(ascii(key))).isEqualTo(9L); + assertThat(readFields(commands, key)).isEqualTo(expectedOpen); + + // A lost response cannot turn the key into a mutable replay; the SQL owner handles retries + // with exact readback and never executes this create script again after DISPATCH_POSSIBLE. + Long repeatCreateReply = + commands.evalsha(sha, ScriptOutputType.INTEGER, new byte[][] {ascii(key)}, arguments); + assertThat(repeatCreateReply).isEqualTo(0L); + assertThat(readFields(commands, key)).isEqualTo(expectedOpen); + + administratorCommands.del(ascii(key)); + Map newerClosed = new HashMap<>(expectedOpen); + newerClosed.put("ownerFenceEpoch", "9"); + newerClosed.put("state", "CLOSED"); + writeFields(administratorCommands, key, newerClosed); + Map beforeRefusedOpen = readFields(administratorCommands, key); + Long closedTargetReply = + commands.evalsha(sha, ScriptOutputType.INTEGER, new byte[][] {ascii(key)}, arguments); + assertThat(closedTargetReply).isEqualTo(0L); + assertThat(readFields(administratorCommands, key)).isEqualTo(beforeRefusedOpen); + assertThat(readFields(administratorCommands, key)).containsEntry("state", "CLOSED"); + assertThat(readFields(administratorCommands, key)).containsEntry("ownerFenceEpoch", "9"); + } + } + + private static byte[][] openArguments( + UUID accountId, + UUID tenantId, + UUID namespaceId, + String gameplayTag, + UUID initializerId, + String ownerFenceEpoch) { + return new byte[][] { + ascii(SCHEMA), + ascii(accountId.toString()), + ascii(tenantId.toString()), + ascii(namespaceId.toString()), + ascii(gameplayTag), + ascii(initializerId.toString()), + ascii(ownerFenceEpoch), + ascii(INCARNATION), + ascii("OPEN") + }; + } + + private static Map readFields( + RedisCommands commands, String key) { + Map fields = new HashMap<>(); + for (Map.Entry field : commands.hgetall(ascii(key)).entrySet()) { + fields.put(asciiString(field.getKey()), asciiString(field.getValue())); + } + return Map.copyOf(fields); + } + + private static void writeFields( + RedisCommands commands, String key, Map fields) { + for (Map.Entry field : fields.entrySet()) { + commands.hset(ascii(key), ascii(field.getKey()), ascii(field.getValue())); + } + } + + private static String hexSha256(byte[] value) throws Exception { + return java.util.HexFormat.of().formatHex(MessageDigest.getInstance("SHA-256").digest(value)); + } + + private static String hexSha1(byte[] value) throws Exception { + return java.util.HexFormat.of().formatHex(MessageDigest.getInstance("SHA-1").digest(value)); + } + + private static byte[] ascii(String value) { + return value.getBytes(StandardCharsets.US_ASCII); + } + + private static String asciiString(byte[] value) { + return new String(value, StandardCharsets.US_ASCII); + } + + private static RedisClient createClient(String username, String password) { + RedisURI.Builder builder = RedisURI.Builder.redis(REDIS.getHost(), REDIS.getMappedPort(6379)); + if (username != null) builder.withAuthentication(username, password); + RedisClient client = RedisClient.create(builder.build()); + client.setOptions( + ClientOptions.builder() + .autoReconnect(false) + .protocolVersion(io.lettuce.core.protocol.ProtocolVersion.RESP2) + .build()); + return client; + } +} diff --git a/services/game-session-service/src/test/java/integration/net/firedevops/firemud/gamesession/repository/CanonicalGameplayAdmissionAbortCompositionFixture.java b/services/game-session-service/src/test/java/integration/net/firedevops/firemud/gamesession/repository/CanonicalGameplayAdmissionAbortCompositionFixture.java index 80f279348d..f3d5e5f406 100644 --- a/services/game-session-service/src/test/java/integration/net/firedevops/firemud/gamesession/repository/CanonicalGameplayAdmissionAbortCompositionFixture.java +++ b/services/game-session-service/src/test/java/integration/net/firedevops/firemud/gamesession/repository/CanonicalGameplayAdmissionAbortCompositionFixture.java @@ -95,6 +95,7 @@ public final class CanonicalGameplayAdmissionAbortCompositionFixture implements initialIssuerState; private final CanonicalGameplayIssuerBindingLocalOperation localOperation; private final CanonicalGameplayIssuerBindingLocalProjectionRepository localProjectionRepository; + private byte[] issuerAcknowledgementBytes; private final RedisClient issuerRedisClient; private final RedisScriptCatalog issuerCatalog; private final Map otherOperations = @@ -144,6 +145,49 @@ public CanonicalGameplayAdmissionAbortCompositionFixture( MigrationVersion migrationTarget, BiConsumer afterBootstrap) { + this( + accountDataSource, + accountCandidate, + issuerRedisClient, + seedBootstrapMemberCount, + migrationTarget, + afterBootstrap, + true); + } + + /** + * Keeps the actual V1047-era owners at their historical schema until the caller upgrades it. + * Later-schema composition tests retain the normal after-bootstrap upgrade behavior. + */ + static CanonicalGameplayAdmissionAbortCompositionFixture atHistoricalIssuerAdmissionFrontier( + DriverManagerDataSource accountDataSource, + Candidate accountCandidate, + RedisClient issuerRedisClient, + MigrationVersion migrationTarget) { + Objects.requireNonNull(migrationTarget, "migrationTarget"); + if (!migrationTarget.equals(MigrationVersion.fromVersion("1047")) + && !migrationTarget.equals(MigrationVersion.fromVersion("1047.1"))) { + throw new IllegalArgumentException("Historical issuer admission requires V1047 or V1047.1"); + } + return new CanonicalGameplayAdmissionAbortCompositionFixture( + accountDataSource, + accountCandidate, + issuerRedisClient, + 0, + migrationTarget, + (data, intent) -> {}, + false); + } + + private CanonicalGameplayAdmissionAbortCompositionFixture( + DriverManagerDataSource accountDataSource, + Candidate accountCandidate, + RedisClient issuerRedisClient, + int seedBootstrapMemberCount, + MigrationVersion migrationTarget, + BiConsumer + afterBootstrap, + boolean upgradeAfterBootstrap) { if (seedBootstrapMemberCount < 0 || seedBootstrapMemberCount > 256) { throw new IllegalArgumentException("Bootstrap fixture member count must be within [0, 256]"); } @@ -235,9 +279,15 @@ public CanonicalGameplayAdmissionAbortCompositionFixture( var partitionOwner = new CanonicalGameplayIssuerBootstrapPartitionRedisOwner( issuerRedisClient, issuerCatalog, issuerSource); - new CanonicalGameplayIssuerBootstrapCoverageOwner(dsl, partitionOwner, issuerSource) - .completeInitialBootstrap(bootstrapIntent.operationId(), bootstrapRequestId); + CanonicalGameplayIssuerInstalledAnchor installedAnchor = + new CanonicalGameplayIssuerBootstrapCoverageOwner(dsl, partitionOwner, issuerSource) + .completeInitialBootstrap(bootstrapIntent.operationId(), bootstrapRequestId); Objects.requireNonNull(afterBootstrap, "afterBootstrap").accept(dataSource, bootstrapIntent); + if (migrationTarget != null && upgradeAfterBootstrap) { + upgradeWithDefaultGameSessionMigrations(MigrationVersion.LATEST, dataSource); + } + new CanonicalGameplayIssuerAdmissionControlRepository(dsl) + .installInitialOpen(installedAnchor, issuerSource); var request = new CanonicalGameplayIssuerBindingLocalOperation.Request( UUID.randomUUID(), transitionId, identity, null, null); @@ -474,9 +524,14 @@ public void publish(AccountGameplayAdmissionLeaseEvidence lease) { repository.readProvisionalCasEvidence(transitionId), new CanonicalGameplayAdmissionDecision( transitionId, lease, identity, generation, null, target)); - new CanonicalGameplayIssuerBindingLocalRedisOwner( - issuerRedisClient, issuerCatalog, localProjectionRepository, issuerSource) - .projectAndRead(localOperation); + var physicalReadback = + new CanonicalGameplayIssuerBindingLocalRedisOwner( + issuerRedisClient, issuerCatalog, localProjectionRepository, issuerSource) + .projectAndRead(localOperation); + issuerAcknowledgementBytes = + new CanonicalGameplayIssuerBindingLocalAcknowledgementRepository(dsl, issuerSource) + .acknowledge(physicalReadback) + .exactBytes(); } /** Uses a controlled Account lease input and the actual provisional SQL/Redis owners. */ @@ -729,8 +784,22 @@ public void projectIssuerReleaseAndLoseReply( public CanonicalGameplayIssuerBindingLocalReleaseOperation completeIssuerRelease( CanonicalGameplayIssuerBindingLocalReleaseOperation operation, CanonicalGameplayIssuerBindingLocalReleaseRedisOwner.Readback readback) { - return new CanonicalGameplayIssuerBindingLocalReleaseOperationRepository(dsl, issuerSource) - .completeWithReadback(operation, readback); + var completed = + new CanonicalGameplayIssuerBindingLocalReleaseOperationRepository(dsl, issuerSource) + .completeWithReadback(operation, readback); + if (operation.originalOperation().operationId().equals(localOperation.operationId())) { + var historicalAcknowledgement = + new CanonicalGameplayIssuerBindingLocalAcknowledgementRepository(dsl, issuerSource) + .readHistorical(localOperation.operationId()); + if (issuerAcknowledgementBytes == null + || historicalAcknowledgement == null + || !java.util.Arrays.equals( + issuerAcknowledgementBytes, historicalAcknowledgement.exactBytes())) { + throw new IllegalStateException( + "Issuer release did not retain the exact original binding-local acknowledgement"); + } + } + return completed; } /** Records a controlled Account terminal input through the actual Game Session abort owner. */ diff --git a/services/game-session-service/src/test/java/integration/net/firedevops/firemud/gamesession/repository/CanonicalGameplayIssuerAdmissionBarrierRepositoryIntegrationTest.java b/services/game-session-service/src/test/java/integration/net/firedevops/firemud/gamesession/repository/CanonicalGameplayIssuerAdmissionBarrierRepositoryIntegrationTest.java new file mode 100644 index 0000000000..a211c7a1a9 --- /dev/null +++ b/services/game-session-service/src/test/java/integration/net/firedevops/firemud/gamesession/repository/CanonicalGameplayIssuerAdmissionBarrierRepositoryIntegrationTest.java @@ -0,0 +1,1895 @@ +package net.firedevops.firemud.gamesession.repository; + +import static org.assertj.core.api.Assertions.assertThat; +import static org.assertj.core.api.Assertions.assertThatThrownBy; +import static org.mockito.ArgumentMatchers.any; +import static org.mockito.Mockito.doReturn; +import static org.mockito.Mockito.doThrow; +import static org.mockito.Mockito.mock; +import static org.mockito.Mockito.spy; +import static org.mockito.Mockito.when; + +import io.lettuce.core.AclSetuserArgs; +import io.lettuce.core.ClientOptions; +import io.lettuce.core.RedisClient; +import io.lettuce.core.RedisURI; +import io.lettuce.core.api.StatefulRedisConnection; +import io.lettuce.core.api.async.RedisAsyncCommands; +import io.lettuce.core.api.sync.RedisCommands; +import io.lettuce.core.codec.ByteArrayCodec; +import io.lettuce.core.protocol.CommandKeyword; +import io.lettuce.core.protocol.CommandType; +import java.math.BigInteger; +import java.nio.charset.StandardCharsets; +import java.time.Duration; +import java.util.LinkedHashMap; +import java.util.List; +import java.util.Map; +import java.util.UUID; +import java.util.concurrent.CountDownLatch; +import java.util.concurrent.ExecutionException; +import java.util.concurrent.ExecutorService; +import java.util.concurrent.Executors; +import java.util.concurrent.TimeUnit; +import java.util.concurrent.atomic.AtomicBoolean; +import java.util.concurrent.atomic.AtomicReference; +import net.firedevops.firemud.common.account.admission.AccountGameplayAdmissionLeaseEvidence; +import net.firedevops.firemud.common.gamesession.CanonicalGameplayAdmissionDecisionReadGrpcCodec.Candidate; +import net.firedevops.firemud.common.gamesession.CanonicalGameplayAdmissionDecisionReadGrpcCodec.Target; +import net.firedevops.firemud.common.redis.contracts.RedisScriptCatalog; +import net.firedevops.firemud.common.security.GameSessionAccountDelegationProfile; +import net.firedevops.firemud.gamesession.binding.CanonicalGameplayAdmissionDecision; +import net.firedevops.firemud.gamesession.binding.CanonicalGameplayBindingIdentity; +import net.firedevops.firemud.gamesession.service.CanonicalGameplayIssuerAdmissionBarrierRedisScriptContribution; +import net.firedevops.firemud.gamesession.service.CanonicalGameplayIssuerBindingLocalRedisScriptContribution; +import net.firedevops.firemud.test.TestContainerImages; +import org.flywaydb.core.api.MigrationVersion; +import org.jooq.DSLContext; +import org.jooq.impl.DSL; +import org.junit.jupiter.api.AfterEach; +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Test; +import org.junit.jupiter.params.ParameterizedTest; +import org.junit.jupiter.params.provider.ValueSource; +import org.springframework.jdbc.datasource.DriverManagerDataSource; +import org.testcontainers.containers.GenericContainer; +import org.testcontainers.containers.PostgreSQLContainer; +import org.testcontainers.junit.jupiter.Container; +import org.testcontainers.junit.jupiter.Testcontainers; + +/** Focused PostgreSQL/Redis proof for the first OPEN permit, replay-only retries, and cutoff. */ +@Testcontainers(disabledWithoutDocker = true) +@SuppressWarnings("resource") +class CanonicalGameplayIssuerAdmissionBarrierRepositoryIntegrationTest { + private static final String ISSUER = GameSessionAccountDelegationProfile.ISSUER; + private static final String OWNER_PRINCIPAL = "gamesession_coord_app"; + private static final BigInteger ONE = BigInteger.ONE; + private static final String EVIDENCE_PREFIX = "game_session_canonical_issuer_admission_"; + private static final List EVIDENCE_TABLES = + List.of("initializer", "initializer_receipt", "cohort_row", "cutoff_target", "operation"); + + @Container + private static final PostgreSQLContainer POSTGRES = + new PostgreSQLContainer<>(TestContainerImages.postgres()); + + @Container + private static final GenericContainer REDIS = + new GenericContainer<>(TestContainerImages.redis()).withExposedPorts(6379); + + private RedisClient administrator; + private RedisClient ownerClient; + private StatefulRedisConnection administratorConnection; + private RedisCommands administratorCommands; + private CanonicalGameplayAdmissionAbortCompositionFixture fixture; + + @BeforeEach + void setUp() { + String password = UUID.randomUUID().toString(); + administrator = createRedisClient(null, null); + administratorConnection = administrator.connect(ByteArrayCodec.INSTANCE); + administratorCommands = administratorConnection.sync(); + administratorCommands.flushdb(); + administratorCommands.aclSetuser( + OWNER_PRINCIPAL, + new AclSetuserArgs() + .reset() + .on() + .addPassword(password) + .keyPattern("session:game:*") + .addCommand(CommandType.HELLO) + .addCommand(CommandType.PING) + .addCommand(CommandType.CLIENT, CommandKeyword.SETINFO) + .addCommand(CommandType.ACL, CommandKeyword.WHOAMI) + .addCommand(CommandType.SCRIPT, CommandKeyword.LOAD) + .addCommand(CommandType.EVALSHA) + .addCommand(CommandType.TYPE) + .addCommand(CommandType.PTTL) + .addCommand(CommandType.HGET) + .addCommand(CommandType.HLEN) + .addCommand(CommandType.HGETALL) + .addCommand(CommandType.HSET)); + ownerClient = createRedisClient(OWNER_PRINCIPAL, password); + } + + @AfterEach + void tearDown() { + if (fixture != null) fixture.close(); + if (administratorConnection != null) administratorConnection.close(); + if (ownerClient != null) ownerClient.shutdown(Duration.ZERO, Duration.ofSeconds(2)); + if (administrator != null) administrator.shutdown(Duration.ZERO, Duration.ofSeconds(2)); + } + + @Test + void preparedReadsRetainTheSoleCreatePermitUntilTheRemoteBoundary() { + FixtureState state = fixtureState(); + UUID operationId = state.fixture().originalOperationId(); + var first = state.repository().readPreparedInitializer(operationId); + var second = state.repository().readPreparedInitializer(operationId); + assertThat(second.value().exactBytes()).containsExactly(first.value().exactBytes()); + assertThat(initializationState(state, operationId)).isEqualTo("PREPARED"); + assertThat(countReceipt(state, operationId)).isZero(); + assertThat(administratorCommands.exists(bytes(first.key()))).isZero(); + + assertThat(state.owner().initializeAndRead(operationId).scriptOutcome()).isEqualTo(1L); + assertThat(state.repository().claimFirstCreatePermit(first)).isFalse(); + assertThat(state.repository().claimFirstCreatePermit(second)).isFalse(); + assertThat(state.owner().initializeAndRead(operationId).scriptOutcome()).isEqualTo(2L); + assertThat(countReceipt(state, operationId)).isEqualTo(1L); + } + + @ParameterizedTest + @ValueSource(strings = {"DESCRIPTOR", "SOURCE", "CURRENTNESS"}) + void localPreflightFailureRetainsPreparedInitializerAndAllowsOneValidCreate(String failure) { + FixtureState state = fixtureState(); + UUID operationId = state.fixture().originalOperationId(); + var prepared = state.repository().readPreparedInitializer(operationId); + var repository = + new ForwardingProjectionRepository(state.repository()) { + @Override + public void requireStillCurrent( + CanonicalGameplayIssuerAdmissionBarrierRedisOwner.PreparedInitializer initializer) { + if ("CURRENTNESS".equals(failure)) { + throw new IllegalStateException("Controlled preclaim SQL currentness failure"); + } + super.requireStillCurrent(initializer); + } + }; + RedisScriptCatalog catalog = + RedisScriptCatalog.fromContributions( + "DESCRIPTOR".equals(failure) + ? List.of() + : List.of(new CanonicalGameplayIssuerAdmissionBarrierRedisScriptContribution())); + var failingOwner = + new CanonicalGameplayIssuerAdmissionBarrierRedisOwner( + ownerClient, + catalog, + repository, + () -> { + if ("SOURCE".equals(failure)) { + throw new IllegalStateException("Controlled preclaim current source failure"); + } + return state.sourceReader().readFreshCurrentState(); + }); + + assertThatThrownBy(() -> failingOwner.initializeAndRead(operationId)) + .isInstanceOf(IllegalStateException.class); + assertThat(initializationState(state, operationId)).isEqualTo("PREPARED"); + assertThat(countReceipt(state, operationId)).isZero(); + assertThat(administratorCommands.exists(bytes(prepared.key()))).isZero(); + assertThat(state.owner().initializeAndRead(operationId).scriptOutcome()).isEqualTo(1L); + assertThat(state.owner().initializeAndRead(operationId).scriptOutcome()).isEqualTo(2L); + assertThat(countReceipt(state, operationId)).isEqualTo(1L); + } + + @Test + @SuppressWarnings({"unchecked", "rawtypes"}) + void remotePreflightFailuresRetainPreparedInitializerAndAllowOneValidCreate() { + FixtureState state = fixtureState(); + UUID operationId = state.fixture().originalOperationId(); + var prepared = state.repository().readPreparedInitializer(operationId); + RedisClient connectFailure = mock(RedisClient.class); + when(connectFailure.connect(any(ByteArrayCodec.class))) + .thenThrow(new IllegalStateException("controlled connect failure")); + RedisClient loadFailure = mock(RedisClient.class); + try (var loadConnection = ownerClient.connect(ByteArrayCodec.INSTANCE)) { + StatefulRedisConnection connection = spy(loadConnection); + RedisAsyncCommands commands = spy(loadConnection.async()); + doReturn(commands).when(connection).async(); + doThrow(new IllegalStateException("controlled SCRIPT LOAD failure")) + .when(commands) + .scriptLoad(any(byte[].class)); + when(loadFailure.connect(any(ByteArrayCodec.class))).thenReturn(connection); + // The actual administrator connection reports principal 'default', which must be refused. + for (RedisClient failingClient : List.of(connectFailure, administrator, loadFailure)) { + var owner = + new CanonicalGameplayIssuerAdmissionBarrierRedisOwner( + failingClient, + RedisScriptCatalog.fromContributions( + List.of(new CanonicalGameplayIssuerAdmissionBarrierRedisScriptContribution())), + state.repository(), + state.sourceReader()); + assertThatThrownBy(() -> owner.initializeAndRead(operationId)) + .isInstanceOf(IllegalStateException.class); + assertThat(initializationState(state, operationId)).isEqualTo("PREPARED"); + assertThat(countReceipt(state, operationId)).isZero(); + assertThat(administratorCommands.exists(bytes(prepared.key()))).isZero(); + } + org.mockito.Mockito.verify(commands, org.mockito.Mockito.never()) + .evalsha(any(), any(), any(byte[][].class), any(byte[][].class)); + } + assertThat(state.owner().initializeAndRead(operationId).scriptOutcome()).isEqualTo(1L); + assertThat(state.owner().initializeAndRead(operationId).scriptOutcome()).isEqualTo(2L); + assertThat(countReceipt(state, operationId)).isEqualTo(1L); + } + + @Test + void concurrentClaimsOfRetainedPreparedReadsHaveOnlyOneFirstCreateWinner() throws Exception { + FixtureState state = fixtureState(); + UUID operationId = state.fixture().originalOperationId(); + var first = state.repository().readPreparedInitializer(operationId); + var second = state.repository().readPreparedInitializer(operationId); + CountDownLatch start = new CountDownLatch(1); + ExecutorService executor = Executors.newFixedThreadPool(2); + try { + var firstClaim = + executor.submit( + () -> { + if (!start.await(10, TimeUnit.SECONDS)) { + throw new IllegalStateException("Controlled claim start timed out"); + } + return state.repository().claimFirstCreatePermit(first); + }); + var secondClaim = + executor.submit( + () -> { + if (!start.await(10, TimeUnit.SECONDS)) { + throw new IllegalStateException("Controlled claim start timed out"); + } + return state.repository().claimFirstCreatePermit(second); + }); + start.countDown(); + assertThat( + List.of(firstClaim.get(10, TimeUnit.SECONDS), secondClaim.get(10, TimeUnit.SECONDS))) + .containsExactlyInAnyOrder(true, false); + assertThat(initializationState(state, operationId)).isEqualTo("INITIALIZING"); + assertThatThrownBy(() -> state.owner().initializeAndRead(operationId)) + .isInstanceOf(IllegalStateException.class); + assertThat(countReceipt(state, operationId)).isZero(); + assertThat(administratorCommands.exists(bytes(first.key()))).isZero(); + } finally { + start.countDown(); + executor.shutdownNow(); + } + } + + @Test + void lostClaimReplyLeavesMissingOpenReplayOnlyWithoutRearmingThePermit() { + FixtureState state = fixtureState(); + UUID operationId = state.fixture().originalOperationId(); + var prepared = state.repository().readPreparedInitializer(operationId); + var lostClaimReply = + new ForwardingProjectionRepository(state.repository()) { + @Override + public boolean claimFirstCreatePermit( + CanonicalGameplayIssuerAdmissionBarrierRedisOwner.PreparedInitializer initializer) { + assertThat(super.claimFirstCreatePermit(initializer)).isTrue(); + throw new IllegalStateException("Controlled loss after first-create claim committed"); + } + }; + assertThatThrownBy(() -> state.owner(lostClaimReply).initializeAndRead(operationId)) + .isInstanceOf(IllegalStateException.class); + assertThat(initializationState(state, operationId)).isEqualTo("INITIALIZING"); + assertThat(administratorCommands.exists(bytes(prepared.key()))).isZero(); + assertThat(state.repository().claimFirstCreatePermit(prepared)).isFalse(); + assertThatThrownBy(() -> state.owner().initializeAndRead(operationId)) + .isInstanceOf(IllegalStateException.class); + assertThat(initializationState(state, operationId)).isEqualTo("INITIALIZING"); + assertThat(countReceipt(state, operationId)).isZero(); + assertThat(administratorCommands.exists(bytes(prepared.key()))).isZero(); + } + + @Test + void firstOpenIsPersistedExactRetryIsReplayOnlyAndCutoffPreservesNewerClosedState() { + FixtureState state = fixtureState(); + UUID operationId = state.fixture().originalOperationId(); + + var first = state.owner().initializeAndRead(operationId); + assertThat(first.scriptOutcome()).isEqualTo(1L); + assertThat(initializationState(state, operationId)).isEqualTo("OPEN_CONFIRMED"); + var replay = state.owner().initializeAndRead(operationId); + assertThat(replay.scriptOutcome()).isEqualTo(2L); + assertThat(replay.exactPhysicalPayload()).containsExactly(first.exactPhysicalPayload()); + + var prepared = state.repository().readPreparedInitializer(operationId); + administratorCommands.del(bytes(prepared.key())); + assertThatThrownBy(() -> state.owner().initializeAndRead(operationId)) + .isInstanceOf(IllegalStateException.class); + + UUID cutoffOperationId = UUID.randomUUID(); + state.repository().beginCutoff(cutoffOperationId, UUID.randomUUID()); + var cutoffTargets = state.repository().readPreparedCutoffTargets(cutoffOperationId); + assertThat(cutoffTargets).hasSize(1); + var target = cutoffTargets.getFirst(); + var closed = + state + .owner() + .closeAndRead( + cutoffOperationId, + target.closedValue().tenantId(), + target.closedValue().playableStateNamespaceId()); + assertThat(closed.scriptOutcome()).isEqualTo(1L); + + var newerClosed = + CanonicalGameplayIssuerAdmissionBarrierValue.closed( + ISSUER, + target.closedValue().tenantId(), + target.closedValue().playableStateNamespaceId(), + target.closedValue().tenantGameplayTag(), + target.closedValue().admissionEpoch().add(ONE), + UUID.randomUUID(), + target.closedValue().initializer()); + writePhysicalValue(target.key(), newerClosed); + byte[] newerBytes = newerClosed.exactBytes(); + assertThatThrownBy( + () -> + state + .owner() + .closeAndRead( + cutoffOperationId, + target.closedValue().tenantId(), + target.closedValue().playableStateNamespaceId())) + .isInstanceOf(IllegalStateException.class); + assertThat(administratorCommands.hget(bytes(target.key()), bytes("payload"))) + .containsExactly(newerBytes); + } + + @Test + void lostReceiptReplaysTheExistingOpenWithoutMintingAnotherCreatePermit() { + FixtureState state = fixtureState(); + UUID operationId = state.fixture().originalOperationId(); + AtomicBoolean loseFirstReceipt = new AtomicBoolean(true); + var delegate = state.repository(); + var lostReplyRepository = + new CanonicalGameplayIssuerAdmissionBarrierRedisOwner.ProjectionRepository() { + @Override + public CanonicalGameplayIssuerAdmissionBarrierRedisOwner.PreparedInitializer + readPreparedInitializer(UUID id) { + return delegate.readPreparedInitializer(id); + } + + @Override + public boolean claimFirstCreatePermit( + CanonicalGameplayIssuerAdmissionBarrierRedisOwner.PreparedInitializer prepared) { + return delegate.claimFirstCreatePermit(prepared); + } + + @Override + public CanonicalGameplayIssuerAdmissionBarrierRedisOwner.PreparedCutoffTarget + readPreparedCutoffTarget(UUID id, UUID tenantId, UUID namespaceId) { + return delegate.readPreparedCutoffTarget(id, tenantId, namespaceId); + } + + @Override + public void requireStillCurrent( + CanonicalGameplayIssuerAdmissionBarrierRedisOwner.PreparedInitializer prepared) { + delegate.requireStillCurrent(prepared); + } + + @Override + public void requireStillCurrent( + CanonicalGameplayIssuerAdmissionBarrierRedisOwner.PreparedCutoffTarget prepared) { + delegate.requireStillCurrent(prepared); + } + + @Override + public void recordOpenReadback( + CanonicalGameplayIssuerAdmissionBarrierRedisOwner.PreparedInitializer prepared, + CanonicalGameplayIssuerAdmissionBarrierRedisOwner.Readback readback) { + if (loseFirstReceipt.getAndSet(false)) { + throw new IllegalStateException("Controlled loss after physical OPEN readback"); + } + delegate.recordOpenReadback(prepared, readback); + } + + @Override + public void recordClosedReadback( + CanonicalGameplayIssuerAdmissionBarrierRedisOwner.PreparedCutoffTarget prepared, + CanonicalGameplayIssuerAdmissionBarrierRedisOwner.Readback readback) { + delegate.recordClosedReadback(prepared, readback); + } + }; + var lostReplyOwner = state.owner(lostReplyRepository); + + assertThatThrownBy(() -> lostReplyOwner.initializeAndRead(operationId)) + .isInstanceOf(IllegalStateException.class); + assertThat(initializationState(state, operationId)).isEqualTo("INITIALIZING"); + assertThat(countReceipt(state, operationId)).isZero(); + + var replay = state.owner().initializeAndRead(operationId); + assertThat(replay.scriptOutcome()).isEqualTo(2L); + assertThat(initializationState(state, operationId)).isEqualTo("OPEN_CONFIRMED"); + assertThat(countReceipt(state, operationId)).isEqualTo(1L); + } + + @Test + void missingOpenAfterUncertainFirstAttemptIsNeverRecreated() { + FixtureState state = fixtureState(); + UUID operationId = state.fixture().originalOperationId(); + AtomicBoolean loseFirstReceipt = new AtomicBoolean(true); + var delegate = state.repository(); + var lostReplyRepository = + new CanonicalGameplayIssuerAdmissionBarrierRedisOwner.ProjectionRepository() { + @Override + public CanonicalGameplayIssuerAdmissionBarrierRedisOwner.PreparedInitializer + readPreparedInitializer(UUID id) { + return delegate.readPreparedInitializer(id); + } + + @Override + public boolean claimFirstCreatePermit( + CanonicalGameplayIssuerAdmissionBarrierRedisOwner.PreparedInitializer prepared) { + return delegate.claimFirstCreatePermit(prepared); + } + + @Override + public CanonicalGameplayIssuerAdmissionBarrierRedisOwner.PreparedCutoffTarget + readPreparedCutoffTarget(UUID id, UUID tenantId, UUID namespaceId) { + return delegate.readPreparedCutoffTarget(id, tenantId, namespaceId); + } + + @Override + public void requireStillCurrent( + CanonicalGameplayIssuerAdmissionBarrierRedisOwner.PreparedInitializer prepared) { + delegate.requireStillCurrent(prepared); + } + + @Override + public void requireStillCurrent( + CanonicalGameplayIssuerAdmissionBarrierRedisOwner.PreparedCutoffTarget prepared) { + delegate.requireStillCurrent(prepared); + } + + @Override + public void recordOpenReadback( + CanonicalGameplayIssuerAdmissionBarrierRedisOwner.PreparedInitializer prepared, + CanonicalGameplayIssuerAdmissionBarrierRedisOwner.Readback readback) { + if (loseFirstReceipt.getAndSet(false)) { + throw new IllegalStateException("Controlled loss after physical OPEN readback"); + } + delegate.recordOpenReadback(prepared, readback); + } + + @Override + public void recordClosedReadback( + CanonicalGameplayIssuerAdmissionBarrierRedisOwner.PreparedCutoffTarget prepared, + CanonicalGameplayIssuerAdmissionBarrierRedisOwner.Readback readback) { + delegate.recordClosedReadback(prepared, readback); + } + }; + assertThatThrownBy(() -> state.owner(lostReplyRepository).initializeAndRead(operationId)) + .isInstanceOf(IllegalStateException.class); + + var prepared = state.repository().readPreparedInitializer(operationId); + administratorCommands.del(bytes(prepared.key())); + assertThatThrownBy(() -> state.owner().initializeAndRead(operationId)) + .isInstanceOf(IllegalStateException.class); + assertThat(initializationState(state, operationId)).isEqualTo("INITIALIZING"); + assertThat(countReceipt(state, operationId)).isZero(); + assertThat(administratorCommands.exists(bytes(prepared.key()))).isZero(); + } + + @Test + void cutoffCapturesAnInitializerPreparedBeforeItsCreatePermitIsClaimed() throws Exception { + FixtureState state = fixtureState(); + UUID operationId = state.fixture().originalOperationId(); + UUID cutoffOperationId = UUID.randomUUID(); + CountDownLatch preparedForRedis = new CountDownLatch(1); + CountDownLatch allowRedisOwnerToContinue = new CountDownLatch(1); + AtomicReference + observedInitializer = new AtomicReference<>(); + var delegate = state.repository(); + var gatedRepository = + new CanonicalGameplayIssuerAdmissionBarrierRedisOwner.ProjectionRepository() { + @Override + public CanonicalGameplayIssuerAdmissionBarrierRedisOwner.PreparedInitializer + readPreparedInitializer(UUID id) { + var prepared = delegate.readPreparedInitializer(id); + observedInitializer.set(prepared); + preparedForRedis.countDown(); + try { + if (!allowRedisOwnerToContinue.await(10, TimeUnit.SECONDS)) { + throw new IllegalStateException("Controlled initializer gate timed out"); + } + } catch (InterruptedException interrupted) { + Thread.currentThread().interrupt(); + throw new IllegalStateException( + "Controlled initializer gate was interrupted", interrupted); + } + return prepared; + } + + @Override + public boolean claimFirstCreatePermit( + CanonicalGameplayIssuerAdmissionBarrierRedisOwner.PreparedInitializer prepared) { + return delegate.claimFirstCreatePermit(prepared); + } + + @Override + public CanonicalGameplayIssuerAdmissionBarrierRedisOwner.PreparedCutoffTarget + readPreparedCutoffTarget(UUID id, UUID tenantId, UUID namespaceId) { + return delegate.readPreparedCutoffTarget(id, tenantId, namespaceId); + } + + @Override + public void requireStillCurrent( + CanonicalGameplayIssuerAdmissionBarrierRedisOwner.PreparedInitializer prepared) { + delegate.requireStillCurrent(prepared); + } + + @Override + public void requireStillCurrent( + CanonicalGameplayIssuerAdmissionBarrierRedisOwner.PreparedCutoffTarget prepared) { + delegate.requireStillCurrent(prepared); + } + + @Override + public void recordOpenReadback( + CanonicalGameplayIssuerAdmissionBarrierRedisOwner.PreparedInitializer prepared, + CanonicalGameplayIssuerAdmissionBarrierRedisOwner.Readback readback) { + delegate.recordOpenReadback(prepared, readback); + } + + @Override + public void recordClosedReadback( + CanonicalGameplayIssuerAdmissionBarrierRedisOwner.PreparedCutoffTarget prepared, + CanonicalGameplayIssuerAdmissionBarrierRedisOwner.Readback readback) { + delegate.recordClosedReadback(prepared, readback); + } + }; + ExecutorService executor = Executors.newSingleThreadExecutor(); + try { + var initializerAttempt = + executor.submit(() -> state.owner(gatedRepository).initializeAndRead(operationId)); + assertThat(preparedForRedis.await(10, TimeUnit.SECONDS)).isTrue(); + assertThat(initializationState(state, operationId)).isEqualTo("PREPARED"); + + state.repository().beginCutoff(cutoffOperationId, UUID.randomUUID()); + allowRedisOwnerToContinue.countDown(); + assertThatThrownBy(() -> initializerAttempt.get(10, TimeUnit.SECONDS)) + .isInstanceOf(ExecutionException.class) + .hasCauseInstanceOf(IllegalStateException.class); + assertThat(administratorCommands.exists(bytes(observedInitializer.get().key()))).isZero(); + + var targets = state.repository().readPreparedCutoffTargets(cutoffOperationId); + assertThat(targets).hasSize(1); + var closed = + state + .owner() + .closeAndRead( + cutoffOperationId, + targets.getFirst().closedValue().tenantId(), + targets.getFirst().closedValue().playableStateNamespaceId()); + assertThat(closed.scriptOutcome()).isEqualTo(1L); + assertThat(countReceipt(state, operationId)).isZero(); + } finally { + allowRedisOwnerToContinue.countDown(); + executor.shutdownNow(); + } + } + + @Test + void cutoffInstalledAfterCreateClaimCannotBeOverwrittenByTheDelayedOpen() throws Exception { + FixtureState state = fixtureState(); + UUID operationId = state.fixture().originalOperationId(); + UUID cutoffOperationId = UUID.randomUUID(); + CountDownLatch claimCommitted = new CountDownLatch(1); + CountDownLatch allowRedisOwnerToContinue = new CountDownLatch(1); + AtomicReference + observedInitializer = new AtomicReference<>(); + var gatedRepository = + new ForwardingProjectionRepository(state.repository()) { + @Override + public boolean claimFirstCreatePermit( + CanonicalGameplayIssuerAdmissionBarrierRedisOwner.PreparedInitializer prepared) { + boolean claimed = super.claimFirstCreatePermit(prepared); + assertThat(claimed).isTrue(); + observedInitializer.set(prepared); + claimCommitted.countDown(); + try { + if (!allowRedisOwnerToContinue.await(10, TimeUnit.SECONDS)) { + throw new IllegalStateException("Controlled postclaim gate timed out"); + } + } catch (InterruptedException interrupted) { + Thread.currentThread().interrupt(); + throw new IllegalStateException( + "Controlled postclaim gate was interrupted", interrupted); + } + return claimed; + } + }; + ExecutorService executor = Executors.newSingleThreadExecutor(); + try { + var initializerAttempt = + executor.submit(() -> state.owner(gatedRepository).initializeAndRead(operationId)); + assertThat(claimCommitted.await(10, TimeUnit.SECONDS)).isTrue(); + assertThat(initializationState(state, operationId)).isEqualTo("INITIALIZING"); + var prepared = observedInitializer.get(); + assertThat(administratorCommands.exists(bytes(prepared.key()))).isZero(); + + var pending = state.repository().beginCutoff(cutoffOperationId, UUID.randomUUID()); + var targets = state.repository().readPreparedCutoffTargets(cutoffOperationId); + assertThat(targets).hasSize(1); + var target = targets.getFirst(); + assertThat(target.expectedOpenValue().exactBytes()) + .containsExactly(prepared.value().exactBytes()); + assertThat(target.closedValue().initializer().exactBytes()) + .containsExactly(prepared.value().initializer().exactBytes()); + var closed = + state + .owner() + .closeAndRead( + cutoffOperationId, + target.closedValue().tenantId(), + target.closedValue().playableStateNamespaceId()); + assertThat(closed.scriptOutcome()).isEqualTo(1L); + + allowRedisOwnerToContinue.countDown(); + assertThatThrownBy(() -> initializerAttempt.get(10, TimeUnit.SECONDS)) + .isInstanceOf(ExecutionException.class) + .hasCauseInstanceOf(IllegalStateException.class); + assertThat(administratorCommands.hget(bytes(prepared.key()), bytes("payload"))) + .containsExactly(closed.exactPhysicalPayload()); + assertThat(initializationState(state, operationId)).isEqualTo("INITIALIZING"); + assertThat(countReceipt(state, operationId)).isZero(); + var installed = state.repository().completeCutoff(cutoffOperationId); + assertThat(installed.state()) + .isEqualTo(CanonicalGameplayIssuerAdmissionControlValue.State.INSTALLED); + assertThat(installed.cohortDigest()).isEqualTo(pending.cohortDigest()); + } finally { + allowRedisOwnerToContinue.countDown(); + executor.shutdownNow(); + } + } + + @Test + void cutoffClosesAnAbortedOriginTargetAndRetainsItsFrozenInitializer() { + FixtureState state = fixtureState(); + UUID originalOperationId = state.fixture().originalOperationId(); + var opened = state.owner().initializeAndRead(originalOperationId); + + new CanonicalGameplayBindingInventoryRepository(state.fixture().dsl()) + .recordFirstNewAccountAbort(state.fixture().source(), UUID.randomUUID()); + assertThat( + state + .fixture() + .dsl() + .fetchSingle( + "SELECT status FROM game_session_canonical_binding_transition" + + " WHERE transition_id = ?", + state.fixture().transitionId()) + .get("status", String.class)) + .isEqualTo("ABORTED"); + + UUID cutoffOperationId = UUID.randomUUID(); + state.repository().beginCutoff(cutoffOperationId, UUID.randomUUID()); + var targets = state.repository().readPreparedCutoffTargets(cutoffOperationId); + assertThat(targets).hasSize(1); + var target = targets.getFirst(); + assertThat(target.expectedOpenValue()).isNotNull(); + assertThat(target.expectedOpenValue().exactBytes()) + .containsExactly(opened.exactPhysicalPayload()); + assertThat(target.closedValue().initializer().exactBytes()) + .containsExactly(opened.value().initializer().exactBytes()); + + var closed = + state + .owner() + .closeAndRead( + cutoffOperationId, + target.closedValue().tenantId(), + target.closedValue().playableStateNamespaceId()); + // Outcome 3 is CAPTURED_OPEN_CLOSED: this target replaces the exact OPEN + // payload captured by the cutoff. + assertThat(closed.scriptOutcome()).isEqualTo(3L); + var installed = state.repository().completeCutoff(cutoffOperationId); + assertThat(installed.state()) + .isEqualTo(CanonicalGameplayIssuerAdmissionControlValue.State.INSTALLED); + + var frozenInitializer = + state + .fixture() + .dsl() + .fetchOne( + "SELECT operation_id, open_payload_bytes FROM" + + " game_session_canonical_issuer_admission_initializer" + + " WHERE operation_id = ?", + originalOperationId); + assertThat(frozenInitializer.get("operation_id", UUID.class)).isEqualTo(originalOperationId); + assertThat(frozenInitializer.get("open_payload_bytes", byte[].class)) + .containsExactly(opened.exactPhysicalPayload()); + assertThatThrownBy(() -> state.owner().initializeAndRead(originalOperationId)) + .isInstanceOf(IllegalStateException.class); + assertThat(administratorCommands.hget(bytes(target.key()), bytes("payload"))) + .containsExactly(closed.exactPhysicalPayload()); + } + + @Test + void cutoffCompletesFromFrozenSourcesAfterTheProvisionalOriginAborts() { + FixtureState state = fixtureState(); + var opened = state.owner().initializeAndRead(state.fixture().originalOperationId()); + UUID cutoffOperationId = UUID.randomUUID(); + UUID requestId = UUID.randomUUID(); + var pending = state.repository().beginCutoff(cutoffOperationId, requestId); + var target = state.repository().readPreparedCutoffTargets(cutoffOperationId).getFirst(); + List frozenRows = + state + .fixture() + .dsl() + .fetch( + "SELECT to_jsonb(c)::text AS image FROM" + + " game_session_canonical_issuer_admission_cohort_row c" + + " WHERE operation_id = ? ORDER BY row_ordinal", + cutoffOperationId) + .getValues("image", String.class); + var frozenTarget = + state + .fixture() + .dsl() + .fetchSingle( + "SELECT target_source_digest, closed_payload_digest FROM" + + " game_session_canonical_issuer_admission_cutoff_target" + + " WHERE operation_id = ?", + cutoffOperationId); + + new CanonicalGameplayBindingInventoryRepository(state.fixture().dsl()) + .recordFirstNewAccountAbort(state.fixture().source(), UUID.randomUUID()); + var transition = + state + .fixture() + .dsl() + .fetchSingle( + "SELECT status, inventory_revision FROM game_session_canonical_binding_transition" + + " WHERE transition_id = ?", + state.fixture().transitionId()); + assertThat(transition.get("status", String.class)).isEqualTo("ABORTED"); + assertThat(transition.get("inventory_revision", java.math.BigDecimal.class).toBigIntegerExact()) + .isGreaterThan(pending.inventorySnapshotRevision()); + var retry = state.repository().beginCutoff(cutoffOperationId, requestId); + assertThat(retry.cohortDigest()).isEqualTo(pending.cohortDigest()); + assertThat(retry.cohortRowCount()).isEqualTo(pending.cohortRowCount()); + assertThat(retry.liveBarrierEpoch()).isEqualTo(pending.liveBarrierEpoch()); + assertThatThrownBy(() -> state.repository().completeCutoff(cutoffOperationId)) + .isInstanceOf(CanonicalGameplayBindingInventoryConflictException.class); + assertThat(target.expectedOpenValue().exactBytes()) + .containsExactly(opened.exactPhysicalPayload()); + var closed = + state + .owner() + .closeAndRead( + cutoffOperationId, + target.closedValue().tenantId(), + target.closedValue().playableStateNamespaceId()); + assertThat(closed.scriptOutcome()).isEqualTo(3L); + assertThat(closed.exactPhysicalPayload()).containsExactly(target.closedValue().exactBytes()); + var installed = state.repository().completeCutoff(cutoffOperationId); + assertThat(installed.state()) + .isEqualTo(CanonicalGameplayIssuerAdmissionControlValue.State.INSTALLED); + assertThat(installed.liveBarrierEpoch()).isEqualTo(pending.liveBarrierEpoch()); + assertThat(installed.cohortDigest()).isEqualTo(pending.cohortDigest()); + assertThat( + state + .fixture() + .dsl() + .fetch( + "SELECT to_jsonb(c)::text AS image FROM" + + " game_session_canonical_issuer_admission_cohort_row c" + + " WHERE operation_id = ? ORDER BY row_ordinal", + cutoffOperationId) + .getValues("image", String.class)) + .containsExactlyElementsOf(frozenRows); + var completedTarget = + state + .fixture() + .dsl() + .fetchSingle( + "SELECT target_source_digest, closed_payload_digest, target_state," + + " exact_closed_readback_bytes FROM game_session_canonical_issuer_admission_cutoff_target" + + " WHERE operation_id = ?", + cutoffOperationId); + assertThat(completedTarget.get("target_source_digest", String.class)) + .isEqualTo(frozenTarget.get("target_source_digest", String.class)); + assertThat(completedTarget.get("closed_payload_digest", String.class)) + .isEqualTo(frozenTarget.get("closed_payload_digest", String.class)); + assertThat(completedTarget.get("target_state", String.class)).isEqualTo("CLOSED"); + assertThat(completedTarget.get("exact_closed_readback_bytes", byte[].class)) + .containsExactly(target.closedValue().exactBytes()); + assertThatThrownBy(() -> state.owner().initializeAndRead(state.fixture().originalOperationId())) + .isInstanceOf(IllegalStateException.class); + } + + @ParameterizedTest + @ValueSource(strings = {"SOURCE_BYTES", "MISSING_SOURCE", "MISSING_TARGET", "TARGET_DIGEST"}) + void cutoffRefusesChangedOrMissingFrozenEvidence(String corruption) { + FixtureState state = fixtureState(); + state.owner().initializeAndRead(state.fixture().originalOperationId()); + UUID cutoffOperationId = UUID.randomUUID(); + var pending = state.repository().beginCutoff(cutoffOperationId, UUID.randomUUID()); + var target = state.repository().readPreparedCutoffTargets(cutoffOperationId).getFirst(); + // Controlled corruption is confined to a rollback-only SQL transaction. The public owners + // reject ambient transactions, so exercise their shared frozen-evidence verifier directly. + String mutation = + switch (corruption) { + case "SOURCE_BYTES" -> + "UPDATE game_session_canonical_issuer_admission_cohort_row" + + " SET source_row_json = source_row_json || ' ' WHERE operation_id = ?"; + case "MISSING_SOURCE" -> + "DELETE FROM game_session_canonical_issuer_admission_cohort_row WHERE operation_id = ?"; + case "MISSING_TARGET" -> + "DELETE FROM game_session_canonical_issuer_admission_cutoff_target WHERE operation_id = ?"; + case "TARGET_DIGEST" -> + "UPDATE game_session_canonical_issuer_admission_cutoff_target" + + " SET target_source_digest = 'sha256:' || repeat('0', 64) WHERE operation_id = ?"; + default -> throw new IllegalArgumentException(corruption); + }; + var dsl = state.fixture().dsl(); + var before = retainedEvidenceImage(dsl); + String family = + corruption.endsWith("SOURCE") || "SOURCE_BYTES".equals(corruption) + ? "cohort_row" + : "cutoff_target"; + String trigger = + "cohort_row".equals(family) + ? "gs_issuer_admission_cohort_guard" + : "gs_issuer_admission_cutoff_target_guard"; + RuntimeException rollback = new IllegalStateException("Controlled corruption rollback"); + assertThatThrownBy( + () -> + dsl.transaction( + configuration -> { + var transaction = DSL.using(configuration); + transaction.execute( + "ALTER TABLE " + + EVIDENCE_PREFIX + + family + + " DISABLE TRIGGER " + + trigger); + assertThat(transaction.execute(mutation, cutoffOperationId)).isPositive(); + String expectedMessage = + switch (corruption) { + case "SOURCE_BYTES" -> + "cohort source digest differs from its stored JSON"; + case "MISSING_SOURCE" -> + "cohort no longer matches its frozen complete digest"; + case "MISSING_TARGET" -> + "target set differs from its complete frozen cohort"; + case "TARGET_DIGEST" -> + "target differs from its immutable captured source"; + default -> throw new IllegalArgumentException(corruption); + }; + assertThatThrownBy( + () -> + new CanonicalGameplayIssuerAdmissionControlRepository(transaction) + .verifyCurrentCutoffTarget( + transaction, + pending, + target.closedValue().tenantId(), + target.closedValue().playableStateNamespaceId(), + target.closedValue().exactBytes())) + .isInstanceOf(CanonicalGameplayBindingInventoryConflictException.class) + .hasMessageContaining(expectedMessage); + throw rollback; + })) + .isSameAs(rollback); + assertThat(retainedEvidenceImage(dsl)).isEqualTo(before); + assertThat( + state + .repository() + .readPreparedCutoffTarget( + cutoffOperationId, + target.closedValue().tenantId(), + target.closedValue().playableStateNamespaceId()) + .closedValue() + .exactBytes()) + .containsExactly(target.closedValue().exactBytes()); + assertThatThrownBy(() -> state.repository().completeCutoff(cutoffOperationId)) + .isInstanceOf(CanonicalGameplayBindingInventoryConflictException.class) + .hasMessageContaining("Every frozen issuer tenant target must read back CLOSED"); + assertThatThrownBy(() -> dsl.execute(mutation, cutoffOperationId)) + .hasMessageContaining("Retained issuer admission"); + state + .owner() + .closeAndRead( + cutoffOperationId, + target.closedValue().tenantId(), + target.closedValue().playableStateNamespaceId()); + assertThat(state.repository().completeCutoff(cutoffOperationId).state()) + .isEqualTo(CanonicalGameplayIssuerAdmissionControlValue.State.INSTALLED); + } + + @Test + void reusesFrozenTargetInitializerAcrossOperationsRevisionProgressAndOriginAbort() { + FixtureState state = fixtureState(); + UUID originalOperationId = state.fixture().originalOperationId(); + var opened = state.owner().initializeAndRead(originalOperationId); + byte[] originalPayload = opened.exactPhysicalPayload(); + UUID secondAccountId = UUID.randomUUID(); + assertThat(secondAccountId).isNotEqualTo(state.candidate().accountId()); + + CanonicalGameplayIssuerBindingLocalOperation currentOperation = + prepareCurrentOperation(state, "same-target-different-account", secondAccountId); + var originalRetry = state.owner().initializeAndRead(originalOperationId); + assertThat(originalRetry.scriptOutcome()).isEqualTo(2L); + assertThat(originalRetry.exactPhysicalPayload()).containsExactly(originalPayload); + + var abortSource = state.fixture().source(); + new CanonicalGameplayBindingInventoryRepository(state.fixture().dsl()) + .recordFirstNewAccountAbort(abortSource, UUID.randomUUID()); + assertThat( + state + .fixture() + .dsl() + .fetchSingle( + "SELECT status FROM game_session_canonical_binding_transition" + + " WHERE transition_id = ?", + state.fixture().transitionId()) + .get("status", String.class)) + .isEqualTo("ABORTED"); + + var abortedOriginRetry = state.owner().initializeAndRead(originalOperationId); + assertThat(abortedOriginRetry.scriptOutcome()).isEqualTo(2L); + assertThat(abortedOriginRetry.exactPhysicalPayload()).containsExactly(originalPayload); + + var currentCandidateReadback = state.owner().initializeAndRead(currentOperation.operationId()); + assertThat(currentCandidateReadback.scriptOutcome()).isEqualTo(2L); + assertThat(currentCandidateReadback.exactPhysicalPayload()).containsExactly(originalPayload); + + var storedInitializer = + state + .fixture() + .dsl() + .fetchOne( + "SELECT operation_id, open_payload_bytes FROM" + + " game_session_canonical_issuer_admission_initializer" + + " WHERE tenant_id = ? AND playable_state_namespace_id = ?", + state.candidate().tenantId(), + state.candidate().playableStateNamespaceId()); + assertThat(storedInitializer.get("operation_id", UUID.class)).isEqualTo(originalOperationId); + assertThat(storedInitializer.get("open_payload_bytes", byte[].class)) + .containsExactly(originalPayload); + + state.currentState().set(currentIssuerState(state.candidate(), "moved-source")); + assertThatThrownBy(() -> state.owner().initializeAndRead(currentOperation.operationId())) + .isInstanceOf(IllegalStateException.class); + + state.currentState().set(currentIssuerState(state.candidate())); + var prepared = state.repository().readPreparedInitializer(currentOperation.operationId()); + administratorCommands.del(bytes(prepared.key())); + assertThatThrownBy(() -> state.owner().initializeAndRead(currentOperation.operationId())) + .isInstanceOf(IllegalStateException.class); + assertThat(administratorCommands.exists(bytes(prepared.key()))).isZero(); + } + + @Test + void preparedInitializerWithAbortedOriginBlocksAnotherAccountInTheSameTenantNamespace() { + FixtureState state = fixtureState(); + UUID originalOperationId = state.fixture().originalOperationId(); + var original = state.repository().readPreparedInitializer(originalOperationId); + var frozenBeforeAbort = retainedEvidenceImage(state.fixture().dsl()); + assertThat(initializationState(state, originalOperationId)).isEqualTo("PREPARED"); + assertThat(administratorCommands.exists(bytes(original.key()))).isZero(); + assertThat(state.fixture().recordOriginalAccountAbort().isAccountAborted()).isTrue(); + + UUID anotherAccountId = UUID.randomUUID(); + assertThat(anotherAccountId).isNotEqualTo(state.candidate().accountId()); + var anotherOperation = + prepareCurrentOperation(state, "aborted-unclaimed-origin", anotherAccountId); + var retained = state.repository().readPreparedInitializer(anotherOperation.operationId()); + assertThat(retained.value().initializer().operationId()).isEqualTo(originalOperationId); + assertThat(retained.value().exactBytes()).containsExactly(original.value().exactBytes()); + assertThat(retained.value().tenantId()).isEqualTo(state.candidate().tenantId()); + assertThat(retained.value().playableStateNamespaceId()) + .isEqualTo(state.candidate().playableStateNamespaceId()); + assertThat(state.repository().claimFirstCreatePermit(retained)).isFalse(); + assertThatThrownBy(() -> state.owner().initializeAndRead(anotherOperation.operationId())) + .isInstanceOf(IllegalStateException.class); + assertThatThrownBy(() -> state.owner().initializeAndRead(originalOperationId)) + .isInstanceOf(IllegalStateException.class); + assertThat(initializationState(state, originalOperationId)).isEqualTo("PREPARED"); + assertThat(countReceipt(state, originalOperationId)).isZero(); + assertThat(administratorCommands.exists(bytes(original.key()))).isZero(); + assertThat(retainedEvidenceImage(state.fixture().dsl())).isEqualTo(frozenBeforeAbort); + } + + @Test + void forwardRetentionGuardsPreservePopulatedV1047EvidenceAndCompleteFlywayHistory() { + FixtureState state = fixtureState(MigrationVersion.fromVersion("1047")); + UUID operationId = state.fixture().originalOperationId(); + state.owner().initializeAndRead(operationId); + UUID cutoffOperationId = UUID.randomUUID(); + UUID cutoffRequestId = UUID.randomUUID(); + var pending = state.repository().beginCutoff(cutoffOperationId, cutoffRequestId); + var before = retainedEvidenceImage(state.fixture().dsl()); + before.values().forEach(rows -> assertThat(rows).isNotEmpty()); + var historyBefore = state.fixture().migrationHistoryImage(); + assertThat( + state + .fixture() + .dsl() + .fetchSingle( + "SELECT version FROM flyway_schema_history ORDER BY installed_rank DESC LIMIT 1") + .get(0, String.class)) + .isEqualTo("1047"); + + assertThat( + state + .fixture() + .upgradeWithDefaultGameSessionMigrations(MigrationVersion.fromVersion("1047.1"))) + .isEqualTo(1); + assertThat(retainedEvidenceImage(state.fixture().dsl())).isEqualTo(before); + var historyAfter = state.fixture().migrationHistoryImage(); + assertThat(historyAfter).hasSize(historyBefore.size() + 1); + assertThat(historyAfter.subList(0, historyBefore.size())) + .containsExactlyElementsOf(historyBefore); + assertThat( + state + .fixture() + .dsl() + .fetchSingle("SELECT script FROM flyway_schema_history WHERE version = '1047.1'") + .get(0, String.class)) + .isEqualTo("V1047.1__issuer_admission_retained_evidence_guards.sql"); + assertThat( + state + .fixture() + .upgradeWithDefaultGameSessionMigrations(MigrationVersion.fromVersion("1047.1"))) + .isZero(); + assertThat(retainedEvidenceImage(state.fixture().dsl())).isEqualTo(before); + assertThat(state.fixture().migrationHistoryImage()).containsExactlyElementsOf(historyAfter); + + assertThat(state.repository().beginCutoff(cutoffOperationId, cutoffRequestId).exactBytes()) + .containsExactly(pending.exactBytes()); + var target = state.repository().readPreparedCutoffTargets(cutoffOperationId).getFirst(); + var closed = + state + .owner() + .closeAndRead( + cutoffOperationId, + target.closedValue().tenantId(), + target.closedValue().playableStateNamespaceId()); + assertThat(closed.scriptOutcome()).isEqualTo(3L); + assertThat( + state + .owner() + .closeAndRead( + cutoffOperationId, + target.closedValue().tenantId(), + target.closedValue().playableStateNamespaceId()) + .scriptOutcome()) + .isEqualTo(2L); + var installed = state.repository().completeCutoff(cutoffOperationId); + assertThat(installed.state()) + .isEqualTo(CanonicalGameplayIssuerAdmissionControlValue.State.INSTALLED); + assertThat(state.repository().completeCutoff(cutoffOperationId).exactBytes()) + .containsExactly(installed.exactBytes()); + assertThat(countReceipt(state, operationId)).isEqualTo(1L); + } + + @ParameterizedTest + @ValueSource( + strings = {"initializer", "initializer_receipt", "cohort_row", "cutoff_target", "operation"}) + void retainedEvidenceRejectsDirectUpdateDeleteAndTruncate(String family) { + FixtureState state = fixtureState(); + state.owner().initializeAndRead(state.fixture().originalOperationId()); + state.repository().beginCutoff(UUID.randomUUID(), UUID.randomUUID()); + var dsl = state.fixture().dsl(); + String table = EVIDENCE_PREFIX + family; + String update = + switch (family) { + case "initializer" -> "initialization_state = 'PREPARED'"; + case "initializer_receipt" -> "script_outcome = script_outcome"; + case "cohort_row" -> "source_row_json = source_row_json || ' '"; + case "cutoff_target" -> "target_source_digest = 'sha256:' || repeat('0', 64)"; + case "operation" -> "operation_state = operation_state"; + default -> throw new IllegalArgumentException(family); + }; + var before = retainedEvidenceImage(dsl); + assertThatThrownBy(() -> dsl.execute("UPDATE " + table + " SET " + update)) + .hasMessageContaining("Retained issuer admission"); + assertThatThrownBy(() -> dsl.execute("DELETE FROM " + table)) + .hasMessageContaining("Retained issuer admission"); + assertThatThrownBy(() -> dsl.execute("TRUNCATE TABLE " + table + " CASCADE")) + .hasMessageContaining("Retained issuer admission"); + assertThat(retainedEvidenceImage(dsl)).isEqualTo(before); + } + + @ParameterizedTest + @ValueSource( + strings = { + "INITIALIZER_SKIP", + "INITIALIZER_ID", + "INITIALIZER_PAYLOAD", + "INITIALIZER_REARM", + "TARGET_ID", + "TARGET_PAYLOAD", + "TARGET_PARTIAL", + "TARGET_READBACK", + "TARGET_REWRITE", + "OPERATION_SOURCE", + "OPERATION_REOPEN" + }) + void retainedEvidenceRejectsIllegalTransitionsIdentityAndPayloadChanges(String change) { + FixtureState state = fixtureState(); + UUID operationId = state.fixture().originalOperationId(); + var prepared = state.repository().readPreparedInitializer(operationId); + if ("INITIALIZER_REARM".equals(change)) { + assertThat(state.repository().claimFirstCreatePermit(prepared)).isTrue(); + } + UUID cutoffOperationId = UUID.randomUUID(); + state.repository().beginCutoff(cutoffOperationId, UUID.randomUUID()); + if ("TARGET_REWRITE".equals(change)) { + var target = state.repository().readPreparedCutoffTargets(cutoffOperationId).getFirst(); + state + .owner() + .closeAndRead( + cutoffOperationId, + target.closedValue().tenantId(), + target.closedValue().playableStateNamespaceId()); + } + var dsl = state.fixture().dsl(); + String mutation = + switch (change) { + case "INITIALIZER_SKIP" -> "initializer SET initialization_state = 'OPEN_CONFIRMED'"; + case "INITIALIZER_ID" -> + "initializer SET operation_id = '11111111-1111-4111-8111-111111111111'"; + case "INITIALIZER_PAYLOAD" -> + "initializer SET open_payload_bytes = convert_to('changed', 'UTF8')"; + case "INITIALIZER_REARM" -> "initializer SET initialization_state = 'PREPARED'"; + case "TARGET_ID" -> "cutoff_target SET target_ordinal = target_ordinal + 1"; + case "TARGET_PAYLOAD" -> + "cutoff_target SET closed_payload_bytes = convert_to('changed', 'UTF8')"; + case "TARGET_PARTIAL" -> "cutoff_target SET target_state = 'CLOSED'"; + case "TARGET_READBACK" -> + "cutoff_target SET target_state = 'CLOSED', script_outcome = 1," + + " exact_closed_readback_bytes = convert_to('changed', 'UTF8')," + + " exact_closed_readback_digest = closed_payload_digest"; + case "TARGET_REWRITE" -> "cutoff_target SET script_outcome = 2"; + case "OPERATION_SOURCE" -> "operation SET cohort_digest = 'sha256:' || repeat('0', 64)"; + case "OPERATION_REOPEN" -> + "operation SET operation_state = 'OPEN' WHERE operation_kind = 'CUTOFF'"; + default -> throw new IllegalArgumentException(change); + }; + var before = retainedEvidenceImage(dsl); + assertThatThrownBy(() -> dsl.execute("UPDATE " + EVIDENCE_PREFIX + mutation)) + .hasMessageContaining("Retained issuer admission"); + assertThat(retainedEvidenceImage(dsl)).isEqualTo(before); + } + + @ParameterizedTest + @ValueSource(booleans = {false, true}) + void forwardLiveControlGuardsPreserveV1047_1RowsAndSameEpochCutoffCompletion( + boolean cutoffBeforeUpgrade) { + FixtureState state = fixtureState(MigrationVersion.fromVersion("1047.1")); + var opened = state.owner().initializeAndRead(state.fixture().originalOperationId()); + UUID cutoffOperationId = UUID.randomUUID(); + UUID cutoffRequestId = UUID.randomUUID(); + if (cutoffBeforeUpgrade) { + state.repository().beginCutoff(cutoffOperationId, cutoffRequestId); + } + var dsl = state.fixture().dsl(); + var before = liveControlEvidenceImage(dsl); + var historyBefore = state.fixture().migrationHistoryImage(); + assertThat( + dsl.fetchSingle( + "SELECT version FROM flyway_schema_history ORDER BY installed_rank DESC LIMIT 1") + .get(0, String.class)) + .isEqualTo("1047.1"); + + assertThat( + state + .fixture() + .upgradeWithDefaultGameSessionMigrations(MigrationVersion.fromVersion("1047.2"))) + .isEqualTo(1); + assertThat(liveControlEvidenceImage(dsl)).isEqualTo(before); + var historyAfter = state.fixture().migrationHistoryImage(); + assertThat(historyAfter).hasSize(historyBefore.size() + 1); + assertThat(historyAfter.subList(0, historyBefore.size())) + .containsExactlyElementsOf(historyBefore); + assertThat( + dsl.fetchSingle("SELECT script FROM flyway_schema_history WHERE version = '1047.2'") + .get(0, String.class)) + .isEqualTo("V1047.2__issuer_admission_live_control_guards.sql"); + assertThat( + state + .fixture() + .upgradeWithDefaultGameSessionMigrations(MigrationVersion.fromVersion("1047.2"))) + .isZero(); + assertThat(liveControlEvidenceImage(dsl)).isEqualTo(before); + assertThat(state.fixture().migrationHistoryImage()).containsExactlyElementsOf(historyAfter); + + var pending = state.repository().beginCutoff(cutoffOperationId, cutoffRequestId); + assertThat(pending.liveBarrierEpoch()).isEqualTo(opened.value().admissionEpoch().add(ONE)); + var pendingImage = liveControlEvidenceImage(dsl); + assertThat(state.repository().beginCutoff(cutoffOperationId, cutoffRequestId).exactBytes()) + .containsExactly(pending.exactBytes()); + assertThat(liveControlEvidenceImage(dsl)).isEqualTo(pendingImage); + var target = state.repository().readPreparedCutoffTargets(cutoffOperationId).getFirst(); + state + .owner() + .closeAndRead( + cutoffOperationId, + target.closedValue().tenantId(), + target.closedValue().playableStateNamespaceId()); + String pendingProvenance = + dsl.fetchSingle( + "SELECT (to_jsonb(control) - ARRAY['state', 'control_exact_bytes'," + + " 'control_exact_digest', 'updated_at'])::text FROM " + + EVIDENCE_PREFIX + + "control control") + .get(0, String.class); + var installed = state.repository().completeCutoff(cutoffOperationId); + assertThat(installed.state()) + .isEqualTo(CanonicalGameplayIssuerAdmissionControlValue.State.INSTALLED); + assertThat(installed.liveBarrierEpoch()).isEqualTo(pending.liveBarrierEpoch()); + assertThat(installed.currentOperationId()).isEqualTo(pending.currentOperationId()); + assertThat(installed.cohortDigest()).isEqualTo(pending.cohortDigest()); + assertThat( + dsl.fetchSingle( + "SELECT (to_jsonb(control) - ARRAY['state', 'control_exact_bytes'," + + " 'control_exact_digest', 'updated_at'])::text FROM " + + EVIDENCE_PREFIX + + "control control") + .get(0, String.class)) + .isEqualTo(pendingProvenance); + var installedImage = liveControlEvidenceImage(dsl); + assertThat(installedImage.get("epoch_counter")).isEqualTo(pendingImage.get("epoch_counter")); + assertThat(state.repository().completeCutoff(cutoffOperationId).exactBytes()) + .containsExactly(installed.exactBytes()); + assertThat(liveControlEvidenceImage(dsl)).isEqualTo(installedImage); + } + + @ParameterizedTest + @ValueSource(booleans = {false, true}) + void liveIssuerCounterOnlyAdvanceFailsAtCommitAndRetainsOriginalAuthority(boolean cutoffPending) { + FixtureState state = fixtureState(); + state.owner().initializeAndRead(state.fixture().originalOperationId()); + if (cutoffPending) { + state.repository().beginCutoff(UUID.randomUUID(), UUID.randomUUID()); + } + var dsl = state.fixture().dsl(); + var before = liveControlEvidenceImage(dsl); + AtomicBoolean allocationExecuted = new AtomicBoolean(); + assertThatThrownBy( + () -> + dsl.transaction( + configuration -> { + DSLContext transaction = DSL.using(configuration); + assertThat( + transaction.execute( + "UPDATE " + + EVIDENCE_PREFIX + + "epoch_counter" + + " SET last_live_barrier_epoch = last_live_barrier_epoch + 1")) + .isEqualTo(1); + assertThat( + transaction + .fetchSingle( + "SELECT counter.last_live_barrier_epoch - control.live_barrier_epoch FROM " + + EVIDENCE_PREFIX + + "epoch_counter counter JOIN " + + EVIDENCE_PREFIX + + "control control USING (issuer_id)") + .get(0, BigInteger.class)) + .isEqualTo(ONE); + allocationExecuted.set(true); + })) + .hasStackTraceContaining("Live issuer admission epoch counter and control"); + assertThat(allocationExecuted).isTrue(); + assertThat(liveControlEvidenceImage(dsl)).isEqualTo(before); + } + + @ParameterizedTest + @ValueSource(booleans = {false, true}) + void liveIssuerGuardUpgradeRejectsIncompatibleRetainedEpochPair(boolean missingControl) { + FixtureState state = fixtureState(MigrationVersion.fromVersion("1047.1")); + var dsl = state.fixture().dsl(); + if (missingControl) { + assertThat(dsl.execute("DELETE FROM " + EVIDENCE_PREFIX + "control")).isEqualTo(1); + } else { + assertThat( + dsl.execute( + "UPDATE " + + EVIDENCE_PREFIX + + "epoch_counter" + + " SET last_live_barrier_epoch = last_live_barrier_epoch + 1")) + .isEqualTo(1); + } + var before = liveControlEvidenceImage(dsl); + var historyBefore = state.fixture().migrationHistoryImage(); + assertThatThrownBy( + () -> + state + .fixture() + .upgradeWithDefaultGameSessionMigrations( + MigrationVersion.fromVersion("1047.2"))) + .hasStackTraceContaining("Live issuer admission epoch counter and control"); + assertThat(liveControlEvidenceImage(dsl)).isEqualTo(before); + assertThat(state.fixture().migrationHistoryImage()).containsExactlyElementsOf(historyBefore); + } + + @ParameterizedTest + @ValueSource(strings = {"epoch_counter", "control"}) + void liveIssuerAuthorityRejectsResetRemovalAndProvenanceRewrites(String family) { + FixtureState state = fixtureState(); + var dsl = state.fixture().dsl(); + String table = EVIDENCE_PREFIX + family; + var before = liveControlEvidenceImage(dsl); + String cutoffTransition = + "state = 'CUTOFF_PENDING', current_operation_kind = 'CUTOFF'," + + " current_operation_id = '11111111-1111-4111-8111-111111111111'," + + " live_barrier_epoch = live_barrier_epoch + 1, "; + List changes = + "epoch_counter".equals(family) + ? List.of( + "last_live_barrier_epoch = last_live_barrier_epoch - 1", + "last_live_barrier_epoch = 0", + "last_live_barrier_epoch = last_live_barrier_epoch", + "last_live_barrier_epoch = last_live_barrier_epoch + 2", + "issuer_id = 'changed-issuer', last_live_barrier_epoch = last_live_barrier_epoch + 1") + : List.of( + "live_barrier_epoch = live_barrier_epoch - 1", + "live_barrier_epoch = 0", + "live_barrier_epoch = live_barrier_epoch", + "state = 'INSTALLED', current_operation_kind = 'CUTOFF'", + "state = 'CUTOFF_PENDING', current_operation_kind = 'CUTOFF'," + + " current_operation_id = '11111111-1111-4111-8111-111111111111'", + "state = 'CUTOFF_PENDING', current_operation_kind = 'CUTOFF'," + + " current_operation_id = '11111111-1111-4111-8111-111111111111'," + + " live_barrier_epoch = live_barrier_epoch + 2", + cutoffTransition + "anchor_exact_bytes = convert_to('changed', 'UTF8')", + cutoffTransition + "account_checkpoint_bytes = convert_to('changed', 'UTF8')", + cutoffTransition + "stable_incarnation_bytes = convert_to('changed', 'UTF8')"); + for (String change : changes) { + assertThatThrownBy(() -> dsl.execute("UPDATE " + table + " SET " + change)) + .as(change) + .hasMessageContaining("Live issuer admission"); + } + assertThatThrownBy(() -> dsl.execute("DELETE FROM " + table)) + .hasMessageContaining("Live issuer admission"); + assertThatThrownBy(() -> dsl.execute("TRUNCATE TABLE " + table + " CASCADE")) + .hasMessageContaining("Live issuer admission"); + assertThat(liveControlEvidenceImage(dsl)).isEqualTo(before); + } + + @Test + void liveIssuerCutoffCompletionFreezesEpochOperationCohortAndSourceAndCannotReopen() { + FixtureState state = fixtureState(); + state.owner().initializeAndRead(state.fixture().originalOperationId()); + UUID cutoffOperationId = UUID.randomUUID(); + state.repository().beginCutoff(cutoffOperationId, UUID.randomUUID()); + var dsl = state.fixture().dsl(); + var pendingImage = liveControlEvidenceImage(dsl); + for (String change : + List.of( + "state = 'OPEN', current_operation_kind = 'INITIAL_ANCHOR_INSTALL'", + "state = 'CUTOFF_PENDING'", + "state = 'INSTALLED', live_barrier_epoch = live_barrier_epoch + 1", + "state = 'INSTALLED', live_barrier_epoch = live_barrier_epoch - 1", + "state = 'INSTALLED', current_operation_id = '11111111-1111-4111-8111-111111111111'", + "state = 'INSTALLED', cohort_row_count = cohort_row_count + 1", + "state = 'INSTALLED', cohort_digest = 'sha256:' || repeat('0', 64)", + "state = 'INSTALLED', bootstrap_control_epoch = bootstrap_control_epoch + 1", + "state = 'INSTALLED', account_checkpoint_bytes = convert_to('changed', 'UTF8')", + "state = 'INSTALLED', anchor_exact_bytes = convert_to('changed', 'UTF8')", + "state = 'INSTALLED', stable_incarnation_bytes = convert_to('changed', 'UTF8')")) { + assertThatThrownBy(() -> dsl.execute("UPDATE " + EVIDENCE_PREFIX + "control SET " + change)) + .as(change) + .hasMessageContaining("Live issuer admission"); + } + assertThat(liveControlEvidenceImage(dsl)).isEqualTo(pendingImage); + var target = state.repository().readPreparedCutoffTargets(cutoffOperationId).getFirst(); + state + .owner() + .closeAndRead( + cutoffOperationId, + target.closedValue().tenantId(), + target.closedValue().playableStateNamespaceId()); + var installed = state.repository().completeCutoff(cutoffOperationId); + var installedImage = liveControlEvidenceImage(dsl); + for (String change : + List.of( + "state = 'INSTALLED'", + "state = 'OPEN', current_operation_kind = 'INITIAL_ANCHOR_INSTALL'", + "state = 'CUTOFF_PENDING', live_barrier_epoch = live_barrier_epoch + 1")) { + assertThatThrownBy(() -> dsl.execute("UPDATE " + EVIDENCE_PREFIX + "control SET " + change)) + .as(change) + .hasMessageContaining("Live issuer admission"); + } + assertThat(state.repository().completeCutoff(cutoffOperationId).exactBytes()) + .containsExactly(installed.exactBytes()); + assertThat(liveControlEvidenceImage(dsl)).isEqualTo(installedImage); + } + + private static Map> liveControlEvidenceImage(DSLContext dsl) { + Map> snapshots = new LinkedHashMap<>(retainedEvidenceImage(dsl)); + for (String family : List.of("epoch_counter", "control")) { + snapshots.put( + family, + dsl.fetch( + "SELECT to_jsonb(evidence)::text || ':' || xmin::text AS image FROM " + + EVIDENCE_PREFIX + + family + + " evidence ORDER BY to_jsonb(evidence)::text") + .getValues("image", String.class)); + } + return snapshots; + } + + private static Map> retainedEvidenceImage(DSLContext dsl) { + Map> snapshots = new LinkedHashMap<>(); + for (String family : EVIDENCE_TABLES) { + snapshots.put( + family, + dsl.fetch( + "SELECT to_jsonb(evidence)::text || ':' || xmin::text AS image FROM " + + EVIDENCE_PREFIX + + family + + " evidence ORDER BY to_jsonb(evidence)::text") + .getValues("image", String.class)); + } + return snapshots; + } + + @Test + void callerOwnedJooqTransactionRefusesBeforeSourceOrRemoteDispatch() { + FixtureState state = fixtureState(); + var dsl = state.fixture().dsl(); + var current = state.currentState().get(); + var anchor = + dsl.transactionResult( + configuration -> { + var transaction = org.jooq.impl.DSL.using(configuration); + CanonicalGameplayBindingInventoryRepository.lockInventoryRevision(transaction); + return CanonicalGameplayIssuerBootstrapCoverageRepository + .readInstalledAnchorForBindingPreparationInTransaction(transaction, current); + }); + AtomicBoolean sourceCalled = new AtomicBoolean(); + CanonicalGameplayIssuerBootstrapPartitionRedisOwner.CurrentIssuerStateSource source = + () -> { + sourceCalled.set(true); + return current; + }; + dsl.transaction( + configuration -> { + var transaction = org.jooq.impl.DSL.using(configuration); + var repository = + new CanonicalGameplayIssuerAdmissionBarrierRepository( + transaction, + new CanonicalGameplayTenantGameplayTagRepository( + transaction, state.fixture().target().targetNamespace(), 1), + source); + assertThatThrownBy( + () -> repository.readPreparedInitializer(state.fixture().originalOperationId())) + .isInstanceOf(CanonicalGameplayBindingInventoryConflictException.class) + .hasMessageContaining("jOOQ transaction"); + assertThatThrownBy( + () -> + new CanonicalGameplayIssuerAdmissionControlRepository(transaction) + .installInitialOpen(anchor, source)) + .isInstanceOf(CanonicalGameplayBindingInventoryConflictException.class) + .hasMessageContaining("jOOQ transaction"); + }); + assertThat(sourceCalled).isFalse(); + assertThat( + dsl.fetchCount( + org.jooq.impl.DSL.table("game_session_canonical_issuer_admission_initializer"))) + .isZero(); + } + + private FixtureState fixtureState() { + return fixtureState(null); + } + + private FixtureState fixtureState(MigrationVersion migrationTarget) { + Candidate candidate = candidate(); + DriverManagerDataSource accountDataSource = new DriverManagerDataSource(); + accountDataSource.setDriverClassName("org.postgresql.Driver"); + String jdbcUrl = POSTGRES.getJdbcUrl(); + accountDataSource.setUrl( + jdbcUrl + (jdbcUrl.contains("?") ? "&" : "?") + "currentSchema=public"); + accountDataSource.setUsername(POSTGRES.getUsername()); + accountDataSource.setPassword(POSTGRES.getPassword()); + fixture = + migrationTarget == null + ? new CanonicalGameplayAdmissionAbortCompositionFixture( + accountDataSource, candidate, ownerClient, 0) + : CanonicalGameplayAdmissionAbortCompositionFixture.atHistoricalIssuerAdmissionFrontier( + accountDataSource, candidate, ownerClient, migrationTarget); + Candidate actualCandidate = fixture.candidate(); + CanonicalGameplayBindingIdentity identity = identity(actualCandidate); + fixture.publish(controlledLeaseEvidence(identity, fixture.generation(), fixture.target())); + // Controlled upstream Account current-source and stable-incarnation inputs; native SQL/Redis + // owners execute below, but this fixture does not establish production source custody. + var currentState = new AtomicReference<>(currentIssuerState(actualCandidate)); + var sourceReader = + (CanonicalGameplayIssuerBootstrapPartitionRedisOwner.CurrentIssuerStateSource) + currentState::get; + var repository = + new CanonicalGameplayIssuerAdmissionBarrierRepository( + fixture.dsl(), + new CanonicalGameplayTenantGameplayTagRepository( + fixture.dsl(), fixture.target().targetNamespace(), 1), + sourceReader); + return new FixtureState( + fixture, + actualCandidate, + repository, + new CanonicalGameplayIssuerAdmissionBarrierRedisOwner( + ownerClient, + RedisScriptCatalog.fromContributions( + List.of(new CanonicalGameplayIssuerAdmissionBarrierRedisScriptContribution())), + repository, + sourceReader), + ownerClient, + currentState); + } + + private CanonicalGameplayIssuerBindingLocalOperation prepareCurrentOperation( + FixtureState state, String seed, UUID accountId) { + Candidate candidate = state.candidate(); + CanonicalGameplayBindingIdentity identity = + new CanonicalGameplayBindingIdentity( + accountId, + candidate.tenantId(), + candidate.playableStateNamespaceId(), + UUID.randomUUID(), + candidate.playableStateScope(), + candidate.gameInstanceId(), + candidate.runtimeGameInstanceId(), + UUID.randomUUID().toString(), + candidate.regionId(), + candidate.regionEpoch(), + candidate.issuerId(), + candidate.issuerAuthGeneration(), + candidate.issuerIndexLayoutVersion(), + candidate.issuerIndexPartitionCount(), + candidate.issuerIndexPartitionCapacity()); + UUID transitionId = UUID.randomUUID(); + var request = + new CanonicalGameplayIssuerBindingLocalOperation.Request( + UUID.randomUUID(), transitionId, identity, null, null); + var operation = + new CanonicalGameplayIssuerBindingLocalOperationRepository( + state.fixture().dsl(), state.sourceReader()) + .beginOrResumeOrdinaryNew(request); + var localCatalog = + RedisScriptCatalog.fromContributions( + List.of(new CanonicalGameplayIssuerBindingLocalRedisScriptContribution())); + var localProjection = + new CanonicalGameplayIssuerBindingLocalProjectionRepository( + state.fixture().dsl(), state.sourceReader()); + var localOwner = + new CanonicalGameplayIssuerBindingLocalRedisOwner( + ownerClient, localCatalog, localProjection, state.sourceReader()); + // Capacity is a distinct physical phase: publish it while SQL is still PREPARED. + localOwner.projectAndRead(operation); + var inventory = new CanonicalGameplayBindingInventoryRepository(state.fixture().dsl()); + var provisionalEvidence = inventory.readProvisionalCasEvidence(transitionId); + var lease = + controlledLeaseEvidence( + identity, operation.preparedTransition().bindingGeneration(), state.fixture().target()); + inventory.markProvisional( + provisionalEvidence, + new CanonicalGameplayAdmissionDecision( + transitionId, + lease, + identity, + operation.preparedTransition().bindingGeneration(), + null, + state.fixture().source().originalDecision().targetEvidence())); + localOwner.projectAndRead(operation); + return operation; + } + + private static Candidate candidate() { + return new Candidate( + UUID.randomUUID(), + UUID.randomUUID(), + UUID.randomUUID(), + UUID.randomUUID(), + "controlled-scope", + UUID.randomUUID(), + 1L, + UUID.randomUUID(), + UUID.randomUUID(), + ONE, + ISSUER, + ONE, + BigInteger.valueOf(3), + ONE, + BigInteger.valueOf(2)); + } + + private static CanonicalGameplayBindingIdentity identity(Candidate candidate) { + return new CanonicalGameplayBindingIdentity( + candidate.accountId(), + candidate.tenantId(), + candidate.playableStateNamespaceId(), + candidate.characterId(), + candidate.playableStateScope(), + candidate.gameInstanceId(), + candidate.runtimeGameInstanceId(), + candidate.sessionId().toString(), + candidate.regionId(), + candidate.regionEpoch(), + candidate.issuerId(), + candidate.issuerAuthGeneration(), + candidate.issuerIndexLayoutVersion(), + candidate.issuerIndexPartitionCount(), + candidate.issuerIndexPartitionCapacity()); + } + + private static CanonicalGameplayIssuerBootstrapPartitionRedisOwner.CurrentIssuerState + currentIssuerState(Candidate candidate) { + return currentIssuerState(candidate, "controlled-release-composition"); + } + + private static CanonicalGameplayIssuerBootstrapPartitionRedisOwner.CurrentIssuerState + currentIssuerState(Candidate candidate, String seed) { + byte[] checkpoint = + ("controlled-initial-issuer-checkpoint/v1|" + candidate.issuerId() + "|1") + .getBytes(StandardCharsets.UTF_8); + var sourceCheckpoint = + new CanonicalGameplayIssuerLayoutBootstrapIntent.AccountIssuerSourceCheckpoint( + candidate.issuerId(), + candidate.issuerAuthGeneration(), + checkpoint, + CanonicalGameplayIssuerMemberV2Codec.sha256(checkpoint), + null, + null); + String digest = + CanonicalGameplayIssuerMemberV2Codec.sha256(seed.getBytes(StandardCharsets.UTF_8)); + var deployment = + new CanonicalGameplayProtectedIncarnationReceiver.ExpectedTargetDeploymentEvidence( + "controlled-release-deployment-" + seed, + "controlled-release-generation-" + seed, + List.of("controlled-release-node-" + seed), + "controlled-release-redis-build-" + seed, + "controlled-release-registry-" + seed, + digest, + "READY", + "controlled-release-boot-" + seed, + "controlled-release-startup-" + seed, + "controlled-release-storage-" + seed, + "controlled-release-aof-" + seed); + var incarnation = + new CanonicalGameplayIssuerMemberV2Value.Incarnation( + "controlled-release-attestor-" + seed, digest, deployment, digest, digest); + return new CanonicalGameplayIssuerBootstrapPartitionRedisOwner.CurrentIssuerState( + sourceCheckpoint, incarnation); + } + + private static AccountGameplayAdmissionLeaseEvidence controlledLeaseEvidence( + CanonicalGameplayBindingIdentity candidate, BigInteger bindingGeneration, Target target) { + long now = System.currentTimeMillis(); + String nowSeconds = Long.toString(now / 1000L); + Map carrier = new LinkedHashMap<>(); + carrier.put("schema", AccountGameplayAdmissionLeaseEvidence.SCHEMA); + carrier.put("schemaVersion", "1"); + carrier.put("mode", "PUBLIC_PRODUCTION"); + carrier.put("leaseKind", AccountGameplayAdmissionLeaseEvidence.LeaseKind.NEW_BINDING.name()); + carrier.put("targetNamespace", target.targetNamespace()); + carrier.put( + "callerWorkload", + "spiffe://firemud/ns/" + target.targetNamespace() + "/sa/game-session-service"); + carrier.put("requestId", UUID.randomUUID().toString()); + carrier.put("leaseId", UUID.randomUUID().toString()); + carrier.put("leaseFence", "1"); + Map scope = new LinkedHashMap<>(); + scope.put("accountId", candidate.accountId().toString()); + scope.put("tenantId", candidate.tenantId().toString()); + scope.put("realmId", target.realmId().toString()); + scope.put("worldSlug", target.worldSlug()); + scope.put("realmSlug", target.realmSlug()); + scope.put("playableStateNamespaceId", target.playableStateNamespaceId().toString()); + scope.put("playableStateScope", target.playableStateScope()); + scope.put("gameInstanceId", target.canonicalGameInstanceId().toString()); + scope.put("characterId", candidate.characterId().toString()); + scope.put("sessionId", candidate.sessionId().toString()); + scope.put("bindingGeneration", bindingGeneration.toString()); + scope.put("catalogRevision", Long.toString(target.catalogRevision())); + scope.put("pointerVersion", Long.toString(target.pointerVersion())); + scope.put("regionId", candidate.regionId().toString()); + scope.put("regionEpoch", candidate.regionEpoch().toString()); + carrier.put("bindingScope", scope); + Map authority = new LinkedHashMap<>(); + authority.put("issuerAuthGeneration", candidate.issuerAuthGeneration().toString()); + authority.put("accountAuthorityGeneration", "1"); + authority.put("tenantAuthorityGeneration", Map.of(candidate.tenantId().toString(), "1")); + authority.put("membershipAuthorityGeneration", Map.of(candidate.tenantId().toString(), "1")); + authority.put("privateRealmGrantVersions", List.of()); + carrier.put("authorityTuple", authority); + carrier.put("issuanceFence", "1"); + carrier.put( + "membershipBaseline", + new LinkedHashMap<>( + Map.of( + "membershipLifecycleState", "ACTIVE", + "membershipVersion", Map.of(candidate.tenantId().toString(), "1"), + "membershipAuthorityGeneration", "1"))); + String prefix = "account:auth-authority:v1:"; + carrier.put( + "outboxCheckpoints", + List.of( + checkpoint(prefix + "account/" + candidate.accountId(), "0"), + checkpoint(prefix + "issuer/" + ISSUER, "0"), + checkpoint( + prefix + "membership/" + candidate.accountId() + "/" + candidate.tenantId(), "1"), + checkpoint(prefix + "tenant/" + candidate.tenantId(), "1"))); + Map tokenIdentity = new LinkedHashMap<>(); + tokenIdentity.put("accountId", candidate.accountId().toString()); + tokenIdentity.put("operationId", UUID.randomUUID().toString()); + tokenIdentity.put("issuanceRequestId", UUID.randomUUID().toString()); + tokenIdentity.put("tokenJti", UUID.randomUUID().toString()); + tokenIdentity.put("tokenSHA256", "a".repeat(64)); + tokenIdentity.put("tokenProfile", "game-session-account-delegation"); + tokenIdentity.put("tokenGeneration", "1"); + tokenIdentity.put("issuanceFence", "1"); + tokenIdentity.put("tokenIdentityFence", "1"); + tokenIdentity.put("issuedAt", nowSeconds); + tokenIdentity.put("notBefore", nowSeconds); + tokenIdentity.put("expiresAt", Long.toString(now / 1000L + 60L)); + carrier.put("tokenIdentityEvidence", tokenIdentity); + carrier.put("evaluatedAt", Long.toString(now)); + carrier.put( + "expiresAt", + Long.toString(now + AccountGameplayAdmissionLeaseEvidence.MAX_DURATION_MILLIS)); + return AccountGameplayAdmissionLeaseEvidence.fromCarrier(carrier); + } + + private static Map checkpoint(String key, String sequence) { + return new LinkedHashMap<>(Map.of("outboxStreamKey", key, "outboxSequence", sequence)); + } + + private static String initializationState(FixtureState state, UUID operationId) { + return state + .fixture() + .dsl() + .fetchSingle( + "SELECT initialization_state FROM game_session_canonical_issuer_admission_initializer" + + " WHERE operation_id = ?", + operationId) + .get("initialization_state", String.class); + } + + private static long countReceipt(FixtureState state, UUID operationId) { + return state + .fixture() + .dsl() + .fetchSingle( + "SELECT count(*) AS receipt_count" + + " FROM game_session_canonical_issuer_admission_initializer_receipt" + + " WHERE operation_id = ?", + operationId) + .get("receipt_count", Long.class); + } + + private void writePhysicalValue(String key, CanonicalGameplayIssuerAdmissionBarrierValue value) { + var initializer = value.initializer(); + Map fields = new LinkedHashMap<>(); + fields.put("schema", CanonicalGameplayIssuerAdmissionBarrierValue.SCHEMA); + fields.put("issuerId", value.issuerId()); + fields.put("tenantId", value.tenantId().toString()); + fields.put("playableStateNamespaceId", value.playableStateNamespaceId().toString()); + fields.put("tenantGameplayTag", value.tenantGameplayTag()); + fields.put("state", value.state().name()); + fields.put("admissionEpoch", value.admissionEpoch().toString()); + fields.put("ownerOperationId", value.ownerOperationId().toString()); + fields.put( + "initializerOperationId", + initializer == null ? "none" : initializer.operationId().toString()); + fields.put( + "initializerEpoch", initializer == null ? "0" : initializer.admissionEpoch().toString()); + fields.put("initializerDigest", initializer == null ? "none" : initializer.exactDigest()); + fields.put("payloadDigest", value.exactDigest()); + for (Map.Entry field : fields.entrySet()) { + administratorCommands.hset(bytes(key), bytes(field.getKey()), bytes(field.getValue())); + } + administratorCommands.hset(bytes(key), bytes("payload"), value.exactBytes()); + } + + private static RedisClient createRedisClient(String username, String password) { + RedisURI.Builder builder = RedisURI.Builder.redis(REDIS.getHost(), REDIS.getMappedPort(6379)); + if (username != null) builder.withAuthentication(username, password); + RedisURI uri = builder.build(); + uri.setTimeout(Duration.ofSeconds(5)); + RedisClient client = RedisClient.create(uri); + client.setOptions( + ClientOptions.builder() + .autoReconnect(false) + .protocolVersion(io.lettuce.core.protocol.ProtocolVersion.RESP2) + .build()); + return client; + } + + private static byte[] bytes(String value) { + return value.getBytes(StandardCharsets.US_ASCII); + } + + private static class ForwardingProjectionRepository + implements CanonicalGameplayIssuerAdmissionBarrierRedisOwner.ProjectionRepository { + private final CanonicalGameplayIssuerAdmissionBarrierRedisOwner.ProjectionRepository delegate; + + ForwardingProjectionRepository( + CanonicalGameplayIssuerAdmissionBarrierRedisOwner.ProjectionRepository delegate) { + this.delegate = delegate; + } + + @Override + public CanonicalGameplayIssuerAdmissionBarrierRedisOwner.PreparedInitializer + readPreparedInitializer(UUID operationId) { + return delegate.readPreparedInitializer(operationId); + } + + @Override + public boolean claimFirstCreatePermit( + CanonicalGameplayIssuerAdmissionBarrierRedisOwner.PreparedInitializer prepared) { + return delegate.claimFirstCreatePermit(prepared); + } + + @Override + public CanonicalGameplayIssuerAdmissionBarrierRedisOwner.PreparedCutoffTarget + readPreparedCutoffTarget(UUID operationId, UUID tenantId, UUID namespaceId) { + return delegate.readPreparedCutoffTarget(operationId, tenantId, namespaceId); + } + + @Override + public void requireStillCurrent( + CanonicalGameplayIssuerAdmissionBarrierRedisOwner.PreparedInitializer prepared) { + delegate.requireStillCurrent(prepared); + } + + @Override + public void requireStillCurrent( + CanonicalGameplayIssuerAdmissionBarrierRedisOwner.PreparedCutoffTarget prepared) { + delegate.requireStillCurrent(prepared); + } + + @Override + public void recordOpenReadback( + CanonicalGameplayIssuerAdmissionBarrierRedisOwner.PreparedInitializer prepared, + CanonicalGameplayIssuerAdmissionBarrierRedisOwner.Readback readback) { + delegate.recordOpenReadback(prepared, readback); + } + + @Override + public void recordClosedReadback( + CanonicalGameplayIssuerAdmissionBarrierRedisOwner.PreparedCutoffTarget prepared, + CanonicalGameplayIssuerAdmissionBarrierRedisOwner.Readback readback) { + delegate.recordClosedReadback(prepared, readback); + } + } + + private record FixtureState( + CanonicalGameplayAdmissionAbortCompositionFixture fixture, + Candidate candidate, + CanonicalGameplayIssuerAdmissionBarrierRepository repository, + CanonicalGameplayIssuerAdmissionBarrierRedisOwner owner, + RedisClient ownerClient, + AtomicReference + currentState) { + private CanonicalGameplayIssuerBootstrapPartitionRedisOwner.CurrentIssuerStateSource + sourceReader() { + return currentState::get; + } + + private CanonicalGameplayIssuerAdmissionBarrierRedisOwner owner( + CanonicalGameplayIssuerAdmissionBarrierRedisOwner.ProjectionRepository + projectionRepository) { + return new CanonicalGameplayIssuerAdmissionBarrierRedisOwner( + ownerClient, + RedisScriptCatalog.fromContributions( + List.of(new CanonicalGameplayIssuerAdmissionBarrierRedisScriptContribution())), + projectionRepository, + sourceReader()); + } + } +} diff --git a/services/game-session-service/src/test/java/integration/net/firedevops/firemud/gamesession/repository/CanonicalGameplayIssuerBindingLocalOperationRepositoryIntegrationTest.java b/services/game-session-service/src/test/java/integration/net/firedevops/firemud/gamesession/repository/CanonicalGameplayIssuerBindingLocalOperationRepositoryIntegrationTest.java index f8d6c3c323..0e3850c7cd 100644 --- a/services/game-session-service/src/test/java/integration/net/firedevops/firemud/gamesession/repository/CanonicalGameplayIssuerBindingLocalOperationRepositoryIntegrationTest.java +++ b/services/game-session-service/src/test/java/integration/net/firedevops/firemud/gamesession/repository/CanonicalGameplayIssuerBindingLocalOperationRepositoryIntegrationTest.java @@ -32,12 +32,9 @@ import org.flywaydb.core.Flyway; import org.flywaydb.core.api.MigrationVersion; import org.jooq.DSLContext; -import org.jooq.ExecuteContext; import org.jooq.Record; import org.jooq.SQLDialect; import org.jooq.impl.DSL; -import org.jooq.impl.DefaultExecuteListener; -import org.jooq.impl.DefaultExecuteListenerProvider; import org.junit.jupiter.api.AfterEach; import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.Test; @@ -143,6 +140,12 @@ void registersOrdinaryNewAgainstInstalledAnchorAndReusesExactPendingOperation() CanonicalGameplayIssuerInstalledAnchor anchor = initialCoverageOwner(dsl, currentState::get) .completeInitialBootstrap(intent.operationId(), bootstrapRequestId); + assertThatThrownBy(() -> operationRepository.beginOrResumeOrdinaryNew(firstRequest)) + .isInstanceOf(CanonicalGameplayBindingInventoryConflictException.class) + .hasMessageContaining("positive live admission-control row"); + assertThat(count(dsl, "game_session_canonical_issuer_binding_local_operation")).isZero(); + new CanonicalGameplayIssuerAdmissionControlRepository(dsl) + .installInitialOpen(anchor, currentState::get); String installedAnchorImage = anchorImage(dsl); String installedProofImage = proofImage(dsl); String initialReservationImage = reservationImage(dsl); @@ -465,6 +468,8 @@ void localIssuerOwnerRetainsPairedNullSourceEventEvidence() { var anchor = initialCoverageOwner(dsl, () -> currentState) .completeInitialBootstrap(intent.operationId(), intent.requestId()); + new CanonicalGameplayIssuerAdmissionControlRepository(dsl) + .installInitialOpen(anchor, () -> currentState); var operation = new CanonicalGameplayIssuerBindingLocalOperationRepository(dsl, () -> currentState) .beginOrResumeOrdinaryNew( @@ -500,8 +505,11 @@ void ordinaryNewPhysicalOperationBoundRefuses257thBeforePreparationAndRetainsExa var currentState = new CanonicalGameplayIssuerBootstrapPartitionRedisOwner.CurrentIssuerState( intent.sourceCheckpoint(), stableIncarnation("physical-operation-bound")); - initialCoverageOwner(dsl, () -> currentState) - .completeInitialBootstrap(intent.operationId(), bootstrapRequestId); + var anchor = + initialCoverageOwner(dsl, () -> currentState) + .completeInitialBootstrap(intent.operationId(), bootstrapRequestId); + new CanonicalGameplayIssuerAdmissionControlRepository(dsl) + .installInitialOpen(anchor, () -> currentState); var repository = new CanonicalGameplayIssuerBindingLocalOperationRepository(dsl, () -> currentState); // Every retained registration is created by the actual SQL owner. No local projection or @@ -565,16 +573,10 @@ void forwardMigrationRetainsCommittedAndPendingPhysicalMutationLineage() { var anchor = initialCoverageOwner(dsl, () -> state) .completeInitialBootstrap(intent.operationId(), intent.requestId()); - // This historical phase has no V1040.5 membership table. Adapt only its slot-count read; - // registration still uses the actual owner and all enabled old-schema guards. This does not - // qualify the new membership gate before that schema exists. - AtomicInteger oldPhaseSlotCountSubstitutions = new AtomicInteger(); - var local = - new CanonicalGameplayIssuerBindingLocalOperationRepository( - preMembershipLocalProducer(dsl, oldPhaseSlotCountSubstitutions), () -> state) - .beginOrResumeOrdinaryNew( - request("migration-request", "migration-transition", identity("migration"))); - assertThat(oldPhaseSlotCountSubstitutions.get()).isEqualTo(1); + // Current ordinary NEW requires V1046 live control, which does not exist at this cut. + // The historical receipt owner is a controlled correlation only; no local operation is minted. + UUID historicalOwnerId = UUID.randomUUID(); + assertThat(count(dsl, "game_session_canonical_issuer_binding_local_operation")).isZero(); UUID committedId = UUID.randomUUID(); UUID pendingId = UUID.randomUUID(); UUID successor = UUID.randomUUID(); @@ -591,15 +593,15 @@ void forwardMigrationRetainsCommittedAndPendingPhysicalMutationLineage() { CanonicalGameplayIssuerPartitionMutationRepository.REVISION_FIELD, successor.toString().getBytes(StandardCharsets.US_ASCII))); // Controlled pre-upgrade SQL receipts exercise retention, immutability and the pending FK. - // They do not claim a Redis mutation/readback or authorize admission; the bootstrap above is - // the actual local SQL/Redis owner, under controlled Account/incarnation collaborators. + // They do not claim an ordinary NEW producer, Redis mutation/readback or admission. The + // bootstrap above uses the actual SQL/Redis owner with controlled Account/incarnation inputs. dsl.transaction( configuration -> { DSLContext transaction = DSL.using(configuration); insertPreLineageMutation( transaction, committedId, - local.operationId(), + historicalOwnerId, "ADD_CAPACITY", initialRevision, successor, @@ -624,7 +626,7 @@ void forwardMigrationRetainsCommittedAndPendingPhysicalMutationLineage() { insertPreLineageMutation( transaction, pendingId, - local.operationId(), + historicalOwnerId, "ADD_BINDING", successor, laterSuccessor, @@ -650,7 +652,7 @@ void forwardMigrationRetainsCommittedAndPendingPhysicalMutationLineage() { dsl.fetch( "SELECT operation_id FROM game_session_canonical_issuer_current_local_operation") .getValues(0, UUID.class)) - .containsExactly(local.operationId()); + .isEmpty(); assertThat( dsl.fetch( "SELECT (to_jsonb(mutation) - 'bootstrap_operation_id')::text" @@ -664,6 +666,7 @@ void forwardMigrationRetainsCommittedAndPendingPhysicalMutationLineage() { .containsExactlyElementsOf(beforeHeads); assertThat(anchorImage(dsl)).isEqualTo(beforeAnchor); assertThat(proofImage(dsl)).isEqualTo(beforeProof); + assertThat(count(dsl, "game_session_canonical_issuer_binding_local_operation")).isZero(); assertThat( dsl.fetch( "SELECT DISTINCT bootstrap_operation_id FROM game_session_canonical_issuer_partition_mutation") @@ -678,8 +681,17 @@ void forwardMigrationRetainsCommittedAndPendingPhysicalMutationLineage() { assertThat(head.pendingMutationId()).isEqualTo(pendingId); assertThat(head.currentRevision()).isEqualTo(successor); var history = - CanonicalGameplayIssuerPartitionMutationRepository.readPartitionInTransaction( - transaction, anchor.bootstrapOperationId(), BigInteger.ZERO); + List.of( + CanonicalGameplayIssuerPartitionMutationRepository.readInTransaction( + transaction, + CanonicalGameplayIssuerPartitionMutation.Kind.ADD_CAPACITY, + historicalOwnerId, + BigInteger.ZERO), + CanonicalGameplayIssuerPartitionMutationRepository.readInTransaction( + transaction, + CanonicalGameplayIssuerPartitionMutation.Kind.ADD_BINDING, + historicalOwnerId, + BigInteger.ZERO)); assertThat(history).hasSize(2); assertThat(history.stream().map(CanonicalGameplayIssuerPartitionMutation::status)) .containsExactlyInAnyOrder( @@ -711,41 +723,6 @@ void forwardMigrationRetainsCommittedAndPendingPhysicalMutationLineage() { .allSatisfy(definition -> assertThat(definition).contains("bootstrap_operation_id")); } - private static DSLContext preMembershipLocalProducer( - DSLContext dsl, AtomicInteger substitutions) { - String currentSlotCount = - "SELECT count(*) FROM game_session_canonical_issuer_current_local_operation membership" - + " JOIN game_session_canonical_issuer_binding_local_operation operation" - + " ON operation.operation_id = membership.operation_id" - + " WHERE membership.issuer_id = ? AND membership.anchor_bootstrap_operation_id = ?" - + " AND membership.partition_id = ?"; - String oldSlotCount = - "SELECT count(*) FROM game_session_canonical_issuer_binding_local_operation operation" - + " WHERE operation.issuer_id = ? AND operation.anchor_bootstrap_operation_id = ?" - + " AND operation.partition_id = ?" - + " AND NOT EXISTS (SELECT 1 FROM game_session_canonical_issuer_binding_local_retirement retirement" - + " WHERE retirement.original_local_operation_id = operation.operation_id" - + " AND retirement.status = 'RETIRED')"; - var configuration = dsl.configuration().derive(); - configuration.set( - new DefaultExecuteListenerProvider( - new DefaultExecuteListener() { - @Override - public void renderEnd(ExecuteContext context) { - String sql = context.sql(); - if (currentSlotCount.equals(sql)) { - substitutions.incrementAndGet(); - context.sql(oldSlotCount); - } else if (sql != null - && sql.contains("game_session_canonical_issuer_current_local_operation")) { - throw new AssertionError( - "Unexpected membership read in the pre-V1040.5 producer"); - } - } - })); - return DSL.using(configuration); - } - private static void insertPreLineageMutation( DSLContext transaction, UUID mutationId, diff --git a/services/game-session-service/src/test/java/integration/net/firedevops/firemud/gamesession/repository/CanonicalGameplayIssuerBindingLocalRedisOwnerIntegrationTest.java b/services/game-session-service/src/test/java/integration/net/firedevops/firemud/gamesession/repository/CanonicalGameplayIssuerBindingLocalRedisOwnerIntegrationTest.java index 031ddb7e26..fbdf8dc786 100644 --- a/services/game-session-service/src/test/java/integration/net/firedevops/firemud/gamesession/repository/CanonicalGameplayIssuerBindingLocalRedisOwnerIntegrationTest.java +++ b/services/game-session-service/src/test/java/integration/net/firedevops/firemud/gamesession/repository/CanonicalGameplayIssuerBindingLocalRedisOwnerIntegrationTest.java @@ -51,6 +51,7 @@ import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.Test; import org.springframework.jdbc.datasource.DriverManagerDataSource; +import org.springframework.transaction.support.TransactionSynchronizationManager; import org.testcontainers.containers.GenericContainer; import org.testcontainers.containers.PostgreSQLContainer; import org.testcontainers.junit.jupiter.Container; @@ -68,6 +69,8 @@ class CanonicalGameplayIssuerBindingLocalRedisOwnerIntegrationTest { private static final String OWNER_PRINCIPAL = "gamesession_coord_app"; private static final String ISSUER_KEY_PREFIX = "session:game:index:issuer:"; private static final String METADATA_FIELD = "!issuer-partition-bootstrap/v1"; + private static final String ACKNOWLEDGEMENT_TABLE = + "game_session_canonical_issuer_binding_local_acknowledgement"; private static final BigInteger LAYOUT_VERSION = BigInteger.valueOf(3); private static final BigInteger PARTITION_COUNT = BigInteger.ONE; private static final BigInteger PARTITION_CAPACITY = BigInteger.valueOf(2); @@ -165,6 +168,8 @@ void projectsOrdinaryNewAgainstInstalledAnchorAndReusesExactPendingOperation() t CanonicalGameplayIssuerInstalledAnchor anchor = initialCoverageOwner(dsl, currentState::get) .completeInitialBootstrap(intent.operationId(), bootstrapRequestId); + new CanonicalGameplayIssuerAdmissionControlRepository(dsl) + .installInitialOpen(anchor, currentState::get); String installedAnchorImage = anchorImage(dsl); String installedProofImage = proofImage(dsl); String initialReservationImage = reservationImage(dsl); @@ -303,6 +308,13 @@ void projectsOrdinaryNewAgainstInstalledAnchorAndReusesExactPendingOperation() t var firstCapacityOnly = projectionOwner.projectAndRead(first); assertThat(firstCapacityOnly.operation()).isSameAs(first); assertThat(firstCapacityOnly.scriptOutcome()).isEqualTo(1L); + var acknowledgementRepository = + new CanonicalGameplayIssuerBindingLocalAcknowledgementRepository(dsl, currentState::get); + assertThatThrownBy(() -> acknowledgementRepository.acknowledge(firstCapacityOnly)) + .isInstanceOf(IllegalStateException.class) + .hasMessageContaining("nonterminal binding"); + assertThat(count(dsl, ACKNOWLEDGEMENT_TABLE)).isZero(); + assertThat(count(dsl, "game_session_canonical_issuer_binding_local_ack_gen_counter")).isZero(); var firstCapacityFields = CanonicalGameplayIssuerBootstrapCoverageRepository.decodeFieldSet( firstCapacityOnly.exactReadbackBytes()); @@ -520,11 +532,196 @@ void projectsOrdinaryNewAgainstInstalledAnchorAndReusesExactPendingOperation() t var resumedAcknowledged = reloadProgressedOperation(dsl, currentState::get, first); assertThat(resumedAcknowledged.preparedTransition().inventoryRevision()) .isGreaterThan(resumedPresent.preparedTransition().inventoryRevision()); + var acknowledgementReadback = + projectionOwner(dsl, currentState::get).projectAndRead(resumedAcknowledged); + assertThat(acknowledgementReadback.scriptOutcome()).isEqualTo(3L); + + String acknowledgementImageBeforeAmbientRefusals = + dsl.fetch("SELECT * FROM " + ACKNOWLEDGEMENT_TABLE).formatJSON(); + String acknowledgementCounterImageBeforeAmbientRefusals = + dsl.fetch("SELECT * FROM game_session_canonical_issuer_binding_local_ack_gen_counter") + .formatJSON(); + AtomicInteger acknowledgementSourceReads = new AtomicInteger(); + CanonicalGameplayIssuerBootstrapPartitionRedisOwner.CurrentIssuerStateSource + acknowledgementSource = + () -> { + acknowledgementSourceReads.incrementAndGet(); + return currentState.get(); + }; + var guardedAcknowledgementRepository = + new CanonicalGameplayIssuerBindingLocalAcknowledgementRepository( + dsl, acknowledgementSource); + TransactionSynchronizationManager.setActualTransactionActive(true); + try { + assertThatThrownBy( + () -> guardedAcknowledgementRepository.acknowledge(acknowledgementReadback)) + .isInstanceOf(IllegalStateException.class) + .hasMessage( + "Issuer binding-local acknowledgement is unavailable: Issuer acknowledgement owner cannot join an ambient SQL transaction"); + assertThat(acknowledgementSourceReads).hasValue(0); + } finally { + TransactionSynchronizationManager.setActualTransactionActive(false); + } + assertThat(dsl.fetch("SELECT * FROM " + ACKNOWLEDGEMENT_TABLE).formatJSON()) + .isEqualTo(acknowledgementImageBeforeAmbientRefusals); assertThat( - projectionOwner(dsl, currentState::get) - .projectAndRead(resumedAcknowledged) - .scriptOutcome()) - .isEqualTo(3L); + dsl.fetch("SELECT * FROM game_session_canonical_issuer_binding_local_ack_gen_counter") + .formatJSON()) + .isEqualTo(acknowledgementCounterImageBeforeAmbientRefusals); + + TransactionSynchronizationManager.initSynchronization(); + try { + assertThat(TransactionSynchronizationManager.isActualTransactionActive()).isFalse(); + assertThatThrownBy( + () -> guardedAcknowledgementRepository.acknowledge(acknowledgementReadback)) + .isInstanceOf(IllegalStateException.class) + .hasMessage( + "Issuer binding-local acknowledgement is unavailable: Issuer acknowledgement owner cannot join an ambient SQL transaction"); + assertThat(acknowledgementSourceReads).hasValue(0); + } finally { + TransactionSynchronizationManager.clearSynchronization(); + } + assertThat(dsl.fetch("SELECT * FROM " + ACKNOWLEDGEMENT_TABLE).formatJSON()) + .isEqualTo(acknowledgementImageBeforeAmbientRefusals); + assertThat( + dsl.fetch("SELECT * FROM game_session_canonical_issuer_binding_local_ack_gen_counter") + .formatJSON()) + .isEqualTo(acknowledgementCounterImageBeforeAmbientRefusals); + + dsl.transaction( + configuration -> { + DSLContext callerTransaction = DSL.using(configuration); + var callerOwnedAcknowledgementRepository = + new CanonicalGameplayIssuerBindingLocalAcknowledgementRepository( + callerTransaction, acknowledgementSource); + assertThatThrownBy( + () -> callerOwnedAcknowledgementRepository.acknowledge(acknowledgementReadback)) + .isInstanceOf(IllegalStateException.class) + .hasMessage( + "Issuer binding-local acknowledgement is unavailable: Issuer acknowledgement owner cannot join a jOOQ transaction"); + assertThat(acknowledgementSourceReads).hasValue(0); + assertThat(callerTransaction.fetch("SELECT * FROM " + ACKNOWLEDGEMENT_TABLE).formatJSON()) + .isEqualTo(acknowledgementImageBeforeAmbientRefusals); + assertThat( + callerTransaction + .fetch( + "SELECT * FROM game_session_canonical_issuer_binding_local_ack_gen_counter") + .formatJSON()) + .isEqualTo(acknowledgementCounterImageBeforeAmbientRefusals); + }); + assertThat(dsl.fetch("SELECT * FROM " + ACKNOWLEDGEMENT_TABLE).formatJSON()) + .isEqualTo(acknowledgementImageBeforeAmbientRefusals); + assertThat( + dsl.fetch("SELECT * FROM game_session_canonical_issuer_binding_local_ack_gen_counter") + .formatJSON()) + .isEqualTo(acknowledgementCounterImageBeforeAmbientRefusals); + + var issuerAcknowledgement = acknowledgementRepository.acknowledge(acknowledgementReadback); + assertThat(issuerAcknowledgement.evidence().operationId()).isEqualTo(first.operationId()); + assertThat(issuerAcknowledgement.evidence().issuerBindingLocalAcknowledgementGeneration()) + .isEqualTo(BigInteger.ONE); + assertThat(issuerAcknowledgement.evidence().anchor().globalCoverageGeneration()) + .isEqualTo(initialGlobalCoverageGeneration); + assertThat(issuerAcknowledgement.evidence().reservation().reservationId()) + .isEqualTo(first.reservation().reservationId()); + assertThat(issuerAcknowledgement.evidence().reservation().issuerCoverageOperationFence()) + .isEqualTo(first.reservation().issuerCoverageOperationFence()); + assertThat(issuerAcknowledgement.evidence().anchor().operationFence()) + .isEqualTo(first.anchor().operationFence()); + assertThat(issuerAcknowledgement.evidence().memberOperation().generation()) + .isEqualTo(first.localMemberGeneration()); + assertThat(issuerAcknowledgement.evidence().physicalReadback().bindingValueBytes()) + .containsExactly(first.exactMemberValueBytes()); + assertThat(issuerAcknowledgement.evidence().physicalReadback().capacityValueBytes()) + .containsExactly(first.exactMemberValueBytes()); + assertThat(issuerAcknowledgement.evidence().physicalReadback().countedCapacity()).isEqualTo(2); + assertThat( + Objects.requireNonNull( + dsl.fetchOne( + "SELECT member_status FROM" + + " game_session_canonical_issuer_binding_local_operation WHERE operation_id = ?", + first.operationId()), + "Expected immutable local issuer operation") + .get("member_status", String.class)) + .isEqualTo("PENDING_PHYSICAL_PROOF"); + assertThat(count(dsl, ACKNOWLEDGEMENT_TABLE)).isEqualTo(1L); + assertThat( + Objects.requireNonNull( + dsl.fetchOne( + "SELECT last_issued_binding_local_acknowledgement_generation FROM" + + " game_session_canonical_issuer_binding_local_ack_gen_counter" + + " WHERE issuer_id = ?", + ISSUER), + "Expected owner-issued local ACK generation counter") + .get("last_issued_binding_local_acknowledgement_generation", BigDecimal.class)) + .isEqualTo(BigDecimal.ONE); + assertThatThrownBy( + () -> + dsl.execute( + "UPDATE game_session_canonical_issuer_binding_local_ack_gen_counter" + + " SET last_issued_binding_local_acknowledgement_generation = 3," + + " counter_version = counter_version + 1 WHERE issuer_id = ?", + ISSUER)) + .hasMessageContaining("must advance its own domain by one"); + assertThat( + Objects.requireNonNull( + dsl.fetchOne( + "SELECT last_issued_binding_local_acknowledgement_generation FROM" + + " game_session_canonical_issuer_binding_local_ack_gen_counter" + + " WHERE issuer_id = ?", + ISSUER), + "Expected counter to refuse a skipped generation") + .get("last_issued_binding_local_acknowledgement_generation", BigDecimal.class)) + .isEqualTo(BigDecimal.ONE); + var restartedAcknowledgementRepository = + new CanonicalGameplayIssuerBindingLocalAcknowledgementRepository(dsl, currentState::get); + var retriedAcknowledgement = + restartedAcknowledgementRepository.acknowledge( + projectionOwner(dsl, currentState::get).projectAndRead(first)); + assertThat(retriedAcknowledgement.exactBytes()) + .containsExactly(issuerAcknowledgement.exactBytes()); + assertThat(retriedAcknowledgement.digest()).isEqualTo(issuerAcknowledgement.digest()); + assertThat(retriedAcknowledgement.evidence().issuerBindingLocalAcknowledgementGeneration()) + .isEqualTo(issuerAcknowledgement.evidence().issuerBindingLocalAcknowledgementGeneration()); + assertThat(restartedAcknowledgementRepository.readHistorical(first.operationId()).exactBytes()) + .containsExactly(issuerAcknowledgement.exactBytes()); + assertThat(count(dsl, ACKNOWLEDGEMENT_TABLE)).isEqualTo(1L); + assertThat( + Objects.requireNonNull( + dsl.fetchOne( + "SELECT last_issued_binding_local_acknowledgement_generation FROM" + + " game_session_canonical_issuer_binding_local_ack_gen_counter" + + " WHERE issuer_id = ?", + ISSUER), + "Expected replay to retain the owner-issued ACK generation") + .get("last_issued_binding_local_acknowledgement_generation", BigDecimal.class)) + .isEqualTo(BigDecimal.ONE); + assertThatThrownBy( + () -> + dsl.execute( + "UPDATE game_session_canonical_issuer_binding_local_acknowledgement" + + " SET acknowledgement_bytes = ? WHERE operation_id = ?", + issuerAcknowledgement.exactBytes(), + first.operationId())) + .hasMessageContaining("issuer binding-local acknowledgements are immutable"); + assertThatThrownBy( + () -> + dsl.execute( + "DELETE FROM game_session_canonical_issuer_binding_local_acknowledgement" + + " WHERE operation_id = ?", + first.operationId())) + .hasMessageContaining("issuer binding-local acknowledgements are immutable"); + assertThat(count(dsl, ACKNOWLEDGEMENT_TABLE)).isEqualTo(1L); + currentState.set( + new CanonicalGameplayIssuerBootstrapPartitionRedisOwner.CurrentIssuerState( + checkpointShape(BigInteger.valueOf(8)), incarnation)); + assertThatThrownBy( + () -> restartedAcknowledgementRepository.acknowledge(acknowledgementReadback)) + .isInstanceOf(IllegalStateException.class) + .hasMessageContaining("differs from the installed anchor"); + assertThat(restartedAcknowledgementRepository.readHistorical(first.operationId()).exactBytes()) + .containsExactly(issuerAcknowledgement.exactBytes()); + currentState.set(initialState); String beforeCapacityRefusal = localRegistrationImage(dsl); assertThatThrownBy( @@ -655,8 +852,11 @@ void readsProjectedSubsetWhenTwoSamePartitionRegistrationsPrecedePhysicalProject intent.sourceCheckpoint(), incarnation); AtomicReference currentState = new AtomicReference<>(initialState); - initialCoverageOwner(dsl, currentState::get) - .completeInitialBootstrap(intent.operationId(), bootstrapRequestId); + CanonicalGameplayIssuerInstalledAnchor anchor = + initialCoverageOwner(dsl, currentState::get) + .completeInitialBootstrap(intent.operationId(), bootstrapRequestId); + new CanonicalGameplayIssuerAdmissionControlRepository(dsl) + .installInitialOpen(anchor, currentState::get); var runtimeTarget = CanonicalGameplayBindingRuntimeTestFixtures.seedRunningLaunch( @@ -798,8 +998,11 @@ void differentPartitionProgressDoesNotFenceTargetButSamePartitionProgressDoes() var state = new CanonicalGameplayIssuerBootstrapPartitionRedisOwner.CurrentIssuerState( intent.sourceCheckpoint(), stableIncarnation("partition-isolation")); - initialCoverageOwner(dsl, () -> state) - .completeInitialBootstrap(intent.operationId(), bootstrapRequest); + var anchor = + initialCoverageOwner(dsl, () -> state) + .completeInitialBootstrap(intent.operationId(), bootstrapRequest); + new CanonicalGameplayIssuerAdmissionControlRepository(dsl) + .installInitialOpen(anchor, () -> state); var runtime = CanonicalGameplayBindingRuntimeTestFixtures.seedRunningLaunch( schema.dataSource(), uuid("partition-isolation-tenant")); diff --git a/services/game-session-service/src/test/java/integration/net/firedevops/firemud/gamesession/repository/CanonicalGameplayIssuerBootstrapCoverageOwnerIntegrationTest.java b/services/game-session-service/src/test/java/integration/net/firedevops/firemud/gamesession/repository/CanonicalGameplayIssuerBootstrapCoverageOwnerIntegrationTest.java index 0371943fd6..6371488c11 100644 --- a/services/game-session-service/src/test/java/integration/net/firedevops/firemud/gamesession/repository/CanonicalGameplayIssuerBootstrapCoverageOwnerIntegrationTest.java +++ b/services/game-session-service/src/test/java/integration/net/firedevops/firemud/gamesession/repository/CanonicalGameplayIssuerBootstrapCoverageOwnerIntegrationTest.java @@ -311,6 +311,8 @@ void installedAnchorReadAndRetryUseFrozenPlanAfterOrdinaryNewAdvancesInventoryCl CanonicalGameplayIssuerInstalledAnchor installed = owner(fixture, () -> current) .completeInitialBootstrap(fixture.intent().operationId(), fixture.requestId()); + new CanonicalGameplayIssuerAdmissionControlRepository(fixture.dsl()) + .installInitialOpen(installed, () -> current); var candidate = identity(PARTITION_COUNT, PARTITION_CAPACITY, "post-anchor-ordinary-new"); new CanonicalGameplayIssuerBindingLocalOperationRepository(fixture.dsl(), () -> current) diff --git a/services/game-session-service/src/test/java/integration/net/firedevops/firemud/gamesession/repository/CanonicalGameplayIssuerLayoutBootstrapRepositoryIntegrationTest.java b/services/game-session-service/src/test/java/integration/net/firedevops/firemud/gamesession/repository/CanonicalGameplayIssuerLayoutBootstrapRepositoryIntegrationTest.java index ffd1e3cbcd..7feab6e063 100644 --- a/services/game-session-service/src/test/java/integration/net/firedevops/firemud/gamesession/repository/CanonicalGameplayIssuerLayoutBootstrapRepositoryIntegrationTest.java +++ b/services/game-session-service/src/test/java/integration/net/firedevops/firemud/gamesession/repository/CanonicalGameplayIssuerLayoutBootstrapRepositoryIntegrationTest.java @@ -1085,6 +1085,8 @@ void retainedPhysicalWorkDoesNotStrandSupersedingLayoutOrOrdinaryNew() { var anchor = coverage.completeInitialBootstrap(replacement.operationId(), replacement.requestId()); assertThat(anchor.bootstrapOperationId()).isEqualTo(replacement.operationId()); + new CanonicalGameplayIssuerAdmissionControlRepository(dsl) + .installInitialOpen(anchor, () -> state); var runtime = CanonicalGameplayBindingRuntimeTestFixtures.seedRunningLaunch( schema.dataSource(), TENANT_ID); diff --git a/services/game-session-service/src/test/java/integration/net/firedevops/firemud/gamesession/repository/CanonicalGameplayIssuerLocalCapacityIntegrationTest.java b/services/game-session-service/src/test/java/integration/net/firedevops/firemud/gamesession/repository/CanonicalGameplayIssuerLocalCapacityIntegrationTest.java index bf75d4f7d1..a94f2133dd 100644 --- a/services/game-session-service/src/test/java/integration/net/firedevops/firemud/gamesession/repository/CanonicalGameplayIssuerLocalCapacityIntegrationTest.java +++ b/services/game-session-service/src/test/java/integration/net/firedevops/firemud/gamesession/repository/CanonicalGameplayIssuerLocalCapacityIntegrationTest.java @@ -448,6 +448,39 @@ void ordinaryReleaseRefusesMissingPartitionRevisionWithoutRedisOrSqlWrites() thr } } + @Test + void seededReleaseCompletesWithoutPublishingTheOriginalAcknowledgement() { + // This class retains prior physical partitions; keep this original in its own layout domain. + try (var fixture = newFixture(BigInteger.valueOf(10), BigInteger.ONE, 0)) { + String seed = "release-without-original-acknowledgement"; + UUID seededOperationId = fixture.prepareOtherControllerNew(seed); + fixture.projectOtherControllerNew(seed); + fixture.publishOtherControllerNew(seed); + assertThat( + fixture + .dsl() + .fetchSingle( + "SELECT count(*) FROM game_session_canonical_issuer_binding_local_acknowledgement" + + " WHERE operation_id = ?", + fixture.originalOperationId()) + .get(0, Long.class)) + .isZero(); + assertThat(fixture.recordOtherAccountAbort(seed).isAccountAborted()).isTrue(); + var pendingRelease = fixture.prepareIssuerRelease(seed); + assertThat(pendingRelease.originalOperation().operationId()).isEqualTo(seededOperationId); + assertThat(seededOperationId).isNotEqualTo(fixture.originalOperationId()); + + var completed = + fixture.completeIssuerRelease( + pendingRelease, fixture.projectIssuerRelease(pendingRelease)); + assertThat(completed.status()) + .isEqualTo(CanonicalGameplayIssuerBindingLocalReleaseOperation.Status.RELEASED); + var retry = fixture.prepareIssuerRelease(seed); + assertThat(retry.operationId()).isEqualTo(completed.operationId()); + assertThat(fixture.projectIssuerRelease(retry).scriptOutcome()).isEqualTo(2L); + } + } + @Test void actualReleaseReadbackPersistsAndReloadsWithMoreThan513PhysicalFields() throws Exception { try (var fixture = newFixture(BigInteger.valueOf(8), BigInteger.ONE, 250)) { diff --git a/services/game-session-service/src/test/java/integration/net/firedevops/firemud/gamesession/repository/CanonicalGameplayIssuerPhysicalRetirementIntegrationTest.java b/services/game-session-service/src/test/java/integration/net/firedevops/firemud/gamesession/repository/CanonicalGameplayIssuerPhysicalRetirementIntegrationTest.java index 7084a40fb0..6c46b94512 100644 --- a/services/game-session-service/src/test/java/integration/net/firedevops/firemud/gamesession/repository/CanonicalGameplayIssuerPhysicalRetirementIntegrationTest.java +++ b/services/game-session-service/src/test/java/integration/net/firedevops/firemud/gamesession/repository/CanonicalGameplayIssuerPhysicalRetirementIntegrationTest.java @@ -758,122 +758,127 @@ void postRetirementSqlRejectsUnaccountedCurrentReservationInAnotherPartition() t @Test void bootstrapMembershipPreservesFrozenOwnershipAcrossAnUnrelatedAdditiveColumn() { - // Capture through the real bootstrap owner at the published prior migration frontier. try (var fixture = newFixture( controlledCandidate(BigInteger.valueOf(19), BigInteger.ONE), 1, - MigrationVersion.fromVersion("1040.5"))) { + MigrationVersion.fromVersion("1040.5"), + this::upgradeRetainedBootstrapAcrossAdditiveColumn)) { assertThat(fixture.originalBaselineReservationCount()).isOne(); - String baselineSourceSql = - " FROM game_session_canonical_issuer_installed_anchor anchor" - + " JOIN game_session_canonical_issuer_partition_build_cohort_row cohort" - + " ON cohort.build_operation_id = anchor.build_operation_id" - + " AND cohort.source_operation_id = anchor.bootstrap_operation_id" - + " AND cohort.issuer_id = anchor.issuer_id" - + " AND cohort.source_kind = 'RESERVATION'"; - UUID baselineReservationId = - fixture - .dsl() - .fetchSingle("SELECT cohort.source_key::uuid" + baselineSourceSql) - .get(0, UUID.class); - String retainedOwnerSql = - "SELECT jsonb_build_object('cohort', to_jsonb(cohort), 'anchor', to_jsonb(anchor))::text" - + baselineSourceSql; - String retainedOwnerBefore = fixture.dsl().fetchSingle(retainedOwnerSql).get(0, String.class); - String reservationBefore = reservationImage(fixture.dsl(), baselineReservationId); - byte[] partitionBefore = physicalFieldSet(fixture.issuerPartitionKey()); - List membershipBefore = currentOperationIds(fixture.dsl()); - String durableHistoryBefore = durableHistoryImage(fixture.dsl(), NIL_UUID); - List migrationHistoryBefore = fixture.migrationHistoryImage(); - - assertThat( - fixture.upgradeWithDefaultGameSessionMigrations( - MigrationVersion.fromVersion("1040.6"))) - .isOne(); - List migrationHistoryAfter = fixture.migrationHistoryImage(); - assertThat(migrationHistoryAfter).hasSize(migrationHistoryBefore.size() + 1); - assertThat(migrationHistoryAfter.subList(0, migrationHistoryBefore.size())) - .containsExactlyElementsOf(migrationHistoryBefore); - assertThat(durableHistoryImage(fixture.dsl(), NIL_UUID)).isEqualTo(durableHistoryBefore); - assertThat(fixture.dsl().fetchSingle(retainedOwnerSql).get(0, String.class)) - .isEqualTo(retainedOwnerBefore); - assertThat(reservationImage(fixture.dsl(), baselineReservationId)) - .isEqualTo(reservationBefore); - assertThat(currentOperationIds(fixture.dsl())).isEqualTo(membershipBefore); - assertThat(physicalFieldSet(fixture.issuerPartitionKey())).isEqualTo(partitionBefore); + assertThat(currentOperationIds(fixture.dsl())).containsExactly(fixture.originalOperationId()); + } + } - fixture - .dsl() - .execute( - "ALTER TABLE game_session_canonical_issuer_partition_reservation" - + " ADD COLUMN non_authority_annotation text"); - // The captured immutable JSON has no new key; the current row has an explicit SQL NULL. - assertThat( - fixture - .dsl() - .fetchSingle( - "SELECT jsonb_exists(cohort.source_row_json::jsonb, 'non_authority_annotation')" - + baselineSourceSql) - .get(0, Boolean.class)) - .isFalse(); - assertThat( - fixture - .dsl() - .fetchSingle( - "SELECT non_authority_annotation FROM" - + " game_session_canonical_issuer_partition_reservation" - + " WHERE reservation_id = ?", - baselineReservationId) - .get(0, String.class)) - .isNull(); - fixture - .dsl() - .fetch( - "SELECT gs_require_issuer_reservation_current_membership(?)", baselineReservationId); + private void upgradeRetainedBootstrapAcrossAdditiveColumn( + org.springframework.jdbc.datasource.DriverManagerDataSource dataSource, + CanonicalGameplayIssuerLayoutBootstrapIntent intent) { + DSLContext parent = DSL.using(dataSource, org.jooq.SQLDialect.POSTGRES); + byte[] partitionKey = + CanonicalGameplayIssuerRedisKeys.forPartition(intent.layoutDescriptor(), BigInteger.ZERO) + .getBytes(StandardCharsets.US_ASCII); + String baselineSourceSql = + " FROM game_session_canonical_issuer_installed_anchor anchor" + + " JOIN game_session_canonical_issuer_partition_build_cohort_row cohort" + + " ON cohort.build_operation_id = anchor.build_operation_id" + + " AND cohort.source_operation_id = anchor.bootstrap_operation_id" + + " AND cohort.issuer_id = anchor.issuer_id" + + " AND cohort.source_kind = 'RESERVATION'"; + UUID baselineReservationId = + parent.fetchSingle("SELECT cohort.source_key::uuid" + baselineSourceSql).get(0, UUID.class); + String retainedOwnerSql = + "SELECT jsonb_build_object('cohort', to_jsonb(cohort), 'anchor', to_jsonb(anchor))::text" + + baselineSourceSql; + String retainedOwnerBefore = parent.fetchSingle(retainedOwnerSql).get(0, String.class); + String reservationBefore = reservationImage(parent, baselineReservationId); + byte[] partitionBefore = physicalFieldSet(partitionKey); + List membershipBefore = currentOperationIds(parent); + assertThat(membershipBefore).isEmpty(); + String durableHistoryBefore = durableHistoryImage(parent, NIL_UUID); + List migrationHistoryBefore = + parent + .fetch( + "SELECT to_jsonb(retained_row)::text FROM flyway_schema_history retained_row ORDER BY installed_rank") + .getValues(0, String.class); - assertThatThrownBy( - () -> - fixture - .dsl() - .transaction( - configuration -> { - DSLContext transaction = DSL.using(configuration); - assertThat( - transaction.execute( - "UPDATE game_session_canonical_issuer_partition_reservation" - + " SET coverage_fence = coverage_fence + 1" - + " WHERE reservation_id = ?", - baselineReservationId)) - .isOne(); - transaction.fetch( - "SELECT gs_require_issuer_reservation_current_membership(?)", - baselineReservationId); - })) - .isInstanceOf(org.jooq.exception.DataAccessException.class) - .rootCause() - .isInstanceOf(org.postgresql.util.PSQLException.class) - .hasMessageContaining( - "Installed issuer reservation requires exact bootstrap or current local-operation membership"); - fixture - .dsl() - .fetch( - "SELECT gs_require_issuer_reservation_current_membership(?)", baselineReservationId); - assertThat( - fixture - .dsl() - .fetchSingle( - "SELECT (to_jsonb(reservation) - 'non_authority_annotation')::text FROM" - + " game_session_canonical_issuer_partition_reservation reservation" - + " WHERE reservation_id = ?", - baselineReservationId) - .get(0, String.class)) - .isEqualTo(reservationBefore); - assertThat(fixture.dsl().fetchSingle(retainedOwnerSql).get(0, String.class)) - .isEqualTo(retainedOwnerBefore); - assertThat(currentOperationIds(fixture.dsl())).isEqualTo(membershipBefore); - assertThat(physicalFieldSet(fixture.issuerPartitionKey())).isEqualTo(partitionBefore); - } + assertThat( + CanonicalGameplayAdmissionAbortCompositionFixture + .upgradeWithDefaultGameSessionMigrations( + MigrationVersion.fromVersion("1040.6"), dataSource)) + .isOne(); + List migrationHistoryAfter = + parent + .fetch( + "SELECT to_jsonb(retained_row)::text FROM flyway_schema_history retained_row ORDER BY installed_rank") + .getValues(0, String.class); + assertThat(migrationHistoryAfter).hasSize(migrationHistoryBefore.size() + 1); + assertThat(migrationHistoryAfter.subList(0, migrationHistoryBefore.size())) + .containsExactlyElementsOf(migrationHistoryBefore); + assertThat(durableHistoryImage(parent, NIL_UUID)).isEqualTo(durableHistoryBefore); + assertThat(parent.fetchSingle(retainedOwnerSql).get(0, String.class)) + .isEqualTo(retainedOwnerBefore); + assertThat(reservationImage(parent, baselineReservationId)).isEqualTo(reservationBefore); + assertThat(currentOperationIds(parent)).isEqualTo(membershipBefore); + assertThat(physicalFieldSet(partitionKey)).isEqualTo(partitionBefore); + + parent.execute( + "ALTER TABLE game_session_canonical_issuer_partition_reservation" + + " ADD COLUMN non_authority_annotation text"); + // The captured immutable JSON has no new key; the current row has an explicit SQL NULL. + assertThat( + parent + .fetchSingle( + "SELECT jsonb_exists(cohort.source_row_json::jsonb, 'non_authority_annotation')" + + baselineSourceSql) + .get(0, Boolean.class)) + .isFalse(); + assertThat( + parent + .fetchSingle( + "SELECT non_authority_annotation FROM" + + " game_session_canonical_issuer_partition_reservation" + + " WHERE reservation_id = ?", + baselineReservationId) + .get(0, String.class)) + .isNull(); + parent.fetch( + "SELECT gs_require_issuer_reservation_current_membership(?)", baselineReservationId); + + assertThatThrownBy( + () -> + parent.transaction( + configuration -> { + DSLContext transaction = DSL.using(configuration); + assertThat( + transaction.execute( + "UPDATE game_session_canonical_issuer_partition_reservation" + + " SET coverage_fence = coverage_fence + 1" + + " WHERE reservation_id = ?", + baselineReservationId)) + .isOne(); + transaction.fetch( + "SELECT gs_require_issuer_reservation_current_membership(?)", + baselineReservationId); + })) + .isInstanceOf(org.jooq.exception.DataAccessException.class) + .rootCause() + .isInstanceOf(org.postgresql.util.PSQLException.class) + .hasMessageContaining( + "Installed issuer reservation requires exact bootstrap or current local-operation membership"); + parent.fetch( + "SELECT gs_require_issuer_reservation_current_membership(?)", baselineReservationId); + assertThat( + parent + .fetchSingle( + "SELECT (to_jsonb(reservation) - 'non_authority_annotation')::text FROM" + + " game_session_canonical_issuer_partition_reservation reservation" + + " WHERE reservation_id = ?", + baselineReservationId) + .get(0, String.class)) + .isEqualTo(reservationBefore); + assertThat(parent.fetchSingle(retainedOwnerSql).get(0, String.class)) + .isEqualTo(retainedOwnerBefore); + assertThat(currentOperationIds(parent)).isEqualTo(membershipBefore); + assertThat(physicalFieldSet(partitionKey)).isEqualTo(partitionBefore); } @Test diff --git a/services/game-session-service/src/test/java/integration/net/firedevops/firemud/gamesession/repository/CanonicalGameplayProtectedIncarnationReceiverPostgresIntegrationTest.java b/services/game-session-service/src/test/java/integration/net/firedevops/firemud/gamesession/repository/CanonicalGameplayProtectedIncarnationReceiverPostgresIntegrationTest.java index 15c90f3a9a..456651a736 100644 --- a/services/game-session-service/src/test/java/integration/net/firedevops/firemud/gamesession/repository/CanonicalGameplayProtectedIncarnationReceiverPostgresIntegrationTest.java +++ b/services/game-session-service/src/test/java/integration/net/firedevops/firemud/gamesession/repository/CanonicalGameplayProtectedIncarnationReceiverPostgresIntegrationTest.java @@ -2,7 +2,27 @@ import static org.assertj.core.api.Assertions.assertThat; import static org.assertj.core.api.Assertions.assertThatThrownBy; +import static org.mockito.ArgumentMatchers.any; +import static org.mockito.ArgumentMatchers.eq; +import static org.mockito.Mockito.doReturn; +import static org.mockito.Mockito.doThrow; +import static org.mockito.Mockito.mock; +import static org.mockito.Mockito.spy; +import static org.mockito.Mockito.when; +import ch.qos.logback.classic.Level; +import ch.qos.logback.classic.Logger; +import ch.qos.logback.classic.spi.ILoggingEvent; +import ch.qos.logback.core.read.ListAppender; +import com.google.protobuf.ByteString; +import io.lettuce.core.AclSetuserArgs; +import io.lettuce.core.RedisClient; +import io.lettuce.core.RedisURI; +import io.lettuce.core.api.StatefulRedisConnection; +import io.lettuce.core.api.async.RedisAsyncCommands; +import io.lettuce.core.codec.ByteArrayCodec; +import io.lettuce.core.protocol.CommandKeyword; +import io.lettuce.core.protocol.CommandType; import java.math.BigInteger; import java.nio.ByteBuffer; import java.nio.file.Path; @@ -17,18 +37,31 @@ import java.util.List; import java.util.Map; import java.util.UUID; +import java.util.concurrent.Executors; +import java.util.concurrent.TimeUnit; +import java.util.concurrent.atomic.AtomicLong; +import java.util.concurrent.atomic.AtomicReference; import net.firedevops.firemud.common.json.Rfc8785CanonicalJson; +import net.firedevops.firemud.common.redis.contracts.RedisScriptCatalog; +import net.firedevops.firemud.common.redis.contracts.RedisScriptDescriptor; import net.firedevops.firemud.common.security.GameSessionAccountDelegationProfile; import net.firedevops.firemud.gamesession.binding.CanonicalGameplayBindingIdentity; import net.firedevops.firemud.gamesession.binding.CanonicalGameplayBindingTransitionRequest; import net.firedevops.firemud.gamesession.binding.CanonicalIssuerReservationFenceEvidence; +import net.firedevops.firemud.gamesession.dto.CanonicalGameplayLoginResult; +import net.firedevops.firemud.gamesession.dto.InitialGameplayLoginAttemptCoordinates; +import net.firedevops.firemud.gamesession.service.CanonicalGameplayAccountInitialBarrierRedisScriptContribution; import net.firedevops.firemud.test.TestContainerImages; import org.flywaydb.core.Flyway; import org.jooq.DSLContext; import org.jooq.SQLDialect; import org.jooq.impl.DSL; import org.junit.jupiter.api.Test; +import org.junit.jupiter.params.ParameterizedTest; +import org.junit.jupiter.params.provider.ValueSource; +import org.slf4j.LoggerFactory; import org.springframework.jdbc.datasource.DriverManagerDataSource; +import org.testcontainers.containers.GenericContainer; import org.testcontainers.containers.PostgreSQLContainer; import org.testcontainers.junit.jupiter.Container; import org.testcontainers.junit.jupiter.Testcontainers; @@ -57,6 +90,587 @@ class CanonicalGameplayProtectedIncarnationReceiverPostgresIntegrationTest { static PostgreSQLContainer postgres = new PostgreSQLContainer<>(TestContainerImages.postgres()); + @Container + static GenericContainer redis = + new GenericContainer<>(TestContainerImages.redis()).withExposedPorts(6379); + + @Test + void localDescriptorFailuresRetainNeverDispatchedOriginalForLaterValidPreparation() + throws Exception { + try (Fixture.InitialFixture fixture = Fixture.InitialFixture.open(); + InitialRedisFixture physical = InitialRedisFixture.open(); + var login = fixture.originalLogin()) { + var snapshot = fixture.initialRepository.readCurrent(fixture.original.requestId()); + String retained = fixture.initialTargetPostimage(); + String key = + CanonicalGameplayAccountInitialBarrierKey.forTarget( + fixture.tenantTags.assignmentForInitialBarrierTarget(fixture.original.requestId()), + snapshot.initializerId(), + fixture.original.requestId()); + RedisClient undispatched = mock(RedisClient.class); + RedisScriptCatalog catalog = mock(RedisScriptCatalog.class); + when(catalog.require(CanonicalGameplayAccountInitialBarrierRedisScriptContribution.SCRIPT_ID)) + .thenThrow(new IllegalStateException("missing local descriptor")) + .thenReturn(mock(RedisScriptDescriptor.class)); + var owner = fixture.initialOwner(undispatched, fixture.initialRepository, catalog); + for (int failure = 0; failure < 2; failure++) { + assertThat( + owner.initializeOnce( + fixture.original, login, fixture.tenantId, fixture.namespaceId)) + .isEqualTo( + new CanonicalGameplayAccountInitialOpenProof.Refused( + CanonicalGameplayAccountInitialOpenProof.Reason.TARGET_NEVER_DISPATCHED)); + assertThat(fixture.initialRepository.readCurrent(fixture.original.requestId()).state()) + .isEqualTo( + CanonicalGameplayAccountInitialBarrierInitializerRepository.State.NEVER_DISPATCHED); + assertThat(fixture.initialTargetPostimage()).isEqualTo(retained); + assertThat(physical.connection.sync().exists(key)).isZero(); + } + org.mockito.Mockito.verifyNoInteractions(undispatched); + var validOwner = fixture.initialOwner(physical.ownerClient(), fixture.initialRepository); + assertThat( + validOwner.initializeOnce( + fixture.original, login, fixture.tenantId, fixture.namespaceId)) + .isInstanceOf(CanonicalGameplayAccountInitialOpenProof.CurrentOpen.class); + assertThat( + fixture.initialRepository.readCurrent(fixture.original.requestId()).initializerId()) + .isEqualTo(snapshot.initializerId()); + physical.connection.sync().del(key); + } + } + + @Test + @SuppressWarnings({"unchecked", "rawtypes"}) + void remotePreflightFailuresRetainNeverDispatchedOriginalForValidRetry() throws Exception { + try (Fixture.InitialFixture fixture = Fixture.InitialFixture.open(); + InitialRedisFixture physical = InitialRedisFixture.open(); + var login = fixture.originalLogin(); + var loadConnection = physical.ownerClient.connect(ByteArrayCodec.INSTANCE)) { + var snapshot = fixture.initialRepository.readCurrent(fixture.original.requestId()); + String retained = fixture.initialTargetPostimage(); + String key = + CanonicalGameplayAccountInitialBarrierKey.forTarget( + fixture.tenantTags.assignmentForInitialBarrierTarget(fixture.original.requestId()), + snapshot.initializerId(), + fixture.original.requestId()); + RedisClient connectFailure = mock(RedisClient.class); + when(connectFailure.connect(any(ByteArrayCodec.class))) + .thenThrow(new IllegalStateException("controlled connect failure")); + RedisClient loadFailure = mock(RedisClient.class); + StatefulRedisConnection connection = spy(loadConnection); + RedisAsyncCommands commands = spy(loadConnection.async()); + doReturn(commands).when(connection).async(); + doThrow(new IllegalStateException("controlled SCRIPT LOAD failure")) + .when(commands) + .scriptLoad(any(byte[].class)); + when(loadFailure.connect(any(ByteArrayCodec.class))).thenReturn(connection); + // The actual administrator connection reports principal 'default', which must be refused. + for (RedisClient failingClient : + List.of(connectFailure, physical.administrator, loadFailure)) { + var owner = fixture.initialOwner(failingClient, fixture.initialRepository); + assertThat( + owner.initializeOnce( + fixture.original, login, fixture.tenantId, fixture.namespaceId)) + .isEqualTo( + new CanonicalGameplayAccountInitialOpenProof.Refused( + CanonicalGameplayAccountInitialOpenProof.Reason.TARGET_NEVER_DISPATCHED)); + assertThat(fixture.initialTargetPostimage()).isEqualTo(retained); + assertThat(fixture.initialRepository.readCurrent(fixture.original.requestId()).state()) + .isEqualTo( + CanonicalGameplayAccountInitialBarrierInitializerRepository.State.NEVER_DISPATCHED); + assertThat(physical.connection.sync().exists(key)).isZero(); + } + assertThat( + fixture + .initialOwner(physical.ownerClient, fixture.initialRepository) + .initializeOnce(fixture.original, login, fixture.tenantId, fixture.namespaceId)) + .isInstanceOf(CanonicalGameplayAccountInitialOpenProof.CurrentOpen.class); + assertThat( + fixture.initialRepository.readCurrent(fixture.original.requestId()).initializerId()) + .isEqualTo(snapshot.initializerId()); + physical.connection.sync().del(key); + } + } + + @Test + void lostDispatchClaimReplyLeavesMissingAccountOpenUncertainWithoutAnotherCreate() + throws Exception { + String sensitiveMessage = "secret-dispatch-claim-reply-token-and-source-93746"; + Logger logger = + (Logger) LoggerFactory.getLogger(CanonicalGameplayAccountInitialBarrierRedisOwner.class); + ListAppender appender = new ListAppender<>(); + appender.start(); + logger.addAppender(appender); + try (Fixture.InitialFixture fixture = Fixture.InitialFixture.open(); + InitialRedisFixture physical = InitialRedisFixture.open(); + var login = fixture.originalLogin()) { + var repository = spy(fixture.initialRepository); + org.mockito.Mockito.doAnswer( + invocation -> { + invocation.callRealMethod(); + throw new IllegalStateException(sensitiveMessage); + }) + .when(repository) + .recordDispatchPossible(any(), any()); + var owner = fixture.initialOwner(physical.ownerClient, repository); + assertThat( + owner.initializeOnce(fixture.original, login, fixture.tenantId, fixture.namespaceId)) + .isInstanceOf(CanonicalGameplayAccountInitialOpenProof.Refused.class); + var snapshot = fixture.initialRepository.readCurrent(fixture.original.requestId()); + assertThat(snapshot.state()) + .isEqualTo( + CanonicalGameplayAccountInitialBarrierInitializerRepository.State.DISPATCH_POSSIBLE); + String retained = fixture.initialTargetPostimage(); + String key = + CanonicalGameplayAccountInitialBarrierKey.forTarget( + fixture.tenantTags.assignmentForInitialBarrierTarget(fixture.original.requestId()), + snapshot.initializerId(), + fixture.original.requestId()); + assertThat(physical.connection.sync().exists(key)).isZero(); + var retry = fixture.initialOwner(physical.ownerClient, fixture.initialRepository); + assertThat( + retry.initializeOnce(fixture.original, login, fixture.tenantId, fixture.namespaceId)) + .isInstanceOf(CanonicalGameplayAccountInitialOpenProof.Refused.class); + assertThat(fixture.initialTargetPostimage()).isEqualTo(retained); + assertThat(physical.connection.sync().exists(key)).isZero(); + org.mockito.Mockito.verify(repository).recordDispatchPossible(any(), any()); + assertThat(appender.list).hasSize(1); + ILoggingEvent event = appender.list.getFirst(); + assertThat(event.getLevel()).isEqualTo(Level.WARN); + assertThat(event.getFormattedMessage()) + .isEqualTo( + "Initial Account OPEN create attempt did not complete originalRequestId=" + + snapshot.originalRequestId() + + " initializerId=" + + snapshot.initializerId() + + " failureType=" + + IllegalStateException.class.getName()) + .doesNotContain(sensitiveMessage); + assertThat(event.getArgumentArray()) + .containsExactly( + snapshot.originalRequestId(), + snapshot.initializerId(), + IllegalStateException.class.getName()); + assertThat(event.getThrowableProxy()).isNull(); + } finally { + logger.detachAppender(appender); + appender.stop(); + } + } + + @Test + void abandonedNeverDispatchedOriginalPreventsFreshInitialForLaterLogin() throws Exception { + try (Fixture.InitialFixture fixture = Fixture.InitialFixture.open()) { + String initializer = + fixture + .dsl + .fetchSingle( + "SELECT to_jsonb(i)::text FROM" + + " game_session_canonical_initial_account_barrier_initializer i") + .get(0, String.class); + String target = fixture.initialTargetPostimage(); + fixture.dsl.execute( + "UPDATE game_session_initial_gameplay_login_journal" + + " SET abandoned = TRUE, abandoned_at = clock_timestamp() WHERE request_id = ?", + fixture.original.requestId()); + String abandonedJournal = + fixture + .dsl + .fetchSingle( + "SELECT to_jsonb(j)::text FROM game_session_initial_gameplay_login_journal j" + + " WHERE request_id = ?", + fixture.original.requestId()) + .get(0, String.class); + var later = + new InitialGameplayLoginAttemptCoordinates(UUID.randomUUID(), UUID.randomUUID(), 18L); + try (var login = + Fixture.mockInitialLoginResult(later, fixture.accountId, UUID.randomUUID())) { + fixture.dsl.execute( + "INSERT INTO game_session_initial_gameplay_login_journal" + + " (request_id, caller_context_id, expected_attempt_fence) VALUES (?, ?, ?)", + later.requestId(), + later.callerContextId(), + later.expectedAttemptFence()); + fixture.dsl.execute( + "UPDATE game_session_initial_gameplay_login_journal" + + " SET verified_token_jti = ?, verified_token_sha256 = ?," + + " verified_token_generation = 1, verified_issuance_fence = 1" + + " WHERE request_id = ?", + login.evidence().tokenJti(), + login.evidence().tokenSha256(), + later.requestId()); + assertThatThrownBy( + () -> + fixture.initialRepository.beginOrRead( + later, login, fixture.tenantId, fixture.namespaceId)) + .hasStackTraceContaining("uq_gs_initial_account_barrier_never_retarget"); + } + assertThat( + fixture + .dsl + .fetchSingle( + "SELECT to_jsonb(i)::text FROM" + + " game_session_canonical_initial_account_barrier_initializer i") + .get(0, String.class)) + .isEqualTo(initializer); + assertThat(fixture.initialTargetPostimage()).isEqualTo(target); + assertThat( + fixture + .dsl + .fetchSingle( + "SELECT to_jsonb(j)::text FROM game_session_initial_gameplay_login_journal j" + + " WHERE request_id = ?", + fixture.original.requestId()) + .get(0, String.class)) + .isEqualTo(abandonedJournal); + assertThat( + fixture + .dsl + .fetchSingle( + "SELECT target_state FROM game_session_canonical_initial_account_barrier_target" + + " WHERE original_request_id = ?", + fixture.original.requestId()) + .get(0, String.class)) + .isEqualTo("NEVER_DISPATCHED"); + } + } + + @Test + void initialTagAssignmentAndDispatchSerializeInventoryBeforeControlInBothOrders() + throws Exception { + for (boolean tagFirst : List.of(true, false)) { + try (Fixture.InitialFixture fixture = Fixture.InitialFixture.open(); + var holder = Fixture.dataSource(fixture.schema).getConnection(); + var tagConnection = Fixture.dataSource(fixture.schema).getConnection(); + var dispatchConnection = Fixture.dataSource(fixture.schema).getConnection()) { + var observation = + fixture + .receiver(new ControlledSigner(fixture.keyPair)) + .observeForInitialAccountBarrier(fixture.original.requestId()); + DSLContext holderDsl = DSL.using(holder, SQLDialect.POSTGRES); + DSLContext tagDsl = DSL.using(tagConnection, SQLDialect.POSTGRES); + DSLContext dispatchDsl = DSL.using(dispatchConnection, SQLDialect.POSTGRES); + int holderPid = + java.util.Objects.requireNonNull( + holderDsl.fetchSingle("SELECT pg_backend_pid()").get(0, Integer.class)); + int tagPid = + java.util.Objects.requireNonNull( + tagDsl.fetchSingle("SELECT pg_backend_pid()").get(0, Integer.class)); + int dispatchPid = + java.util.Objects.requireNonNull( + dispatchDsl.fetchSingle("SELECT pg_backend_pid()").get(0, Integer.class)); + var tags = + new CanonicalGameplayTenantGameplayTagRepository( + tagDsl, fixture.targetWorkloadNamespace, 1); + var repository = + new CanonicalGameplayAccountInitialBarrierInitializerRepository( + dispatchDsl, Clock.fixed(NOW, ZoneOffset.UTC)); + java.util.concurrent.Callable tag = + () -> tags.assignmentForInitialBarrierTarget(fixture.original.requestId()); + java.util.concurrent.Callable dispatch = + () -> repository.recordDispatchPossible(fixture.original.requestId(), observation); + holder.setAutoCommit(false); + holderDsl.fetchSingle( + "SELECT account_id FROM game_session_canonical_account_coverage_control" + + " WHERE account_id = ? FOR UPDATE", + fixture.accountId); + try (var executor = Executors.newFixedThreadPool(2)) { + try { + var first = executor.submit(tagFirst ? tag : dispatch); + int firstPid = tagFirst ? tagPid : dispatchPid; + int secondPid = tagFirst ? dispatchPid : tagPid; + awaitInitialBackendBlockedBy(fixture.dsl, firstPid, holderPid); + var second = executor.submit(tagFirst ? dispatch : tag); + awaitInitialBackendBlockedBy(fixture.dsl, secondPid, firstPid); + // Neither waiter may own target rows before it owns account control. + holderDsl.fetchSingle( + "SELECT initializer_id FROM game_session_canonical_initial_account_barrier_initializer" + + " WHERE original_request_id = ? FOR UPDATE NOWAIT", + fixture.original.requestId()); + holder.rollback(); + assertThat(first.get(5L, TimeUnit.SECONDS)).isNotNull(); + assertThat(second.get(5L, TimeUnit.SECONDS)).isNotNull(); + } finally { + holder.rollback(); + } + } + assertThat(fixture.initialRepository.readCurrent(fixture.original.requestId()).state()) + .isEqualTo( + CanonicalGameplayAccountInitialBarrierInitializerRepository.State + .DISPATCH_POSSIBLE); + } + } + } + + private static void awaitInitialBackendBlockedBy( + DSLContext observer, int waitingPid, int holderPid) throws InterruptedException { + long deadline = System.nanoTime() + TimeUnit.SECONDS.toNanos(5); + boolean blocked = false; + while (System.nanoTime() < deadline) { + blocked = + Boolean.TRUE.equals( + observer + .fetchSingle("SELECT ? = ANY(pg_blocking_pids(?))", holderPid, waitingPid) + .get(0, Boolean.class)); + if (blocked) break; + TimeUnit.MILLISECONDS.sleep(10L); + } + assertThat(blocked) + .as("PostgreSQL backend %s waits on exact holder %s", waitingPid, holderPid) + .isTrue(); + } + + @Test + void initialOwnerComposesSqlSignedObservationAndRedisWithoutRecreatingResetOpen() + throws Exception { + for (BigInteger epoch : List.of(BigInteger.ZERO, BigInteger.valueOf(8))) { + try (Fixture.InitialFixture fixture = Fixture.InitialFixture.open(epoch); + InitialRedisFixture physical = InitialRedisFixture.open(); + CanonicalGameplayLoginResult login = fixture.originalLogin()) { + var owner = fixture.initialOwner(physical.ownerClient(), fixture.initialRepository); + var initialized = + owner.initializeOnce(fixture.original, login, fixture.tenantId, fixture.namespaceId); + assertThat(initialized) + .isInstanceOf(CanonicalGameplayAccountInitialOpenProof.CurrentOpen.class); + var opened = (CanonicalGameplayAccountInitialOpenProof.CurrentOpen) initialized; + assertThat(opened.sourceControlEpoch()).isEqualTo(epoch); + assertThat(opened.exactFields()).hasSize(9); + assertThat(physical.connection().sync().hgetall(opened.key())) + .isEqualTo(opened.exactFields()); + String retained = fixture.initialTargetPostimage(); + + var replay = owner.verifyCurrentOpen(fixture.original.requestId()); + assertThat(replay).isInstanceOf(CanonicalGameplayAccountInitialOpenProof.CurrentOpen.class); + assertThat(((CanonicalGameplayAccountInitialOpenProof.CurrentOpen) replay).exactFields()) + .isEqualTo(opened.exactFields()); + assertThat(fixture.initialTargetPostimage()).isEqualTo(retained); + + fixture.dsl.execute( + "UPDATE game_session_initial_gameplay_login_journal" + + " SET abandoned = true, abandoned_at = CURRENT_TIMESTAMP" + + " WHERE request_id = ?", + fixture.original.requestId()); + // The installed target is storage evidence independent of a later caller. The old LOGIN + // cannot create anything, while another binding may verify the same current target. + assertThat( + owner.verifyCurrentOpenForTarget( + fixture.accountId, fixture.tenantId, fixture.namespaceId)) + .isInstanceOf(CanonicalGameplayAccountInitialOpenProof.CurrentOpen.class); + assertThat( + owner.initializeOnce( + fixture.original, login, fixture.tenantId, fixture.namespaceId)) + .isInstanceOf(CanonicalGameplayAccountInitialOpenProof.Refused.class); + assertThat(physical.connection().sync().hgetall(opened.key())) + .isEqualTo(opened.exactFields()); + assertThat(fixture.initialTargetPostimage()).isEqualTo(retained); + + physical.connection().sync().del(opened.key()); + assertThat(owner.verifyCurrentOpen(fixture.original.requestId())) + .isInstanceOf(CanonicalGameplayAccountInitialOpenProof.Refused.class); + assertThat( + owner.initializeOnce( + fixture.original, login, fixture.tenantId, fixture.namespaceId)) + .isInstanceOf(CanonicalGameplayAccountInitialOpenProof.Refused.class); + assertThat(physical.connection().sync().exists(opened.key())).isZero(); + assertThat(fixture.initialTargetPostimage()).isEqualTo(retained); + } + } + } + + @ParameterizedTest + @ValueSource(strings = {"INVENTORY", "CONTROL"}) + void initialOpenReadbackExpiredDuringSqlLockWaitCannotCompleteOriginal(String heldLock) + throws Exception { + AtomicLong trustedMillis = new AtomicLong(NOW.toEpochMilli()); + Clock trustedClock = mock(Clock.class); + when(trustedClock.millis()).thenAnswer(ignored -> trustedMillis.get()); + try (Fixture.InitialFixture fixture = Fixture.InitialFixture.open(); + InitialRedisFixture physical = InitialRedisFixture.open(); + var login = fixture.originalLogin(); + var holder = Fixture.dataSource(fixture.schema).getConnection(); + var acceptanceConnection = Fixture.dataSource(fixture.schema).getConnection()) { + var repository = + spy( + new CanonicalGameplayAccountInitialBarrierInitializerRepository( + fixture.dsl, trustedClock)); + AtomicReference captured = + new AtomicReference<>(); + org.mockito.Mockito.doAnswer( + invocation -> { + captured.set(invocation.getArgument(1)); + throw new IllegalStateException("controlled capture before SQL completion"); + }) + .when(repository) + .acceptOpenReadback(eq(fixture.original.requestId()), any()); + var owner = + fixture.initialOwner( + physical.ownerClient(), + repository, + RedisScriptCatalog.fromContributions( + List.of(new CanonicalGameplayAccountInitialBarrierRedisScriptContribution())), + trustedClock); + assertThat( + owner.initializeOnce(fixture.original, login, fixture.tenantId, fixture.namespaceId)) + .isInstanceOf(CanonicalGameplayAccountInitialOpenProof.Refused.class); + var readback = java.util.Objects.requireNonNull(captured.get()); + assertThat(trustedMillis.get()) + .isGreaterThanOrEqualTo( + Math.max( + readback.beforeIncarnation().issuedAtEpochMillis(), + readback.afterIncarnation().issuedAtEpochMillis())) + .isLessThan( + Math.min( + readback.beforeIncarnation().expiresAtEpochMillis(), + readback.afterIncarnation().expiresAtEpochMillis())); + assertThat(fixture.initialRepository.readCurrent(fixture.original.requestId()).state()) + .isEqualTo( + CanonicalGameplayAccountInitialBarrierInitializerRepository.State.DISPATCH_POSSIBLE); + String retainedTarget = fixture.initialTargetPostimage(); + Map retainedPhysical = physical.connection().sync().hgetall(readback.key()); + assertThat(retainedPhysical).isEqualTo(readback.barrierFields()); + DSLContext holderDsl = DSL.using(holder, SQLDialect.POSTGRES); + DSLContext acceptanceDsl = DSL.using(acceptanceConnection, SQLDialect.POSTGRES); + int holderPid = + java.util.Objects.requireNonNull( + holderDsl.fetchSingle("SELECT pg_backend_pid()").get(0, Integer.class)); + int acceptancePid = + java.util.Objects.requireNonNull( + acceptanceDsl.fetchSingle("SELECT pg_backend_pid()").get(0, Integer.class)); + var acceptanceRepository = + new CanonicalGameplayAccountInitialBarrierInitializerRepository( + acceptanceDsl, trustedClock); + holder.setAutoCommit(false); + if ("INVENTORY".equals(heldLock)) { + holderDsl.fetchSingle( + "SELECT inventory_revision FROM game_session_canonical_binding_inventory_clock" + + " WHERE singleton_id = 1 FOR UPDATE"); + } else { + holderDsl.fetchSingle( + "SELECT account_id FROM game_session_canonical_account_coverage_control" + + " WHERE account_id = ? FOR UPDATE", + fixture.accountId); + } + try (var executor = Executors.newSingleThreadExecutor()) { + try { + var acceptance = + executor.submit( + () -> + acceptanceRepository.acceptOpenReadback( + fixture.original.requestId(), readback)); + awaitInitialBackendBlockedBy(fixture.dsl, acceptancePid, holderPid); + trustedMillis.set( + Math.max( + readback.beforeIncarnation().expiresAtEpochMillis(), + readback.afterIncarnation().expiresAtEpochMillis()) + + 1L); + holder.rollback(); + assertThatThrownBy(() -> acceptance.get(5L, TimeUnit.SECONDS)) + .hasStackTraceContaining( + "INITIAL protected incarnation observation expired before SQL completion"); + } finally { + holder.rollback(); + } + } + assertThat(fixture.initialRepository.readCurrent(fixture.original.requestId()).state()) + .isEqualTo( + CanonicalGameplayAccountInitialBarrierInitializerRepository.State.DISPATCH_POSSIBLE); + assertThat(fixture.initialTargetPostimage()).isEqualTo(retainedTarget); + assertThat(physical.connection().sync().hgetall(readback.key())).isEqualTo(retainedPhysical); + physical.connection().sync().del(readback.key()); + } + } + + @Test + void initialOwnerRecoversLostSqlReceiptFromExactPhysicalOpenWithoutAnotherCreate() + throws Exception { + try (Fixture.InitialFixture fixture = Fixture.InitialFixture.open(); + InitialRedisFixture physical = InitialRedisFixture.open(); + CanonicalGameplayLoginResult login = fixture.originalLogin()) { + var repository = spy(fixture.initialRepository); + // Controlled receipt loss after the real SQL dispatch and real Redis write/readback. + doThrow(new IllegalStateException("Controlled loss of first SQL receipt")) + .doCallRealMethod() + .when(repository) + .acceptOpenReadback(eq(fixture.original.requestId()), any()); + var owner = fixture.initialOwner(physical.ownerClient(), repository); + assertThat( + owner.initializeOnce(fixture.original, login, fixture.tenantId, fixture.namespaceId)) + .isInstanceOf(CanonicalGameplayAccountInitialOpenProof.Refused.class); + assertThat(repository.readCurrent(fixture.original.requestId()).state()) + .isEqualTo( + CanonicalGameplayAccountInitialBarrierInitializerRepository.State.DISPATCH_POSSIBLE); + String key = + CanonicalGameplayAccountInitialBarrierKey.forTarget( + fixture.tenantTags.assignmentForInitialBarrierTarget(fixture.original.requestId()), + repository.readCurrent(fixture.original.requestId()).initializerId(), + fixture.original.requestId()); + Map firstPostimage = physical.connection().sync().hgetall(key); + + var recovered = + owner.initializeOnce(fixture.original, login, fixture.tenantId, fixture.namespaceId); + assertThat(recovered) + .isInstanceOf(CanonicalGameplayAccountInitialOpenProof.CurrentOpen.class); + assertThat(((CanonicalGameplayAccountInitialOpenProof.CurrentOpen) recovered).key()) + .isEqualTo(key); + assertThat(physical.connection().sync().hgetall(key)).isEqualTo(firstPostimage); + assertThat(repository.readCurrent(fixture.original.requestId()).state()) + .isEqualTo( + CanonicalGameplayAccountInitialBarrierInitializerRepository.State.OPEN_INSTALLED); + String retained = fixture.initialTargetPostimage(); + assertThat(owner.verifyCurrentOpen(fixture.original.requestId())) + .isInstanceOf(CanonicalGameplayAccountInitialOpenProof.CurrentOpen.class); + assertThat(fixture.initialTargetPostimage()).isEqualTo(retained); + } + } + + private record InitialRedisFixture( + RedisClient administrator, + StatefulRedisConnection connection, + RedisClient ownerClient) + implements AutoCloseable { + static InitialRedisFixture open() { + String principal = "gamesession_coord_app"; + String password = UUID.randomUUID().toString(); + RedisClient administrator = + RedisClient.create(RedisURI.create(redis.getHost(), redis.getMappedPort(6379))); + StatefulRedisConnection connection = administrator.connect(); + // This container is owned solely by this test class; each case removes only its own key. + connection + .sync() + .aclSetuser( + principal, + new AclSetuserArgs() + .reset() + .on() + .addPassword(password) + .keyPattern("session:game:*") + .addCommand(CommandType.HELLO) + .addCommand(CommandType.PING) + .addCommand(CommandType.CLIENT, CommandKeyword.SETINFO) + .addCommand(CommandType.ACL, CommandKeyword.WHOAMI) + .addCommand(CommandType.SCRIPT, CommandKeyword.LOAD) + .addCommand(CommandType.EVALSHA) + .addCommand(CommandType.TYPE) + .addCommand(CommandType.PTTL) + .addCommand(CommandType.HLEN) + .addCommand(CommandType.HGETALL) + .addCommand(CommandType.HSET)); + RedisClient owner = + RedisClient.create( + RedisURI.Builder.redis(redis.getHost(), redis.getMappedPort(6379)) + .withAuthentication(principal, password) + .build()); + return new InitialRedisFixture(administrator, connection, owner); + } + + @Override + public void close() { + connection.close(); + ownerClient.shutdown(Duration.ZERO, Duration.ofSeconds(2)); + administrator.shutdown(Duration.ZERO, Duration.ofSeconds(2)); + } + } + @Test void verifiesOnlySignedExactCurrentTargetAndRejectsReplayAndMismatches() throws Exception { try (Fixture fixture = Fixture.open()) { @@ -210,11 +824,69 @@ void changedCurrentSqlContextAfterSourceCallCannotProduceVerifiedEvidence() thro } } + @Test + void initialArmVerifiesExactOriginalAndNonzeroNoActiveEpochWithSameTrustedVerifier() + throws Exception { + try (Fixture.InitialFixture fixture = Fixture.InitialFixture.open()) { + ControlledSigner channel = new ControlledSigner(fixture.keyPair()); + var receiver = fixture.receiver(channel); + + var verified = receiver.observeForInitialAccountBarrier(fixture.original().requestId()); + + assertThat(verified.ownerKind()) + .isEqualTo( + CanonicalGameplayProtectedIncarnationReceiver.OwnerKind.INITIAL_ACCOUNT_BARRIER); + assertThat(verified.requestId()).isEqualTo(fixture.original().requestId()); + assertThat(verified.originalCallerContextId()) + .isEqualTo(fixture.original().callerContextId()); + assertThat(verified.originalAttemptFence()).isEqualTo(17L); + assertThat(verified.accountId()).isEqualTo(fixture.accountId()); + assertThat(verified.cohortDigest()).isNull(); + assertThat(verified.sourceControlState()).isEqualTo("NO_ACTIVE_ACCOUNT_WIDE_FLOW"); + assertThat(verified.sourceControlEpoch()).isEqualTo("8"); + assertThat(verified.acceptedAttestationDigest()).isEqualTo(ACCEPTED_ATTESTATION_DIGEST); + assertThat(verified.evidence()).isEqualTo(fixture.expectedEvidence()); + + var repeated = receiver.observeForInitialAccountBarrier(fixture.original().requestId()); + assertThat(repeated.observationNonce()).isNotEqualTo(verified.observationNonce()); + assertThat(repeated.incarnationDigest()).isEqualTo(verified.incarnationDigest()); + + for (Mutation mutation : + List.of(Mutation.WRONG_INITIAL_SOURCE_EPOCH, Mutation.WRONG_INITIAL_ATTEMPT)) { + assertThatThrownBy( + () -> + fixture + .receiver(new ControlledSigner(fixture.keyPair(), mutation, null)) + .observeForInitialAccountBarrier(fixture.original().requestId())) + .isInstanceOf( + CanonicalGameplayProtectedIncarnationReceiver.ObservationRejectedException.class); + } + } + } + + @Test + void changedNoActiveEpochAfterInitialObservationCannotProduceVerifiedEvidence() throws Exception { + try (Fixture.InitialFixture fixture = Fixture.InitialFixture.open()) { + ControlledSigner channel = + new ControlledSigner(fixture.keyPair(), Mutation.NONE, fixture.dsl()); + + assertThatThrownBy( + () -> + fixture + .receiver(channel) + .observeForInitialAccountBarrier(fixture.original().requestId())) + .isInstanceOf(CanonicalGameplayBindingInventoryConflictException.class); + assertThat(channel.lastSigned()).isNotNull(); + } + } + private enum Mutation { NONE, WRONG_NONCE, WRONG_OPERATION_ID, WRONG_OPERATION_FENCE, + WRONG_INITIAL_SOURCE_EPOCH, + WRONG_INITIAL_ATTEMPT, WRONG_STORAGE_GENERATION, FOREIGN_ACCOUNT, FOREIGN_TENANT, @@ -251,18 +923,43 @@ private ControlledSigner(KeyPair keyPair, Mutation mutation, DSLContext contextM public CanonicalGameplayProtectedIncarnationReceiver.SignedObservation observe( CanonicalGameplayProtectedIncarnationReceiver.ObservationRequest request) { if (contextMutationDsl != null) { - contextMutationDsl.execute( - "UPDATE game_session_canonical_account_admission_fence_intent" - + " SET cohort_digest = ? WHERE operation_id = ?", - "sha256:" + "f".repeat(64), - request.context().operationId()); + if (request.context().ownerKind() + == CanonicalGameplayProtectedIncarnationReceiver.OwnerKind.INITIAL_ACCOUNT_BARRIER) { + contextMutationDsl.execute( + "UPDATE game_session_canonical_account_coverage_control" + + " SET last_operation_fence = 9 WHERE account_id = ?", + request.context().accountId()); + } else { + contextMutationDsl.execute( + "UPDATE game_session_canonical_account_admission_fence_intent" + + " SET cohort_digest = ? WHERE operation_id = ?", + "sha256:" + "f".repeat(64), + request.context().operationId()); + } } Map root = payload(request); switch (mutation) { case WRONG_NONCE -> root.put("observationNonce", "A".repeat(43)); - case WRONG_OPERATION_ID -> - asMap(root.get("owner")).put("operationId", UUID.randomUUID().toString()); - case WRONG_OPERATION_FENCE -> asMap(root.get("owner")).put("operationFence", "999999"); + case WRONG_OPERATION_ID -> { + String field = + request.context().ownerKind() + == CanonicalGameplayProtectedIncarnationReceiver.OwnerKind + .INITIAL_ACCOUNT_BARRIER + ? "initializerId" + : "operationId"; + asMap(root.get("owner")).put(field, UUID.randomUUID().toString()); + } + case WRONG_OPERATION_FENCE -> { + String field = + request.context().ownerKind() + == CanonicalGameplayProtectedIncarnationReceiver.OwnerKind + .INITIAL_ACCOUNT_BARRIER + ? "sourceControlEpoch" + : "operationFence"; + asMap(root.get("owner")).put(field, "999999"); + } + case WRONG_INITIAL_SOURCE_EPOCH -> asMap(root.get("owner")).put("sourceControlEpoch", "9"); + case WRONG_INITIAL_ATTEMPT -> asMap(root.get("owner")).put("originalAttemptFence", 18L); case WRONG_STORAGE_GENERATION -> asMap(root.get("targetDeploymentEvidence")) .put("storageGeneration", "storage-untrusted-response"); @@ -332,14 +1029,32 @@ private static Map payload( var context = request.context(); var evidence = request.expectedEvidence(); Map owner = new LinkedHashMap<>(); - owner.put("operationId", context.operationId().toString()); - owner.put("requestId", context.requestId().toString()); - owner.put("accountId", context.accountId().toString()); - owner.put("operationFence", context.operationFence()); - owner.put("plannedAccountAdmissionFence", context.plannedAccountAdmissionFence().toString()); - owner.put("inventorySnapshotRevision", context.inventorySnapshotRevision()); - owner.put("cohortDigest", context.cohortDigest()); - owner.put("barrierTargetDigest", context.barrierTargetDigest()); + boolean initial = + context.ownerKind() + == CanonicalGameplayProtectedIncarnationReceiver.OwnerKind.INITIAL_ACCOUNT_BARRIER; + if (initial) { + owner.put("ownerKind", context.ownerKind().name()); + owner.put("initializerId", context.operationId().toString()); + owner.put("originalRequestId", context.requestId().toString()); + owner.put("originalCallerContextId", context.originalCallerContextId().toString()); + owner.put("originalAttemptFence", context.originalAttemptFence()); + owner.put("accountId", context.accountId().toString()); + owner.put("sourceControlState", context.sourceControlState()); + owner.put("sourceControlEpoch", context.sourceControlEpoch()); + owner.put("inventorySnapshotRevision", context.inventorySnapshotRevision()); + owner.put("accountLoginEvidenceDigest", context.accountLoginEvidenceDigest()); + owner.put("sourceControlDigest", context.sourceControlDigest()); + owner.put("targetDigest", context.barrierTargetDigest()); + } else { + owner.put("operationId", context.operationId().toString()); + owner.put("requestId", context.requestId().toString()); + owner.put("accountId", context.accountId().toString()); + owner.put("operationFence", context.operationFence()); + owner.put("plannedAccountAdmissionFence", context.plannedAccountAdmissionFence().toString()); + owner.put("inventorySnapshotRevision", context.inventorySnapshotRevision()); + owner.put("cohortDigest", context.cohortDigest()); + owner.put("barrierTargetDigest", context.barrierTargetDigest()); + } Map target = new LinkedHashMap<>(); target.put("targetOrdinal", context.targetOrdinal()); @@ -363,7 +1078,11 @@ private static Map payload( targetEvidence.put("aofGeneration", evidence.aofGeneration()); Map root = new LinkedHashMap<>(); - root.put("schema", "firemud.gs.protected-incarnation-read/v1"); + root.put( + "schema", + initial + ? "firemud.gs.protected-initial-account-barrier-read/v1" + : "firemud.gs.protected-incarnation-read/v1"); root.put("attestorBinding", request.attestorBinding()); root.put("attestorKeyId", KEY_ID); root.put("acceptedAttestationDigest", request.acceptedAttestationDigest()); @@ -562,6 +1281,310 @@ public void close() { dropSchema(schema); } + private static final class InitialFixture implements AutoCloseable { + private final String schema; + private final DSLContext dsl; + private final InitialGameplayLoginAttemptCoordinates original; + private final UUID accountId; + private final UUID tenantId; + private final UUID namespaceId; + private final String targetWorkloadNamespace; + private final KeyPair keyPair; + private final CanonicalGameplayProtectedIncarnationReceiver.ExpectedTargetDeploymentEvidence + expectedEvidence; + private final CanonicalGameplayAccountInitialBarrierInitializerRepository initialRepository; + private final CanonicalGameplayTenantGameplayTagRepository tenantTags; + + private InitialFixture( + String schema, + DSLContext dsl, + InitialGameplayLoginAttemptCoordinates original, + UUID accountId, + UUID tenantId, + UUID namespaceId, + String targetWorkloadNamespace, + KeyPair keyPair, + CanonicalGameplayProtectedIncarnationReceiver.ExpectedTargetDeploymentEvidence + expectedEvidence, + CanonicalGameplayAccountInitialBarrierInitializerRepository initialRepository, + CanonicalGameplayTenantGameplayTagRepository tenantTags) { + this.schema = schema; + this.dsl = dsl; + this.original = original; + this.accountId = accountId; + this.tenantId = tenantId; + this.namespaceId = namespaceId; + this.targetWorkloadNamespace = targetWorkloadNamespace; + this.keyPair = keyPair; + this.expectedEvidence = expectedEvidence; + this.initialRepository = initialRepository; + this.tenantTags = tenantTags; + } + + private static InitialFixture open() throws Exception { + return open(BigInteger.valueOf(8)); + } + + private static InitialFixture open(BigInteger sourceControlEpoch) throws Exception { + String schema = "gs_initial_incarnation_" + UUID.randomUUID().toString().replace("-", ""); + DriverManagerDataSource dataSource = Fixture.dataSource(schema); + Flyway.configure() + .dataSource(dataSource) + .schemas(schema) + .defaultSchema(schema) + .table("flyway_schema_history") + .locations(MIGRATION_LOCATION) + .load() + .migrate(); + DSLContext dsl = DSL.using(dataSource, SQLDialect.POSTGRES); + UUID tenantId = UUID.randomUUID(); + var runtime = + CanonicalGameplayBindingRuntimeTestFixtures.seedRunningLaunch(dataSource, tenantId); + CanonicalGameplayBindingInventoryRepositoryIntegrationTest + .seedSyntheticVerifiedLegacyDisposition(dsl); + + UUID accountId = UUID.randomUUID(); + UUID transitionId = UUID.randomUUID(); + UUID characterId = UUID.randomUUID(); + var identity = + new CanonicalGameplayBindingIdentity( + accountId, + runtime.canonicalTenantId(), + runtime.playableStateNamespaceId(), + characterId, + "SHARED", + runtime.gameInstanceUuid(), + runtime.gameInstanceId(), + UUID.randomUUID().toString(), + UUID.randomUUID(), + BigInteger.ONE, + GameSessionAccountDelegationProfile.ISSUER, + BigInteger.ONE, + BigInteger.ONE, + BigInteger.valueOf(16), + BigInteger.valueOf(32)); + var reservation = + new CanonicalIssuerReservationFenceEvidence( + UUID.randomUUID(), + UUID.randomUUID(), + UUID.randomUUID(), + BigInteger.ONE, + BigInteger.ONE, + BigInteger.ONE); + new CanonicalGameplayBindingInventoryRepository(dsl) + .prepare( + new CanonicalGameplayBindingTransitionRequest( + transitionId, UUID.randomUUID(), identity, reservation, null, null)); + dsl.execute( + "UPDATE game_session_canonical_account_coverage_control" + + " SET last_operation_fence = ? WHERE account_id = ?", + sourceControlEpoch, + accountId); + + InitialGameplayLoginAttemptCoordinates original = + new InitialGameplayLoginAttemptCoordinates(UUID.randomUUID(), UUID.randomUUID(), 17L); + var accountLogin = mockInitialLoginResult(original, accountId, UUID.randomUUID()); + dsl.execute( + "INSERT INTO game_session_initial_gameplay_login_journal" + + " (request_id, caller_context_id, expected_attempt_fence) VALUES (?, ?, ?)", + original.requestId(), + original.callerContextId(), + original.expectedAttemptFence()); + dsl.execute( + "UPDATE game_session_initial_gameplay_login_journal" + + " SET verified_token_jti = ?, verified_token_sha256 = ?," + + " verified_token_generation = 1, verified_issuance_fence = 1" + + " WHERE request_id = ?", + accountLogin.evidence().tokenJti(), + accountLogin.evidence().tokenSha256(), + original.requestId()); + CanonicalGameplayAccountInitialBarrierInitializerRepository initialRepository = + new CanonicalGameplayAccountInitialBarrierInitializerRepository(dsl); + initialRepository.beginOrRead( + original, + accountLogin, + runtime.canonicalTenantId(), + runtime.playableStateNamespaceId()); + accountLogin.close(); + + KeyPairGenerator generator = KeyPairGenerator.getInstance("RSA"); + generator.initialize(2048); + KeyPair keyPair = generator.generateKeyPair(); + var expectedEvidence = controlledExpectedEvidence(); + var tenantTags = + new CanonicalGameplayTenantGameplayTagRepository(dsl, runtime.targetNamespace(), 1); + return new InitialFixture( + schema, + dsl, + original, + accountId, + runtime.canonicalTenantId(), + runtime.playableStateNamespaceId(), + runtime.targetNamespace(), + keyPair, + expectedEvidence, + initialRepository, + tenantTags); + } + + private CanonicalGameplayProtectedIncarnationReceiver receiver( + CanonicalGameplayProtectedIncarnationReceiver.ProtectedObservationChannel channel) { + return receiver( + channel, + new CanonicalGameplayProtectedIncarnationReceiver.TrustedConfiguration( + ATTESTOR_BINDING, + ACCEPTED_ATTESTATION_DIGEST, + Map.of(KEY_ID, (java.security.interfaces.RSAPublicKey) keyPair.getPublic()), + expectedEvidence, + ACL_DIGEST, + CONFIG_DIGEST, + 16 * 1024, + 1, + Duration.ofSeconds(30))); + } + + private CanonicalGameplayProtectedIncarnationReceiver receiver( + CanonicalGameplayProtectedIncarnationReceiver.ProtectedObservationChannel channel, + CanonicalGameplayProtectedIncarnationReceiver.TrustedConfiguration configuration) { + return new CanonicalGameplayProtectedIncarnationReceiver( + initialRepository, + tenantTags, + channel, + configuration, + Clock.fixed(NOW, ZoneOffset.UTC)); + } + + private CanonicalGameplayLoginResult originalLogin() { + UUID tokenJti = + dsl.fetchSingle( + "SELECT verified_token_jti FROM game_session_initial_gameplay_login_journal" + + " WHERE request_id = ?", + original.requestId()) + .get(0, UUID.class); + return mockInitialLoginResult(original, accountId, tokenJti); + } + + private String initialTargetPostimage() { + return dsl.fetchSingle( + "SELECT to_jsonb(t)::text FROM game_session_canonical_initial_account_barrier_target t" + + " WHERE original_request_id = ?", + original.requestId()) + .get(0, String.class); + } + + private CanonicalGameplayAccountInitialBarrierRedisOwner initialOwner( + RedisClient client, + CanonicalGameplayAccountInitialBarrierInitializerRepository repository) { + return initialOwner( + client, + repository, + RedisScriptCatalog.fromContributions( + List.of(new CanonicalGameplayAccountInitialBarrierRedisScriptContribution()))); + } + + private CanonicalGameplayAccountInitialBarrierRedisOwner initialOwner( + RedisClient client, + CanonicalGameplayAccountInitialBarrierInitializerRepository repository, + RedisScriptCatalog catalog) { + return initialOwner(client, repository, catalog, Clock.systemUTC()); + } + + private CanonicalGameplayAccountInitialBarrierRedisOwner initialOwner( + RedisClient client, + CanonicalGameplayAccountInitialBarrierInitializerRepository repository, + RedisScriptCatalog catalog, + Clock trustedClock) { + var configuration = + new CanonicalGameplayProtectedIncarnationReceiver.TrustedConfiguration( + ATTESTOR_BINDING, + ACCEPTED_ATTESTATION_DIGEST, + Map.of(KEY_ID, (java.security.interfaces.RSAPublicKey) keyPair.getPublic()), + expectedEvidence, + ACL_DIGEST, + CONFIG_DIGEST, + 16 * 1024, + 1, + Duration.ofSeconds(30)); + var receiver = + new CanonicalGameplayProtectedIncarnationReceiver( + repository, tenantTags, new ControlledSigner(keyPair), configuration, trustedClock); + return new CanonicalGameplayAccountInitialBarrierRedisOwner( + client, catalog, repository, tenantTags, receiver); + } + + private InitialGameplayLoginAttemptCoordinates original() { + return original; + } + + private UUID accountId() { + return accountId; + } + + private KeyPair keyPair() { + return keyPair; + } + + private DSLContext dsl() { + return dsl; + } + + private CanonicalGameplayProtectedIncarnationReceiver.ExpectedTargetDeploymentEvidence + expectedEvidence() { + return expectedEvidence; + } + + @Override + public void close() { + try (var connection = + java.sql.DriverManager.getConnection( + postgres.getJdbcUrl(), postgres.getUsername(), postgres.getPassword()); + var statement = connection.createStatement()) { + statement.execute("DROP SCHEMA IF EXISTS " + schema + " CASCADE"); + } catch (Exception failure) { + throw new IllegalStateException("Could not dispose INITIAL observation schema", failure); + } + } + } + + private static CanonicalGameplayLoginResult mockInitialLoginResult( + InitialGameplayLoginAttemptCoordinates original, UUID accountId, UUID tokenJti) { + var evidence = + new CanonicalGameplayLoginResult.NonSecretEvidence( + accountId, + original.requestId(), + original.callerContextId(), + tokenJti, + "e".repeat(64), + GameSessionAccountDelegationProfile.PROFILE, + NOW.getEpochSecond(), + NOW.getEpochSecond(), + NOW.plusSeconds(120).getEpochSecond(), + "1", + "1", + ByteString.copyFromUtf8("{}"), + ByteString.copyFromUtf8("[]"), + ByteString.copyFromUtf8("[]")); + CanonicalGameplayLoginResult result = mock(CanonicalGameplayLoginResult.class); + when(result.evidence()).thenReturn(evidence); + return result; + } + + private static CanonicalGameplayProtectedIncarnationReceiver.ExpectedTargetDeploymentEvidence + controlledExpectedEvidence() { + return new CanonicalGameplayProtectedIncarnationReceiver.ExpectedTargetDeploymentEvidence( + "controlled-target-deployment", + "generation-7", + List.of("redis-node-a"), + "redis-test-build", + "registry-test-v1", + "sha256:" + "d".repeat(64), + "READY", + "boot-7", + "startup-7", + "storage-7", + "aof-7"); + } + private static DriverManagerDataSource dataSource(String schema) { DriverManagerDataSource dataSource = new DriverManagerDataSource(); dataSource.setDriverClassName("org.postgresql.Driver"); diff --git a/services/game-session-service/src/test/java/integration/net/firedevops/firemud/gamesession/repository/InitialGameplayLoginCoordinationJournalRepositoryIntegrationTest.java b/services/game-session-service/src/test/java/integration/net/firedevops/firemud/gamesession/repository/InitialGameplayLoginCoordinationJournalRepositoryIntegrationTest.java index 747bf7223f..6d62c22eac 100644 --- a/services/game-session-service/src/test/java/integration/net/firedevops/firemud/gamesession/repository/InitialGameplayLoginCoordinationJournalRepositoryIntegrationTest.java +++ b/services/game-session-service/src/test/java/integration/net/firedevops/firemud/gamesession/repository/InitialGameplayLoginCoordinationJournalRepositoryIntegrationTest.java @@ -457,7 +457,13 @@ void physicalSqlRejectsReplacementReopeningDeletionAndTruncation() throws Except + " SET disposal_disposition = 'PENDING', disposal_proof_kind = 'NONE' WHERE request_id = ?", original.requestId()); rejectedSql("DELETE FROM " + TABLE + " WHERE request_id = ?", original.requestId()); - rejectedSql("TRUNCATE " + TABLE); + // Include references in this disposable schema so the journal guard, rather than the + // foreign-key precheck, rejects truncation before any retained evidence can be removed. + assertThatThrownBy(() -> dsl.execute("TRUNCATE " + TABLE + " CASCADE")) + .hasMessageContaining("Initial gameplay LOGIN journal retention is held") + .isInstanceOfSatisfying( + DataAccessException.class, + failure -> assertThat(failure.sqlState()).isEqualTo("23514")); assertThat(journal.readCommitted(original).orElseThrow().retainedReceipt()).contains(terminal); } diff --git a/services/game-session-service/src/test/java/integration/net/firedevops/firemud/gamesession/service/InitialGameplayLoginContextRedisIntegrationTest.java b/services/game-session-service/src/test/java/integration/net/firedevops/firemud/gamesession/service/InitialGameplayLoginContextRedisIntegrationTest.java index 7d2c646fe8..10147d37af 100644 --- a/services/game-session-service/src/test/java/integration/net/firedevops/firemud/gamesession/service/InitialGameplayLoginContextRedisIntegrationTest.java +++ b/services/game-session-service/src/test/java/integration/net/firedevops/firemud/gamesession/service/InitialGameplayLoginContextRedisIntegrationTest.java @@ -301,7 +301,10 @@ void exactInstallAndRetryUsePhysicalAcknowledgementsIndependentReadbackAndNoSecr var result = validatedResult(original, UUID.randomUUID()); var qualification = new ControlledAuthority(); var provider = new TracedProvider(writer); - var client = client(provider, qualification, 1); + // A positive durability proof allows replica fsync under shared-runner load. + // Insufficient-acknowledgement cases keep their separate short failure deadline. + var client = + client(provider, qualification, new AcknowledgementPolicy(Profile.REPLICATED, 1, 1, 3_000)); var installed = InitialGameplayLoginContextState.installed(original, result); provider.expectedReadback = installed.encode(); var firstInstall = client.install(original, result); diff --git a/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/repository/CanonicalGameplayAccountInitialBarrierRedisOwnerTest.java b/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/repository/CanonicalGameplayAccountInitialBarrierRedisOwnerTest.java new file mode 100644 index 0000000000..604808d8e2 --- /dev/null +++ b/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/repository/CanonicalGameplayAccountInitialBarrierRedisOwnerTest.java @@ -0,0 +1,693 @@ +package net.firedevops.firemud.gamesession.repository; + +import static org.assertj.core.api.Assertions.assertThat; +import static org.mockito.ArgumentMatchers.any; +import static org.mockito.ArgumentMatchers.anyLong; +import static org.mockito.ArgumentMatchers.eq; +import static org.mockito.Mockito.doReturn; +import static org.mockito.Mockito.mock; +import static org.mockito.Mockito.verify; +import static org.mockito.Mockito.verifyNoInteractions; +import static org.mockito.Mockito.when; + +import io.lettuce.core.RedisClient; +import io.lettuce.core.RedisFuture; +import io.lettuce.core.api.StatefulRedisConnection; +import io.lettuce.core.api.async.RedisAsyncCommands; +import io.lettuce.core.codec.ByteArrayCodec; +import java.math.BigInteger; +import java.nio.charset.StandardCharsets; +import java.util.HashMap; +import java.util.List; +import java.util.Map; +import java.util.UUID; +import java.util.concurrent.TimeUnit; +import java.util.concurrent.atomic.AtomicInteger; +import net.firedevops.firemud.common.redis.contracts.RedisScriptCatalog; +import net.firedevops.firemud.gamesession.dto.CanonicalGameplayLoginResult; +import net.firedevops.firemud.gamesession.dto.InitialGameplayLoginAttemptCoordinates; +import net.firedevops.firemud.gamesession.service.CanonicalGameplayAccountInitialBarrierRedisScriptContribution; +import org.junit.jupiter.api.Test; + +class CanonicalGameplayAccountInitialBarrierRedisOwnerTest { + private static final String DIGEST = "sha256:" + "a".repeat(64); + + @Test + @SuppressWarnings({"unchecked", "rawtypes"}) + void missingPhysicalValueAfterPossibleDispatchRefusesWithoutFreshScriptAttempt() + throws Exception { + UUID requestId = UUID.randomUUID(); + UUID callerContextId = UUID.randomUUID(); + UUID initializerId = UUID.randomUUID(); + UUID accountId = UUID.randomUUID(); + UUID tenantId = UUID.randomUUID(); + UUID namespaceId = UUID.randomUUID(); + var original = new InitialGameplayLoginAttemptCoordinates(requestId, callerContextId, 17L); + var snapshot = + new CanonicalGameplayAccountInitialBarrierInitializerRepository.InitializerSnapshot( + initializerId, + requestId, + callerContextId, + 17L, + accountId, + tenantId, + namespaceId, + DIGEST, + "NO_ACTIVE_ACCOUNT_WIDE_FLOW", + BigInteger.valueOf(8), + BigInteger.valueOf(4), + DIGEST, + CanonicalGameplayAccountInitialBarrierInitializerRepository.State.DISPATCH_POSSIBLE, + DIGEST, + DIGEST, + DIGEST, + 1_000L, + 1_100L, + 31_000L, + null, + DIGEST); + + var repository = mock(CanonicalGameplayAccountInitialBarrierInitializerRepository.class); + when(repository.beginOrRead(any(), any(), any(), any())).thenReturn(snapshot); + when(repository.readCurrent(requestId)).thenReturn(snapshot); + var tenantTags = mock(CanonicalGameplayTenantGameplayTagRepository.class); + var assignment = mock(CanonicalGameplayTenantGameplayTagRepository.Assignment.class); + when(tenantTags.assignmentForInitialBarrierTarget(requestId)).thenReturn(assignment); + when(assignment.isInitialBarrierTarget()).thenReturn(true); + when(assignment.initialBarrierInitializerId()).thenReturn(initializerId); + when(assignment.initialBarrierOriginalRequestId()).thenReturn(requestId); + when(assignment.accountId()).thenReturn(accountId); + when(assignment.tenantId()).thenReturn(tenantId); + when(assignment.playableStateNamespaceId()).thenReturn(namespaceId); + when(assignment.tenantGameplayTag()).thenReturn("g8-" + "b".repeat(32)); + + var observation = mock(CanonicalGameplayProtectedIncarnationReceiver.VerifiedIncarnation.class); + when(observation.ownerKind()) + .thenReturn( + CanonicalGameplayProtectedIncarnationReceiver.OwnerKind.INITIAL_ACCOUNT_BARRIER); + when(observation.operationId()).thenReturn(initializerId); + when(observation.requestId()).thenReturn(requestId); + when(observation.originalCallerContextId()).thenReturn(callerContextId); + when(observation.originalAttemptFence()).thenReturn(17L); + when(observation.accountId()).thenReturn(accountId); + when(observation.tenantId()).thenReturn(tenantId); + when(observation.playableStateNamespaceId()).thenReturn(namespaceId); + when(observation.sourceControlState()).thenReturn("NO_ACTIVE_ACCOUNT_WIDE_FLOW"); + when(observation.sourceControlEpoch()).thenReturn("8"); + when(observation.inventorySnapshotRevision()).thenReturn("4"); + when(observation.accountLoginEvidenceDigest()).thenReturn(DIGEST); + when(observation.sourceControlDigest()).thenReturn(DIGEST); + when(observation.barrierTargetDigest()).thenReturn(DIGEST); + when(observation.incarnationDigest()).thenReturn(DIGEST); + when(observation.acceptedAttestationDigest()).thenReturn(DIGEST); + var receiver = mock(CanonicalGameplayProtectedIncarnationReceiver.class); + when(receiver.observeForInitialAccountBarrier(requestId)).thenReturn(observation); + + RedisClient redis = mock(RedisClient.class); + StatefulRedisConnection connection = mock(StatefulRedisConnection.class); + RedisAsyncCommands commands = mock(RedisAsyncCommands.class); + when(redis.connect(any(ByteArrayCodec.class))).thenReturn(connection); + when(connection.isOpen()).thenReturn(true); + when(connection.async()).thenReturn(commands); + doReturn(future("gamesession_coord_app")).when(commands).aclWhoami(); + doReturn(future("none")).when(commands).type(any(byte[].class)); + RedisScriptCatalog catalog = mock(RedisScriptCatalog.class); + + var owner = + new CanonicalGameplayAccountInitialBarrierRedisOwner( + redis, catalog, repository, tenantTags, receiver); + var proof = + owner.initializeOnce( + original, mock(CanonicalGameplayLoginResult.class), tenantId, namespaceId); + + assertThat(proof) + .isEqualTo( + new CanonicalGameplayAccountInitialOpenProof.Refused( + CanonicalGameplayAccountInitialOpenProof.Reason.REMOTE_OUTCOME_UNCERTAIN)); + verify(repository).beginOrRead(eq(original), any(), eq(tenantId), eq(namespaceId)); + verify(commands).type(any(byte[].class)); + verifyNoInteractions(catalog); + } + + @Test + @SuppressWarnings({"unchecked", "rawtypes"}) + void possibleDispatchIsPersistedBeforeEvalAndMissingAfterwardNeverGetsAFreshCreate() + throws Exception { + UUID requestId = UUID.randomUUID(); + UUID callerContextId = UUID.randomUUID(); + UUID initializerId = UUID.randomUUID(); + UUID accountId = UUID.randomUUID(); + UUID tenantId = UUID.randomUUID(); + UUID namespaceId = UUID.randomUUID(); + var original = new InitialGameplayLoginAttemptCoordinates(requestId, callerContextId, 17L); + var never = + snapshot( + initializerId, + original, + accountId, + tenantId, + namespaceId, + CanonicalGameplayAccountInitialBarrierInitializerRepository.State.NEVER_DISPATCHED); + var possible = + new CanonicalGameplayAccountInitialBarrierInitializerRepository.InitializerSnapshot( + initializerId, + requestId, + callerContextId, + 17L, + accountId, + tenantId, + namespaceId, + DIGEST, + "NO_ACTIVE_ACCOUNT_WIDE_FLOW", + BigInteger.valueOf(8), + BigInteger.valueOf(4), + DIGEST, + CanonicalGameplayAccountInitialBarrierInitializerRepository.State.DISPATCH_POSSIBLE, + DIGEST, + DIGEST, + DIGEST, + 1_000L, + 1_100L, + 31_000L, + null, + DIGEST); + var before = initialObservation(possible); + + var repository = mock(CanonicalGameplayAccountInitialBarrierInitializerRepository.class); + when(repository.beginOrRead(any(), any(), any(), any())).thenReturn(never); + when(repository.recordDispatchPossible(requestId, before)).thenReturn(possible); + when(repository.readCurrent(requestId)).thenReturn(possible); + var tenantTags = mock(CanonicalGameplayTenantGameplayTagRepository.class); + var assignment = mock(CanonicalGameplayTenantGameplayTagRepository.Assignment.class); + when(tenantTags.assignmentForInitialBarrierTarget(requestId)).thenReturn(assignment); + when(assignment.isInitialBarrierTarget()).thenReturn(true); + when(assignment.initialBarrierInitializerId()).thenReturn(initializerId); + when(assignment.initialBarrierOriginalRequestId()).thenReturn(requestId); + when(assignment.accountId()).thenReturn(accountId); + when(assignment.tenantId()).thenReturn(tenantId); + when(assignment.playableStateNamespaceId()).thenReturn(namespaceId); + when(assignment.tenantGameplayTag()).thenReturn("g8-" + "b".repeat(32)); + var receiver = mock(CanonicalGameplayProtectedIncarnationReceiver.class); + when(receiver.observeForInitialAccountBarrier(requestId)).thenReturn(before); + + RedisClient redis = mock(RedisClient.class); + StatefulRedisConnection connection = mock(StatefulRedisConnection.class); + RedisAsyncCommands commands = mock(RedisAsyncCommands.class); + when(connection.isOpen()).thenReturn(true); + when(connection.async()).thenReturn(commands); + doReturn(future("gamesession_coord_app")).when(commands).aclWhoami(); + when(commands.scriptLoad(any(byte[].class))) + .thenAnswer( + invocation -> { + verify(repository, org.mockito.Mockito.never()).recordDispatchPossible(any(), any()); + return future( + java.util.HexFormat.of() + .formatHex( + java.security.MessageDigest.getInstance("SHA-1") + .digest(invocation.getArgument(0, byte[].class)))); + }); + when(commands.evalsha(any(), any(), any(byte[][].class), any(byte[][].class))) + .thenAnswer( + ignored -> { + verify(repository).recordDispatchPossible(requestId, before); + throw new IllegalStateException("controlled unknown EVAL outcome"); + }); + AtomicInteger connectionAttempts = new AtomicInteger(); + when(redis.connect(any(ByteArrayCodec.class))) + .thenAnswer( + ignored -> { + if (connectionAttempts.getAndIncrement() == 0) return connection; + throw new IllegalStateException("controlled lost readback connection"); + }); + RedisScriptCatalog catalog = + RedisScriptCatalog.fromContributions( + List.of(new CanonicalGameplayAccountInitialBarrierRedisScriptContribution())); + var owner = + new CanonicalGameplayAccountInitialBarrierRedisOwner( + redis, catalog, repository, tenantTags, receiver); + + var proof = + owner.initializeOnce( + original, mock(CanonicalGameplayLoginResult.class), tenantId, namespaceId); + + assertThat(proof) + .isEqualTo( + new CanonicalGameplayAccountInitialOpenProof.Refused( + CanonicalGameplayAccountInitialOpenProof.Reason.REMOTE_OUTCOME_UNCERTAIN)); + assertThat(connectionAttempts.get()).isEqualTo(2); + verify(repository).recordDispatchPossible(requestId, before); + verify(commands).evalsha(any(), any(), any(byte[][].class), any(byte[][].class)); + } + + @Test + @SuppressWarnings({"unchecked", "rawtypes"}) + void exactSameOriginalOpenReplayIsReadOnlyAndReturnsCurrentTypedProof() throws Exception { + UUID requestId = UUID.randomUUID(); + UUID callerContextId = UUID.randomUUID(); + UUID initializerId = UUID.randomUUID(); + UUID accountId = UUID.randomUUID(); + UUID tenantId = UUID.randomUUID(); + UUID namespaceId = UUID.randomUUID(); + String tag = "g8-" + "b".repeat(32); + var original = new InitialGameplayLoginAttemptCoordinates(requestId, callerContextId, 17L); + var snapshot = + new CanonicalGameplayAccountInitialBarrierInitializerRepository.InitializerSnapshot( + initializerId, + requestId, + callerContextId, + 17L, + accountId, + tenantId, + namespaceId, + DIGEST, + "NO_ACTIVE_ACCOUNT_WIDE_FLOW", + BigInteger.valueOf(8), + BigInteger.valueOf(4), + DIGEST, + CanonicalGameplayAccountInitialBarrierInitializerRepository.State.OPEN_INSTALLED, + DIGEST, + DIGEST, + DIGEST, + 1_000L, + 1_100L, + 31_000L, + DIGEST, + DIGEST); + var assignment = mock(CanonicalGameplayTenantGameplayTagRepository.Assignment.class); + when(assignment.isInitialBarrierTarget()).thenReturn(true); + when(assignment.initialBarrierInitializerId()).thenReturn(initializerId); + when(assignment.initialBarrierOriginalRequestId()).thenReturn(requestId); + when(assignment.accountId()).thenReturn(accountId); + when(assignment.tenantId()).thenReturn(tenantId); + when(assignment.playableStateNamespaceId()).thenReturn(namespaceId); + when(assignment.tenantGameplayTag()).thenReturn(tag); + var repository = mock(CanonicalGameplayAccountInitialBarrierInitializerRepository.class); + when(repository.beginOrRead(any(), any(), any(), any())).thenReturn(snapshot); + when(repository.readCurrent(requestId)).thenReturn(snapshot); + var tenantTags = mock(CanonicalGameplayTenantGameplayTagRepository.class); + when(tenantTags.assignmentForInitialBarrierTarget(requestId)).thenReturn(assignment); + var observation = initialObservation(snapshot); + var receiver = mock(CanonicalGameplayProtectedIncarnationReceiver.class); + when(receiver.observeForInitialAccountBarrier(requestId)).thenReturn(observation); + + var expected = + CanonicalGameplayAccountInitialBarrierValue.open( + accountId, tenantId, namespaceId, tag, initializerId, BigInteger.valueOf(8), DIGEST); + Map raw = new HashMap<>(); + expected + .fields() + .forEach( + (field, value) -> + raw.put( + field.getBytes(StandardCharsets.US_ASCII), + value.getBytes(StandardCharsets.US_ASCII))); + RedisClient redis = mock(RedisClient.class); + StatefulRedisConnection connection = mock(StatefulRedisConnection.class); + RedisAsyncCommands commands = mock(RedisAsyncCommands.class); + when(redis.connect(any(ByteArrayCodec.class))).thenReturn(connection); + when(connection.isOpen()).thenReturn(true); + when(connection.async()).thenReturn(commands); + doReturn(future("gamesession_coord_app")).when(commands).aclWhoami(); + doReturn(future("hash")).when(commands).type(any(byte[].class)); + doReturn(future(-1L)).when(commands).pttl(any(byte[].class)); + doReturn(future(9L)).when(commands).hlen(any(byte[].class)); + doReturn(future(raw)).when(commands).hgetall(any(byte[].class)); + RedisScriptCatalog catalog = mock(RedisScriptCatalog.class); + var owner = + new CanonicalGameplayAccountInitialBarrierRedisOwner( + redis, catalog, repository, tenantTags, receiver); + + var proof = + owner.initializeOnce( + original, mock(CanonicalGameplayLoginResult.class), tenantId, namespaceId); + + assertThat(proof).isInstanceOf(CanonicalGameplayAccountInitialOpenProof.CurrentOpen.class); + var current = (CanonicalGameplayAccountInitialOpenProof.CurrentOpen) proof; + assertThat(current.originalRequestId()).isEqualTo(requestId); + assertThat(current.sourceControlEpoch()).isEqualTo(BigInteger.valueOf(8)); + assertThat(current.exactFields()).isEqualTo(expected.fields()); + verify(repository, org.mockito.Mockito.times(2)).readCurrent(requestId); + verify(repository).beginOrRead(eq(original), any(), eq(tenantId), eq(namespaceId)); + verify(repository, org.mockito.Mockito.times(3)).requireNoAmbientTransaction(); + verify(receiver, org.mockito.Mockito.times(2)).observeForInitialAccountBarrier(requestId); + verifyNoInteractions(catalog); + verify(commands).hgetall(any(byte[].class)); + verify(commands, org.mockito.Mockito.never()) + .evalsha(any(), any(), any(byte[][].class), any(byte[][].class)); + } + + @Test + @SuppressWarnings({"unchecked", "rawtypes"}) + void installedOpenCanBeResolvedByExactTargetAndOnlyPerformsFreshReadback() throws Exception { + UUID requestId = UUID.randomUUID(); + UUID callerContextId = UUID.randomUUID(); + UUID initializerId = UUID.randomUUID(); + UUID accountId = UUID.randomUUID(); + UUID tenantId = UUID.randomUUID(); + UUID namespaceId = UUID.randomUUID(); + String tag = "g8-" + "b".repeat(32); + var snapshot = + new CanonicalGameplayAccountInitialBarrierInitializerRepository.InitializerSnapshot( + initializerId, + requestId, + callerContextId, + 17L, + accountId, + tenantId, + namespaceId, + DIGEST, + "NO_ACTIVE_ACCOUNT_WIDE_FLOW", + BigInteger.valueOf(8), + BigInteger.valueOf(4), + DIGEST, + CanonicalGameplayAccountInitialBarrierInitializerRepository.State.OPEN_INSTALLED, + DIGEST, + DIGEST, + DIGEST, + 1_000L, + 1_100L, + 31_000L, + DIGEST, + DIGEST); + var assignment = mock(CanonicalGameplayTenantGameplayTagRepository.Assignment.class); + when(assignment.isInitialBarrierTarget()).thenReturn(true); + when(assignment.initialBarrierInitializerId()).thenReturn(initializerId); + when(assignment.initialBarrierOriginalRequestId()).thenReturn(requestId); + when(assignment.accountId()).thenReturn(accountId); + when(assignment.tenantId()).thenReturn(tenantId); + when(assignment.playableStateNamespaceId()).thenReturn(namespaceId); + when(assignment.tenantGameplayTag()).thenReturn(tag); + var repository = mock(CanonicalGameplayAccountInitialBarrierInitializerRepository.class); + when(repository.readInstalledOpenForTarget(accountId, tenantId, namespaceId)) + .thenReturn(snapshot); + when(repository.readCurrent(requestId)).thenReturn(snapshot); + var tenantTags = mock(CanonicalGameplayTenantGameplayTagRepository.class); + when(tenantTags.assignmentForInitialBarrierTarget(requestId)).thenReturn(assignment); + var observation = initialObservation(snapshot); + var receiver = mock(CanonicalGameplayProtectedIncarnationReceiver.class); + when(receiver.observeForInitialAccountBarrier(requestId)).thenReturn(observation); + + var expected = + CanonicalGameplayAccountInitialBarrierValue.open( + accountId, tenantId, namespaceId, tag, initializerId, BigInteger.valueOf(8), DIGEST); + Map raw = new HashMap<>(); + expected + .fields() + .forEach( + (field, value) -> + raw.put( + field.getBytes(StandardCharsets.US_ASCII), + value.getBytes(StandardCharsets.US_ASCII))); + RedisClient redis = mock(RedisClient.class); + StatefulRedisConnection connection = mock(StatefulRedisConnection.class); + RedisAsyncCommands commands = mock(RedisAsyncCommands.class); + when(redis.connect(any(ByteArrayCodec.class))).thenReturn(connection); + when(connection.isOpen()).thenReturn(true); + when(connection.async()).thenReturn(commands); + doReturn(future("gamesession_coord_app")).when(commands).aclWhoami(); + doReturn(future("hash")).when(commands).type(any(byte[].class)); + doReturn(future(-1L)).when(commands).pttl(any(byte[].class)); + doReturn(future(9L)).when(commands).hlen(any(byte[].class)); + doReturn(future(raw)).when(commands).hgetall(any(byte[].class)); + RedisScriptCatalog catalog = mock(RedisScriptCatalog.class); + var owner = + new CanonicalGameplayAccountInitialBarrierRedisOwner( + redis, catalog, repository, tenantTags, receiver); + + var proof = owner.verifyCurrentOpenForTarget(accountId, tenantId, namespaceId); + + assertThat(proof).isInstanceOf(CanonicalGameplayAccountInitialOpenProof.CurrentOpen.class); + var current = (CanonicalGameplayAccountInitialOpenProof.CurrentOpen) proof; + assertThat(current.originalRequestId()).isEqualTo(requestId); + assertThat(current.exactFields()).isEqualTo(expected.fields()); + verify(repository).readInstalledOpenForTarget(accountId, tenantId, namespaceId); + verify(repository, org.mockito.Mockito.times(2)).readCurrent(requestId); + verify(tenantTags).assignmentForInitialBarrierTarget(requestId); + verify(receiver, org.mockito.Mockito.times(2)).observeForInitialAccountBarrier(requestId); + verifyNoInteractions(catalog); + verify(commands).hgetall(any(byte[].class)); + verify(commands, org.mockito.Mockito.never()) + .evalsha(any(), any(), any(byte[][].class), any(byte[][].class)); + } + + @Test + void missingAmbiguousAndStaleTargetResolutionNeverReachPhysicalReadOrCreate() { + UUID missingAccount = UUID.randomUUID(); + UUID ambiguousAccount = UUID.randomUUID(); + UUID staleAccount = UUID.randomUUID(); + UUID tenantId = UUID.randomUUID(); + UUID namespaceId = UUID.randomUUID(); + var repository = mock(CanonicalGameplayAccountInitialBarrierInitializerRepository.class); + when(repository.readInstalledOpenForTarget(missingAccount, tenantId, namespaceId)) + .thenThrow(new IllegalStateException("no installed target")); + when(repository.readInstalledOpenForTarget(ambiguousAccount, tenantId, namespaceId)) + .thenThrow(new IllegalStateException("multiple installed targets")); + when(repository.readInstalledOpenForTarget(staleAccount, tenantId, namespaceId)) + .thenThrow(new IllegalStateException("NO_ACTIVE source changed")); + var tenantTags = mock(CanonicalGameplayTenantGameplayTagRepository.class); + var receiver = mock(CanonicalGameplayProtectedIncarnationReceiver.class); + RedisClient redis = mock(RedisClient.class); + RedisScriptCatalog catalog = mock(RedisScriptCatalog.class); + var owner = + new CanonicalGameplayAccountInitialBarrierRedisOwner( + redis, catalog, repository, tenantTags, receiver); + + var missing = owner.verifyCurrentOpenForTarget(missingAccount, tenantId, namespaceId); + var ambiguous = owner.verifyCurrentOpenForTarget(ambiguousAccount, tenantId, namespaceId); + var stale = owner.verifyCurrentOpenForTarget(staleAccount, tenantId, namespaceId); + + var refused = + new CanonicalGameplayAccountInitialOpenProof.Refused( + CanonicalGameplayAccountInitialOpenProof.Reason.SOURCE_CONTROL_UNAVAILABLE); + assertThat(missing).isEqualTo(refused); + assertThat(ambiguous).isEqualTo(refused); + assertThat(stale).isEqualTo(refused); + verify(repository).readInstalledOpenForTarget(missingAccount, tenantId, namespaceId); + verify(repository).readInstalledOpenForTarget(ambiguousAccount, tenantId, namespaceId); + verify(repository).readInstalledOpenForTarget(staleAccount, tenantId, namespaceId); + verifyNoInteractions(tenantTags, receiver, redis, catalog); + } + + @Test + void nonInstalledTargetIsRefusedWithoutFresheningOrRecreatingIt() { + UUID accountId = UUID.randomUUID(); + UUID tenantId = UUID.randomUUID(); + UUID namespaceId = UUID.randomUUID(); + var never = + snapshot( + UUID.randomUUID(), + new InitialGameplayLoginAttemptCoordinates(UUID.randomUUID(), UUID.randomUUID(), 17L), + accountId, + tenantId, + namespaceId, + CanonicalGameplayAccountInitialBarrierInitializerRepository.State.NEVER_DISPATCHED); + var repository = mock(CanonicalGameplayAccountInitialBarrierInitializerRepository.class); + when(repository.readInstalledOpenForTarget(accountId, tenantId, namespaceId)).thenReturn(never); + var tenantTags = mock(CanonicalGameplayTenantGameplayTagRepository.class); + var receiver = mock(CanonicalGameplayProtectedIncarnationReceiver.class); + RedisClient redis = mock(RedisClient.class); + RedisScriptCatalog catalog = mock(RedisScriptCatalog.class); + var owner = + new CanonicalGameplayAccountInitialBarrierRedisOwner( + redis, catalog, repository, tenantTags, receiver); + + var proof = owner.verifyCurrentOpenForTarget(accountId, tenantId, namespaceId); + + assertThat(proof) + .isEqualTo( + new CanonicalGameplayAccountInitialOpenProof.Refused( + CanonicalGameplayAccountInitialOpenProof.Reason.TARGET_NEVER_DISPATCHED)); + verify(repository).readInstalledOpenForTarget(accountId, tenantId, namespaceId); + verifyNoInteractions(tenantTags, receiver, redis, catalog); + } + + @Test + @SuppressWarnings({"unchecked", "rawtypes"}) + void ambiguousDispatchRetryRequiresExactOpenReadbackBeforeCompletingOriginalReceipt() + throws Exception { + UUID requestId = UUID.randomUUID(); + UUID callerContextId = UUID.randomUUID(); + UUID initializerId = UUID.randomUUID(); + UUID accountId = UUID.randomUUID(); + UUID tenantId = UUID.randomUUID(); + UUID namespaceId = UUID.randomUUID(); + String tag = "g8-" + "b".repeat(32); + var original = new InitialGameplayLoginAttemptCoordinates(requestId, callerContextId, 17L); + var pending = + new CanonicalGameplayAccountInitialBarrierInitializerRepository.InitializerSnapshot( + initializerId, + requestId, + callerContextId, + 17L, + accountId, + tenantId, + namespaceId, + DIGEST, + "NO_ACTIVE_ACCOUNT_WIDE_FLOW", + BigInteger.valueOf(8), + BigInteger.valueOf(4), + DIGEST, + CanonicalGameplayAccountInitialBarrierInitializerRepository.State.DISPATCH_POSSIBLE, + DIGEST, + DIGEST, + DIGEST, + 1_000L, + 1_100L, + 31_000L, + null, + DIGEST); + var installed = + new CanonicalGameplayAccountInitialBarrierInitializerRepository.InitializerSnapshot( + initializerId, + requestId, + callerContextId, + 17L, + accountId, + tenantId, + namespaceId, + DIGEST, + "NO_ACTIVE_ACCOUNT_WIDE_FLOW", + BigInteger.valueOf(8), + BigInteger.valueOf(4), + DIGEST, + CanonicalGameplayAccountInitialBarrierInitializerRepository.State.OPEN_INSTALLED, + DIGEST, + DIGEST, + DIGEST, + 1_000L, + 1_100L, + 31_000L, + DIGEST, + DIGEST); + var assignment = mock(CanonicalGameplayTenantGameplayTagRepository.Assignment.class); + when(assignment.isInitialBarrierTarget()).thenReturn(true); + when(assignment.initialBarrierInitializerId()).thenReturn(initializerId); + when(assignment.initialBarrierOriginalRequestId()).thenReturn(requestId); + when(assignment.accountId()).thenReturn(accountId); + when(assignment.tenantId()).thenReturn(tenantId); + when(assignment.playableStateNamespaceId()).thenReturn(namespaceId); + when(assignment.tenantGameplayTag()).thenReturn(tag); + var repository = mock(CanonicalGameplayAccountInitialBarrierInitializerRepository.class); + when(repository.beginOrRead(any(), any(), any(), any())).thenReturn(pending); + when(repository.readCurrent(requestId)).thenReturn(pending); + when(repository.acceptOpenReadback(any(), any())).thenReturn(installed); + var tenantTags = mock(CanonicalGameplayTenantGameplayTagRepository.class); + when(tenantTags.assignmentForInitialBarrierTarget(requestId)).thenReturn(assignment); + var observation = initialObservation(pending); + var receiver = mock(CanonicalGameplayProtectedIncarnationReceiver.class); + when(receiver.observeForInitialAccountBarrier(requestId)).thenReturn(observation); + + var expected = + CanonicalGameplayAccountInitialBarrierValue.open( + accountId, tenantId, namespaceId, tag, initializerId, BigInteger.valueOf(8), DIGEST); + Map raw = new HashMap<>(); + expected + .fields() + .forEach( + (field, value) -> + raw.put( + field.getBytes(StandardCharsets.US_ASCII), + value.getBytes(StandardCharsets.US_ASCII))); + RedisClient redis = mock(RedisClient.class); + StatefulRedisConnection connection = mock(StatefulRedisConnection.class); + RedisAsyncCommands commands = mock(RedisAsyncCommands.class); + when(redis.connect(any(ByteArrayCodec.class))).thenReturn(connection); + when(connection.isOpen()).thenReturn(true); + when(connection.async()).thenReturn(commands); + doReturn(future("gamesession_coord_app")).when(commands).aclWhoami(); + doReturn(future("hash")).when(commands).type(any(byte[].class)); + doReturn(future(-1L)).when(commands).pttl(any(byte[].class)); + doReturn(future(9L)).when(commands).hlen(any(byte[].class)); + doReturn(future(raw)).when(commands).hgetall(any(byte[].class)); + RedisScriptCatalog catalog = mock(RedisScriptCatalog.class); + var owner = + new CanonicalGameplayAccountInitialBarrierRedisOwner( + redis, catalog, repository, tenantTags, receiver); + + var proof = + owner.initializeOnce( + original, mock(CanonicalGameplayLoginResult.class), tenantId, namespaceId); + + assertThat(proof).isInstanceOf(CanonicalGameplayAccountInitialOpenProof.CurrentOpen.class); + var current = (CanonicalGameplayAccountInitialOpenProof.CurrentOpen) proof; + assertThat(current.originalRequestId()).isEqualTo(requestId); + assertThat(current.exactFields()).isEqualTo(expected.fields()); + verify(repository).acceptOpenReadback(eq(requestId), any()); + verify(repository).readCurrent(requestId); + verify(receiver, org.mockito.Mockito.times(2)).observeForInitialAccountBarrier(requestId); + verifyNoInteractions(catalog); + verify(commands).hgetall(any(byte[].class)); + verify(commands, org.mockito.Mockito.never()) + .evalsha(any(), any(), any(byte[][].class), any(byte[][].class)); + } + + private static CanonicalGameplayAccountInitialBarrierInitializerRepository.InitializerSnapshot + snapshot( + UUID initializerId, + InitialGameplayLoginAttemptCoordinates original, + UUID accountId, + UUID tenantId, + UUID namespaceId, + CanonicalGameplayAccountInitialBarrierInitializerRepository.State state) { + return new CanonicalGameplayAccountInitialBarrierInitializerRepository.InitializerSnapshot( + initializerId, + original.requestId(), + original.callerContextId(), + original.expectedAttemptFence(), + accountId, + tenantId, + namespaceId, + DIGEST, + "NO_ACTIVE_ACCOUNT_WIDE_FLOW", + BigInteger.valueOf(8), + BigInteger.valueOf(4), + DIGEST, + state, + null, + null, + null, + 0L, + 0L, + 0L, + null, + DIGEST); + } + + private static CanonicalGameplayProtectedIncarnationReceiver.VerifiedIncarnation + initialObservation( + CanonicalGameplayAccountInitialBarrierInitializerRepository.InitializerSnapshot + snapshot) { + var observation = mock(CanonicalGameplayProtectedIncarnationReceiver.VerifiedIncarnation.class); + when(observation.ownerKind()) + .thenReturn( + CanonicalGameplayProtectedIncarnationReceiver.OwnerKind.INITIAL_ACCOUNT_BARRIER); + when(observation.operationId()).thenReturn(snapshot.initializerId()); + when(observation.requestId()).thenReturn(snapshot.originalRequestId()); + when(observation.originalCallerContextId()).thenReturn(snapshot.originalCallerContextId()); + when(observation.originalAttemptFence()).thenReturn(snapshot.originalAttemptFence()); + when(observation.accountId()).thenReturn(snapshot.accountId()); + when(observation.tenantId()).thenReturn(snapshot.tenantId()); + when(observation.playableStateNamespaceId()).thenReturn(snapshot.playableStateNamespaceId()); + when(observation.sourceControlState()).thenReturn(snapshot.sourceControlState()); + when(observation.sourceControlEpoch()).thenReturn(snapshot.sourceControlEpoch().toString()); + when(observation.inventorySnapshotRevision()) + .thenReturn(snapshot.inventorySnapshotRevision().toString()); + when(observation.accountLoginEvidenceDigest()) + .thenReturn(snapshot.accountLoginEvidenceDigest()); + when(observation.sourceControlDigest()).thenReturn(snapshot.sourceControlDigest()); + when(observation.barrierTargetDigest()).thenReturn(snapshot.targetDigest()); + when(observation.incarnationDigest()).thenReturn(DIGEST); + when(observation.acceptedAttestationDigest()).thenReturn(DIGEST); + when(observation.payloadDigest()).thenReturn(DIGEST); + when(observation.issuedAtEpochMillis()).thenReturn(1_000L); + when(observation.observedAtEpochMillis()).thenReturn(1_100L); + when(observation.expiresAtEpochMillis()).thenReturn(31_000L); + return observation; + } + + private static RedisFuture future(T value) throws Exception { + RedisFuture future = mock(RedisFuture.class); + when(future.get(anyLong(), any(TimeUnit.class))).thenReturn(value); + return future; + } +} diff --git a/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/repository/CanonicalGameplayAccountInitialBarrierValueTest.java b/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/repository/CanonicalGameplayAccountInitialBarrierValueTest.java new file mode 100644 index 0000000000..8ce2a1fa43 --- /dev/null +++ b/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/repository/CanonicalGameplayAccountInitialBarrierValueTest.java @@ -0,0 +1,192 @@ +package net.firedevops.firemud.gamesession.repository; + +import static org.assertj.core.api.Assertions.assertThat; +import static org.assertj.core.api.Assertions.assertThatThrownBy; +import static org.mockito.Mockito.mock; +import static org.mockito.Mockito.when; + +import java.math.BigInteger; +import java.util.LinkedHashMap; +import java.util.Map; +import java.util.UUID; +import org.junit.jupiter.api.Test; + +class CanonicalGameplayAccountInitialBarrierValueTest { + private static final String DIGEST = "sha256:" + "a".repeat(64); + + @Test + void initialBarrierValueRetainsTheExactPositivelyReadEpochIncludingZero() { + UUID accountId = UUID.randomUUID(); + UUID tenantId = UUID.randomUUID(); + UUID namespaceId = UUID.randomUUID(); + UUID initializerId = UUID.randomUUID(); + + var value = + CanonicalGameplayAccountInitialBarrierValue.open( + accountId, + tenantId, + namespaceId, + "g7-" + "b".repeat(32), + initializerId, + BigInteger.ZERO, + DIGEST); + + assertThat(value.fields()) + .containsExactlyInAnyOrderEntriesOf( + Map.of( + "schema", + CanonicalGameplayAccountInitialBarrierValue.SCHEMA, + "accountId", + accountId.toString(), + "tenantId", + tenantId.toString(), + "playableStateNamespaceId", + namespaceId.toString(), + "tenantGameplayTag", + "g7-" + "b".repeat(32), + "ownerOperationId", + initializerId.toString(), + "ownerFenceEpoch", + "0", + "incarnationDigest", + DIGEST, + "state", + "OPEN")); + assertThat(value.fields().keySet()) + .containsExactlyInAnyOrderElementsOf(CanonicalGameplayAccountInitialBarrierValue.FIELDS); + } + + @Test + void currentOpenProofRequiresExactCapturedEpochOriginalAttemptAndNineFields() { + UUID initializerId = UUID.randomUUID(); + UUID requestId = UUID.randomUUID(); + UUID callerContextId = UUID.randomUUID(); + UUID accountId = UUID.randomUUID(); + UUID tenantId = UUID.randomUUID(); + UUID namespaceId = UUID.randomUUID(); + var value = + CanonicalGameplayAccountInitialBarrierValue.open( + accountId, + tenantId, + namespaceId, + "g8-" + "c".repeat(32), + initializerId, + BigInteger.valueOf(9), + DIGEST); + + var proof = + new CanonicalGameplayAccountInitialOpenProof.CurrentOpen( + initializerId, + requestId, + callerContextId, + 9, + accountId, + tenantId, + namespaceId, + "session:game:account-admission:{g8-" + + "c".repeat(32) + + "}:" + + accountId + + ":" + + namespaceId, + BigInteger.valueOf(9), + BigInteger.ONE, + DIGEST, + DIGEST, + DIGEST, + 1_000L, + 31_000L, + value.fields()); + + assertThat(proof.originalAttemptFence()).isEqualTo(9L); + assertThat(proof.sourceControlEpoch()).isEqualTo(BigInteger.valueOf(9)); + assertThat(proof.exactFields()).containsEntry("ownerFenceEpoch", "9"); + assertThatThrownBy( + () -> + new CanonicalGameplayAccountInitialOpenProof.CurrentOpen( + initializerId, + requestId, + callerContextId, + 9, + accountId, + tenantId, + namespaceId, + proof.key(), + BigInteger.ONE, + BigInteger.ONE, + DIGEST, + DIGEST, + DIGEST, + 1_000L, + 31_000L, + value.fields())) + .isInstanceOf(IllegalArgumentException.class); + Map changed = new LinkedHashMap<>(value.fields()); + changed.put("ownerFenceEpoch", "1"); + assertThatThrownBy( + () -> + new CanonicalGameplayAccountInitialOpenProof.CurrentOpen( + initializerId, + requestId, + callerContextId, + 9, + accountId, + tenantId, + namespaceId, + proof.key(), + BigInteger.ZERO, + BigInteger.ONE, + DIGEST, + DIGEST, + DIGEST, + 1_000L, + 31_000L, + changed)) + .isInstanceOf(IllegalArgumentException.class); + } + + @Test + void unavailableSourcesHaveTypedNonAdmittingRefusals() { + assertThat( + new CanonicalGameplayAccountInitialOpenProof.Refused( + CanonicalGameplayAccountInitialOpenProof.Reason.REMOTE_OUTCOME_UNCERTAIN)) + .isInstanceOf(CanonicalGameplayAccountInitialOpenProof.Refused.class) + .extracting(CanonicalGameplayAccountInitialOpenProof.Refused::reason) + .isEqualTo(CanonicalGameplayAccountInitialOpenProof.Reason.REMOTE_OUTCOME_UNCERTAIN); + } + + @Test + void initialKeyUsesCanonicalBarrierSerializationOnlyForItsPersistedOriginalTarget() { + UUID initializerId = UUID.randomUUID(); + UUID requestId = UUID.randomUUID(); + UUID accountId = UUID.randomUUID(); + UUID tenantId = UUID.randomUUID(); + UUID namespaceId = UUID.randomUUID(); + var assignment = mock(CanonicalGameplayTenantGameplayTagRepository.Assignment.class); + when(assignment.isInitialBarrierTarget()).thenReturn(true); + when(assignment.initialBarrierInitializerId()).thenReturn(initializerId); + when(assignment.initialBarrierOriginalRequestId()).thenReturn(requestId); + when(assignment.tenantGameplayTag()).thenReturn("g7-" + tenantId.toString().replace("-", "")); + when(assignment.accountId()).thenReturn(accountId); + when(assignment.playableStateNamespaceId()).thenReturn(namespaceId); + + String key = + CanonicalGameplayAccountInitialBarrierKey.forTarget(assignment, initializerId, requestId); + + assertThat(key) + .isEqualTo( + "session:game:account-admission:{g7-" + + tenantId.toString().replace("-", "") + + "}:" + + accountId + + ":" + + namespaceId); + assertThatThrownBy( + () -> + CanonicalGameplayAccountInitialBarrierKey.forTarget( + assignment, UUID.randomUUID(), requestId)) + .isInstanceOf(IllegalArgumentException.class); + assertThatThrownBy(() -> CanonicalGameplaySessionRedisKeys.accountAdmissionBarrier(assignment)) + .isInstanceOf(IllegalArgumentException.class); + } +} diff --git a/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/repository/CanonicalGameplayIssuerBindingLocalAcknowledgementCodecTest.java b/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/repository/CanonicalGameplayIssuerBindingLocalAcknowledgementCodecTest.java new file mode 100644 index 0000000000..547748b9eb --- /dev/null +++ b/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/repository/CanonicalGameplayIssuerBindingLocalAcknowledgementCodecTest.java @@ -0,0 +1,249 @@ +package net.firedevops.firemud.gamesession.repository; + +import static org.assertj.core.api.Assertions.assertThat; +import static org.assertj.core.api.Assertions.assertThatThrownBy; + +import com.fasterxml.jackson.databind.ObjectMapper; +import com.fasterxml.jackson.databind.node.ObjectNode; +import java.math.BigInteger; +import java.nio.charset.StandardCharsets; +import java.util.UUID; +import net.firedevops.firemud.gamesession.binding.CanonicalIssuerPartitionReservation; +import org.junit.jupiter.api.Test; + +class CanonicalGameplayIssuerBindingLocalAcknowledgementCodecTest { + private static final ObjectMapper JSON = new ObjectMapper(); + private static final BigInteger LARGE = new BigInteger("9007199254740997"); + + @Test + void roundTripsDistinctOriginalReservationAnchorAndLocalOperationEvidence() throws Exception { + var evidence = fixture(); + byte[] encoded = CanonicalGameplayIssuerBindingLocalAcknowledgementCodec.encode(evidence); + + var decoded = CanonicalGameplayIssuerBindingLocalAcknowledgementCodec.decode(encoded); + ObjectNode root = (ObjectNode) JSON.readTree(encoded); + + assertThat(CanonicalGameplayIssuerBindingLocalAcknowledgementCodec.encode(decoded)) + .containsExactly(encoded); + assertThat(root.path("schemaVersion").intValue()).isEqualTo(1); + assertThat(root.path("scope").textValue()).isEqualTo("ISSUER_BINDING_LOCAL"); + assertThat(root.path("issuerBindingLocalAcknowledgementGeneration").textValue()) + .isEqualTo("83"); + assertThat(root.path("globalIssuerCoverageGeneration").textValue()).isEqualTo("NOT_YET_ISSUED"); + assertThat(root.path("anchor").path("globalCoverageGeneration").textValue()).isEqualTo("5"); + assertThat(root.path("reservation").path("issuerCoverageOperationId").textValue()) + .isNotEqualTo(root.path("anchor").path("issuerCoverageOperationId").textValue()); + assertThat(root.path("reservation").path("coverageFence").textValue()) + .isNotEqualTo(root.path("anchor").path("coverageFence").textValue()); + assertThat(root.path("memberOperation").path("generation").textValue()) + .isNotEqualTo(root.path("globalIssuerCoverageGeneration").textValue()); + } + + @Test + void roundTripsGenerationBeyondJsonExactIntegerRange() throws Exception { + byte[] encoded = CanonicalGameplayIssuerBindingLocalAcknowledgementCodec.encode(fixture(LARGE)); + var decoded = CanonicalGameplayIssuerBindingLocalAcknowledgementCodec.decode(encoded); + + assertThat( + JSON.readTree(encoded).path("issuerBindingLocalAcknowledgementGeneration").textValue()) + .isEqualTo(LARGE.toString()); + assertThat(decoded.issuerBindingLocalAcknowledgementGeneration()).isEqualTo(LARGE); + assertThat(CanonicalGameplayIssuerBindingLocalAcknowledgementCodec.encode(decoded)) + .containsExactly(encoded); + } + + @Test + void rejectsUnknownFieldsAndAnAccountOrGlobalCoverageAlias() throws Exception { + byte[] encoded = CanonicalGameplayIssuerBindingLocalAcknowledgementCodec.encode(fixture()); + ObjectNode original = (ObjectNode) JSON.readTree(encoded); + ObjectNode unknown = original.deepCopy(); + unknown.put("accountIndexAcknowledgementSchemaVersion", 2); + ObjectNode globalCoverage = original.deepCopy(); + globalCoverage.put("globalIssuerCoverageGeneration", "17"); + ObjectNode unissuedAcknowledgement = original.deepCopy(); + unissuedAcknowledgement.put("issuerBindingLocalAcknowledgementGeneration", "NOT_YET_ISSUED"); + + assertThatThrownBy( + () -> + CanonicalGameplayIssuerBindingLocalAcknowledgementCodec.decode( + JSON.writeValueAsBytes(unknown))) + .isInstanceOf(IllegalArgumentException.class) + .hasMessageContaining("missing or unknown fields"); + assertThatThrownBy( + () -> + CanonicalGameplayIssuerBindingLocalAcknowledgementCodec.decode( + JSON.writeValueAsBytes(globalCoverage))) + .isInstanceOf(IllegalArgumentException.class) + .hasMessageContaining("version or scope"); + assertThatThrownBy( + () -> + CanonicalGameplayIssuerBindingLocalAcknowledgementCodec.decode( + JSON.writeValueAsBytes(unissuedAcknowledgement))) + .isInstanceOf(IllegalArgumentException.class); + } + + @Test + void rejectsDifferentOriginalReservationProvenanceUnderTheSameBinding() { + var original = fixture(); + var changedReservation = + new CanonicalGameplayIssuerBindingLocalAcknowledgement.Reservation( + original.reservation().reservationId(), + original.reservation().transitionId(), + original.reservation().reservationFence(), + original.reservation().partitionId(), + original.reservation().lifecycle(), + uuid(51), + original.reservation().issuerCoverageOperationFence().add(BigInteger.ONE), + original.reservation().coverageFence().add(BigInteger.ONE), + original.reservation().inventorySnapshotRevision().add(BigInteger.ONE), + original.reservation().inventoryRevision()); + + assertThatThrownBy( + () -> + new CanonicalGameplayIssuerBindingLocalAcknowledgement.Evidence( + original.operationId(), + original.issuerBindingLocalAcknowledgementGeneration(), + original.requestId(), + original.transitionId(), + original.candidateAccountIndexFence(), + original.issuerId(), + original.bindingRef(), + original.bindingGeneration(), + original.memberValueBytes(), + original.memberValueDigest(), + changedReservation, + original.anchor(), + original.memberOperation(), + original.currentSource(), + original.physicalReadback(), + original.capacity(), + original.sqlCurrentnessDigest())) + .isInstanceOf(IllegalArgumentException.class) + .hasMessageContaining("exact member and proof tuples"); + } + + private static CanonicalGameplayIssuerBindingLocalAcknowledgement.Evidence fixture() { + return fixture(BigInteger.valueOf(83)); + } + + private static CanonicalGameplayIssuerBindingLocalAcknowledgement.Evidence fixture( + BigInteger acknowledgementGeneration) { + var sourceMember = CanonicalGameplayIssuerMemberV2ValueCodecTest.fixture(); + var original = sourceMember.reservation(); + var reservation = + new CanonicalIssuerPartitionReservation( + original.reservationId(), + sourceMember.owner(), + sourceMember.bindingGeneration(), + original.transitionId(), + original.partitionId(), + CanonicalIssuerPartitionReservation.Lifecycle.RESERVED, + original.reservationFence(), + original.issuerCoverageOperationId(), + original.issuerCoverageOperationFence(), + original.coverageFence(), + original.inventorySnapshotRevision(), + original.inventoryRevision()); + var member = + new CanonicalGameplayIssuerMemberV2Value( + sourceMember.owner(), + sourceMember.bindingGeneration(), + reservation, + sourceMember.anchor(), + sourceMember.memberOperation(), + sourceMember.anchor().operationFence(), + sourceMember.layoutDescriptor(), + sourceMember.sourceCheckpoint(), + sourceMember.incarnation()); + byte[] memberBytes = CanonicalGameplayIssuerMemberV2Codec.encode(member); + byte[] readbackBytes = "exact-physical-field-set/v1".getBytes(StandardCharsets.UTF_8); + byte[] checkpointBytes = member.sourceCheckpoint().exactCheckpointBytes(); + byte[] eventBytes = member.sourceCheckpoint().latestIssuerEventBytes(); + byte[] incarnationBytes = + CanonicalGameplayIssuerInstalledAnchor.encodeIncarnation(member.incarnation()); + byte[] layoutBytes = member.layoutDescriptor().exactDescriptorBytes(); + byte[] anchorBytes = "installed-anchor/v1".getBytes(StandardCharsets.UTF_8); + BigInteger one = BigInteger.ONE; + BigInteger bound = + member + .layoutDescriptor() + .partitionCount() + .multiply(member.layoutDescriptor().partitionCapacity()); + return new CanonicalGameplayIssuerBindingLocalAcknowledgement.Evidence( + member.memberOperation().operationId(), + acknowledgementGeneration, + uuid(41), + member.reservation().transitionId(), + uuid(42), + member.owner().issuerId(), + member.owner().bindingRef().bytes(), + member.bindingGeneration(), + memberBytes, + CanonicalGameplayIssuerMemberV2Codec.sha256(memberBytes), + new CanonicalGameplayIssuerBindingLocalAcknowledgement.Reservation( + reservation.reservationId(), + reservation.transitionId(), + reservation.reservationFence(), + reservation.partitionId(), + reservation.lifecycle().name(), + reservation.issuerCoverageOperationId(), + reservation.issuerCoverageOperationFence(), + reservation.coverageFence(), + reservation.inventorySnapshotRevision(), + reservation.inventoryRevision()), + new CanonicalGameplayIssuerBindingLocalAcknowledgement.Anchor( + member.anchor().issuerCoverageOperationId(), + member.anchor().issuerCoverageOperationId(), + member.anchor().operationFence(), + member.anchor().coverageFence(), + member.anchor().issuerInventorySnapshotRevision(), + BigInteger.valueOf(5), + member.issuerControlEpoch(), + member.layoutDescriptor().layoutVersion(), + member.layoutDescriptor().partitionCount(), + member.layoutDescriptor().partitionCapacity(), + member.layoutDescriptor().mappingIdentity(), + layoutBytes, + member.layoutDescriptor().descriptorDigest(), + anchorBytes, + CanonicalGameplayIssuerMemberV2Codec.sha256(anchorBytes)), + new CanonicalGameplayIssuerBindingLocalAcknowledgement.MemberOperation( + member.memberOperation().operationId(), + member.memberOperation().operationFence(), + member.memberOperation().coverageGeneration()), + new CanonicalGameplayIssuerBindingLocalAcknowledgement.CurrentSource( + member.owner().issuerAuthGeneration(), + checkpointBytes, + member.sourceCheckpoint().checkpointDigest(), + eventBytes, + member.sourceCheckpoint().latestIssuerEventDigest(), + incarnationBytes, + CanonicalGameplayIssuerMemberV2Codec.sha256(incarnationBytes)), + new CanonicalGameplayIssuerBindingLocalAcknowledgement.PhysicalReadback( + memberBytes, + CanonicalGameplayIssuerMemberV2Codec.sha256(memberBytes), + memberBytes, + CanonicalGameplayIssuerMemberV2Codec.sha256(memberBytes), + CanonicalGameplayIssuerMemberV2Codec.sha256(readbackBytes), + 2, + 4, + 1, + 1, + 1), + new CanonicalGameplayIssuerBindingLocalAcknowledgement.Capacity( + reservation.partitionId(), + member.layoutDescriptor().partitionCapacity(), + BigInteger.ZERO, + BigInteger.ZERO, + BigInteger.ZERO, + one, + one, + bound), + CanonicalGameplayIssuerMemberV2Codec.sha256( + "current-sql-cohort/v1".getBytes(StandardCharsets.UTF_8))); + } + + private static UUID uuid(long value) { + return UUID.fromString(String.format("00000000-0000-0000-0000-%012d", value)); + } +}