diff --git a/.github/workflows/smoke.yml b/.github/workflows/smoke.yml index 3280e79f20..b8d5e3f612 100644 --- a/.github/workflows/smoke.yml +++ b/.github/workflows/smoke.yml @@ -616,19 +616,19 @@ jobs: // Include held-admission proof, authenticated cleanup, and their executed inputs. const canonicalPlayClassifierSha256 = { "dev-tools/verify-smoke-images.sh": "6597800feb9604921a55be989e70247ec4610f81ac8c203f038429c1be7d0bc7", - "dev-tools/smoke/smoke_common.py": "b986110c875c2ed49e8239d09946b2c40fe7081fc3daa7cb8d5d6ce201330907", - "services/game-session-service/websocket-login-look-smoke.sh": "48c4969a4e29e2ea974d43405741de79f582b6131576f2ca2b5ddbbc818bf0ca", + "dev-tools/smoke/smoke_common.py": "74c37f2641b457eb6dda266f30222c5cc7448ab0ba14f374d413a7d6d54514e1", + "services/game-session-service/websocket-login-look-smoke.sh": "60bc796c04364706235816b02b1b495f1e1e2d260b6d36b093dd0ed2eb845d44", "dev-tools/smoke/demo-smoke-defaults.sh": "8c9aae1abf005b47af3f313e0d635a666c74776733bcf5278a2e11ac9c8a18fb", "dev-tools/smoke/held-admission-qualification.sh": "b548a773f1786b72d40a3728052a336cb249257a3f40735f005b060812184ed3", "dev-tools/smoke/held_admission_qualification.py": "2d118d7ba6a19dac7d8c717dbbbe25df6f04a3c186a3185135d1bdc5fc75b557", - "dev-tools/smoke/run-owned-compose.sh": "fc127524510c02cc0fd5a1a588868be48e5a42783529e14b2b823eaf85dce5e5", + "dev-tools/smoke/run-owned-compose.sh": "7b96cb02d5414283264c4d5e9a1b85ae063ada35dc834696f9016e520583a960", "dev-tools/certs/ensure-dev-certs.sh": "b94f8b1a18d53c818528d1fe31caa5d4270ad324dad6408aeaf896cdbf5f2e2b", ".env.sample": "d19cecadde844c77b8e1d366b5a2ff8fae1a5c181fad450f3fc1c407be70752d", "docker/docker-compose.yml": "0e8ea0fc42a6388a267d6f80baaf1259f38a73c460aa3db77a09be0fa9436a19", "docker/docker-compose.override.yml": "2e720be03f942fd4456d46cea5a127f16106a1056aec6ddaaf52b2bb31b51d75", "docker/docker-compose.smoke-images.override.yml": "7717be8b49a1dc548a47fba852c181feeb4dbe9a21fc201a7f8e74b992801fd6", "docker/docker-compose.pr-local-minio.override.yml": "d975ce211afcb73079a21c70fda358e3a8f3366b83fe0302907c9d7149ce965e", - "docker/docker-compose.grpc-mtls.override.yml": "b8378f7e41849b63f95fa2f233c897d65b6ac1b0d3ccf4777aa924b3b35bceb4" + "docker/docker-compose.grpc-mtls.override.yml": "e6ee1a005a28aa7018a2f5f053deb47bd72a76ee62fb312d9c0e67c33a83aec6" }; const canonicalSmokeJobName = "PR Full-Stack Smoke (runtime-required=true)"; const workflowPath = ".github/workflows/runtime-images.yml"; diff --git a/design/architecture/microservices/entity-management-service/api-contracts.md b/design/architecture/microservices/entity-management-service/api-contracts.md index 569acfa1af..6330e412ed 100644 --- a/design/architecture/microservices/entity-management-service/api-contracts.md +++ b/design/architecture/microservices/entity-management-service/api-contracts.md @@ -219,6 +219,8 @@ The target `ListRoomEntities` request carries the same `CausalReadFence` as Worl After that protocol exists, Entity Management serves the same region/scope/epoch and returns that proof, a scoped `servedThroughTickId`, and an opaque Entity component version. That returned version follows the [Identifier Glossary causal-read contract](../../system-architecture-identifier-glossary.md#cross-service-causal-read-fence-identity): Entity advances it atomically with relevant durable containment-owner commits and returns the stored version on matching replay/no-op. Game Logic accepts the participant when the returned region/scope/epoch matches and `servedThroughTickId >=` the requested `committedTickId`; a behind-floor or mixed tenant, game instance, region, room, or epoch response is rejected or retried. Opaque component versions are not directly compared. Game Logic validates the served-through proof, then composes only the requested floor plus the World and Entity component versions in the room-view identity and returns that identity with `LookResult` so Game Session can retain its transcript rendering/cache behavior; it does not claim an exact cross-database historical snapshot. +The protected `RunOwnedFixtureLookEntityService/ReadRunOwnedFixtureGround` read is restricted to the pre-v1 run-owned Compose fixture and the authenticated Game Logic workload. Entity correlates the exact active World proof with the mounted fixture receipt and verifies that the canonical game instance has no persisted ground-holder data in the current owner snapshot. Populated or unqualified scopes are held. Entity qualifies fixture room contents using the canonical game instance UUID. + Room-entity data is derived from runtime entity state plus authoritative world location. Ground items are discovered by querying items contained by the synthetic room-ground container for the target `RoomInstanceRef`. Characters and NPCs are included when their current location (owned by World Management) matches the target `RoomInstanceRef`: - Game Session obtains the complete causal floor, including `regionId`, from durable region commit authority before invoking `ResolveLook`; Game Logic propagates that floor unchanged to `ListRoomEntities`. The target request/response evolution must carry enough information for Entity Management to prove service of that region/scope/epoch floor; the current proto/request path does not yet carry the floor or served-through proof and does not claim this behavior complete. diff --git a/design/architecture/microservices/game-logic-service/api-contracts.md b/design/architecture/microservices/game-logic-service/api-contracts.md index 7d796d48a0..58ee718b98 100644 --- a/design/architecture/microservices/game-logic-service/api-contracts.md +++ b/design/architecture/microservices/game-logic-service/api-contracts.md @@ -129,6 +129,8 @@ grpcurl -plaintext -d '{"tenant_id":"demo","session_id":"demo","command":"look"} ## LOOK Aggregation and Formatting +The protected `RunOwnedFixtureLookService/ResolveRunOwnedFixtureLook` read serves the run-owned starter-room view for an already admitted Game Session caller. It combines the exact current World snapshot with Entity's qualified empty-ground read, checks the World response again, and returns the ordinary structured `LookResult`. The scope markers identify the fixture data. The target causal-floor contract below governs durable runtime reads. + - `ResolveLook` orchestrates World Management and Entity Management: World provides room topology, ambient state, and the authoritative occupant set for the target room or instance, while Entity enriches those caller-supplied occupant references with live entity and ground-item display data to build a deterministic `LookResult` that Game Session renders for clients. - In the target causal-read path, Game Session allocates the complete `CausalReadFence` from durable region commit authority before invoking `ResolveLook`. Its runtime fence identity is at least `{tenantId, gameInstanceId, regionId, roomInstanceId, regionEpoch, committedTickId}`. `playableStateNamespaceId` and `playableStateScope` may remain broader validated request/admission context, but they are not part of the runtime fence identity. Game Logic propagates the fence unchanged to World and Entity and forwards the validated preferred locale unchanged to World Management for localized room snapshot resolution. World Management owns stored-variant selection; fallback and provider rules remain owned by [Input, Output, and Presentation](../../system-architecture-input-output-and-presentation.md#localization-and-translation) and [ADR 0136](../../decisions/adr-0136-future-compatible-localization-boundary.md), not this service. Game Logic accepts only participant proofs matching the requested fence scope and epoch, with `servedThroughTickId >= requestedFloor` (the committed-tick floor), and requires each participant's own opaque component version. It rejects or retries behind-floor, missing-version, or mixed-region/scope/epoch responses. Component versions are not globally comparable numeric values: equality is not required, numeric skew is not evaluated, and the floor/epoch proof is the correctness fence. The floor and composite-identity details remain owned by the [Identifier Glossary](../../system-architecture-identifier-glossary.md#cross-service-causal-read-fence-identity) and [ADR 0059](../../decisions/adr-0059-causal-floor-cross-service-presentation-reads.md). The current `ResolveLook` request/proto path remains floor-free, so this propagation and proof are target behavior rather than current implementation. - The target-state `LookResult` should stay explicitly sectioned rather than collapsing everything into one mixed list. At minimum it should preserve distinct sections for room/world snapshot data, exits, visible occupants, visible room-ground items from the room-attached container, and later optional overlays such as combat, hazards, or ambient scripted notices. diff --git a/design/architecture/microservices/world-management-service/api-contracts.md b/design/architecture/microservices/world-management-service/api-contracts.md index 602fba97af..595eda2b9a 100644 --- a/design/architecture/microservices/world-management-service/api-contracts.md +++ b/design/architecture/microservices/world-management-service/api-contracts.md @@ -34,6 +34,7 @@ Canonical source intake and Version association revalidate the fixed Game Sessio - `GetRoom` – retrieves room data including exits and environmental effects through `RoomInstanceRef`. - `GetRoomSnapshot` – returns a minimal, LOOK-focused view scoped by `RoomInstanceRef`. +- `WorldCanonicalInstanceLifecycleReadService.ReadRunOwnedFixtureStartRoom` reads the World-allocated starter room for the exact ACTIVE run-owned fixture. The same-namespace Game Session workload presents the complete lifecycle selector over mTLS. World validates the retained fixture association and reads the room mapping and lifecycle in one owner snapshot. The reply carries the fixture lifecycle evidence and World room key. Actor placement and player admission remain separate owner operations. - `ListRoomOccupants` – **target state:** returns the authoritative typed occupant list for actors in a room, scoped by `RoomInstanceRef`. The current LOOK path is fixture-backed and has no World-owned location/occupancy persistence or authoritative read/write surface; it must not be treated as gameplay occupancy truth. - `ApplyRoomAmbientStatePatch` – applies a typed ambient fact patch to the target runtime scope under expected epoch/version preconditions and an operation/aggregate/request-digest-bound guard derived from the root `EffectId`; matching replay returns the durable prior result and a conflicting identity or payload fails closed. - `GetDraftDesignDigest` – returns the publish-gating digest for Draft world templates using the typed scope request `GetDraftDesignDigestRequest { tenantId, scope: oneof { versionId, scriptPatchVersion } }`. World Management supports `versionId` scope only and must return `UNSUPPORTED_SCOPE` for `scriptPatchVersion`. @@ -219,6 +220,8 @@ This is **as-of World-owner catalog evidence only**. It selects ADR 0137's permi ## LOOK Snapshot Contract +The run-owned Compose fixture can use the protected `RunOwnedFixtureLookWorldService/ReadRunOwnedFixtureLookRoom` read. World requires the authenticated same-namespace Game Logic workload and the exact ACTIVE fixture lifecycle selector. In one owner snapshot it resolves the retained physical starter-room mapping, checks the requested room key, verifies that no World-owned character location is present there, and reads the existing scoped room snapshot. The returned tenant and game instance are canonical UUIDs. The returned scope marker identifies the fixture snapshot. The target causal-floor contract below governs durable runtime reads. This fixture read is held for populated rooms and requires the pre-v1 waiver. + `GetRoomSnapshot` is the canonical endpoint feeding Game Logic's `ResolveLook`. The current and target fence contracts are intentionally separate. ### Current room-snapshot contract diff --git a/design/project-management/implementation-tracking/game-session-runtime-and-tick-coordination.md b/design/project-management/implementation-tracking/game-session-runtime-and-tick-coordination.md index 8dda305151..b9c0e93089 100644 --- a/design/project-management/implementation-tracking/game-session-runtime-and-tick-coordination.md +++ b/design/project-management/implementation-tracking/game-session-runtime-and-tick-coordination.md @@ -44,9 +44,13 @@ The prepared `CanonicalGameInstanceLaunchAssociationReadGrpcService` is a standa R82 passed the focused adapter unit/static/format gate in 54 seconds with eight fresh cases and zero failures/errors/skips. That historical run predates the two Spring storage-failure cases now present in the ten-case suite and does not qualify those later cases. These cases use a mocked repository; authenticated socket composition and genuine original issuer authority remain unproved. The initial R79 compile failed on a missing production-class import in the new test; that fixture issue is corrected without changing owner semantics. Production Game Design complete-launch reads remain denied, and this adapter supplies neither a genuine original StartSession producer nor current Account authority through a downstream commit. Its World consumer and recovery dependencies are recorded in [the World tracker](./world-runtime-and-movement.md#original-startsession-world-preparation-and-recovery). Deployment, ACTIVE lifecycle, admission, Entity placement and packaged playable closure remain held. The [restricted original-claim continuation contract](../../architecture/microservices/game-session-service/api-contracts.md#restricted-original-claim-evidence-continuation) and World’s existing creation/runtime contracts retain authority; earlier fixture and owner proofs below keep their original attribution. +### Canonical fixture first OPEN + +`RunOwnedFixtureFirstOpenCoordinator`, run by a scheduled driver under the run-owned fixture flag and the launch-association owner read, takes the fixture from its verified receipt to its first `OPEN`: STARTING launch, World prepare and activate, the intent and World initial-admission hold, a PENDING attempt with no Account protection, World verification, STARTING→RUNNING with an immutable `game_session_run_owned_fixture_runtime_completion` row, and the pointer commit. The fixture's policy-seal evidence digest takes the release attestation's place in intent, attempt and lifecycle bindings, and its terminal proof uses the V1006 framing with that digest in the protection slot. [V1070](../../../services/game-session-service/src/main/resources/db/migration/V1070__game_session_run_owned_fixture_initial_admission.sql) adds fixture branches to the intent/attempt, evidence, pointer-owner and tenant-scope guards; Human checks are unchanged. The numeric fixture bootstrap is removed. Focused PostgreSQL proof: `GameSessionRunOwnedFixtureFirstOpenPostgresIntegrationTest`. Fixture ABORT, the World hold settlement read, runtime binding decisions and player admission remain open. + ### Canonical fixture launch owner stage -Source-first canonical preparation is isolated in `RunOwnedCanonicalLaunchPreparationOwner`. It validates the fixed capability and closed Game Design receipt, and its explicit `prepareFixedVerifiedFixtureLaunch()` call creates and independently reads the canonical fresh association, catalog, and `STARTING` launch. It has no scheduler. The fixed authenticated `GetRunOwnedFixtureLaunchAssociation` RPC reads only that canonical owner allocation and returns its retained source/policy evidence. The published `RunOwnedInitialAdmissionFixtureCoordinator` scheduled bootstrap and `GameInstanceServiceImpl` behavior remain unchanged pending coherent canonical adoption; the explicit source owner is not wired into that bootstrap. Focused source and retained-bootstrap checks are qualified below; they do not establish scheduled canonical allocation, canonical World/first-`OPEN`, or genuine player admission. +Source-first canonical preparation is isolated in `RunOwnedCanonicalLaunchPreparationOwner`. It validates the fixed capability and closed Game Design receipt, and its explicit `prepareFixedVerifiedFixtureLaunch()` call creates and independently reads the canonical fresh association, catalog, and `STARTING` launch. The scheduled `RunOwnedFixtureFirstOpenDriver` drives it through `RunOwnedFixtureFirstOpenCoordinator`. The fixed authenticated `GetRunOwnedFixtureLaunchAssociation` RPC reads only that canonical owner allocation and returns its retained source/policy evidence. The retired numeric fixture bootstrap is removed. Compose proof (#3474) committed the fixture's canonical first `OPEN`; genuine player admission remains open. The source-first reconstruction on the `29ba9330f80dd3f2682ab8574c7806be505ba4bb` working base passed 98 focused Game Session unit cases (eight explicit preparation-owner, thirteen retained coordinator, 68 GameInstance service, seven fixture association-read and two protected-interceptor cases). Its native receiving gate passed 32 fresh cases: four canonical launch and nine catalog PostgreSQL cases, two World TLS and three World PostgreSQL cases, and fourteen Game Design producer cases, all without failures, errors or skips. The TLS test uses controlled creation/source evidence with a real authenticated descriptor read; the World PostgreSQL test uses controlled upstream evidence and actual owner/CAS storage. The unchanged World unit scope contributes 33 passing cases from the preceding execution. Affected static checks pass, including the final TLS builder correction. Fresh source-built baseline and same-version restart both passed WebSocket and Telnet `WORLDS`/`LOGIN`/`PLAY`/`LOOK`, followed by successful original-capability teardown of the claimed Compose project. Because the packaged scripts force fixture mode off, the fresh source-built and same-version restart WebSocket/Telnet `WORLDS`/`LOGIN`/`PLAY`/`LOOK` results establish only ordinary default-off baseline behavior, not the enabled fixture coordinator or canonical admission; canonical player-flow closure remains open. Earlier failed receipt-constructor, operation-ID and test-format gates remain recorded separately. @@ -60,7 +64,7 @@ The source-first receiving merge `96ca0b8ac07946969a13be659cf65af101e82c41` on p The dependency-readiness child also supplies the actual random-port Game Logic HTTP readiness URL to the shared cross-service stack, before caller-specific overrides. Its initial source omitted this test producer, leaving the container-DNS default in a localhost harness; the inherited TCP Proxy CI job failed while waiting for Game Session readiness. The corrected local inputs on parent `7ab19d077f021b044b2d45409d892324c6204a48` freshly pass all 14 `TelnetGatewayGameSessionAccountCrossServiceIntegrationTest` cases with zero failures, errors or skips, including traffic-admission readiness, plus test-fixture Checkstyle, SpotBugs and formatting. The cloud job selected 17 total cases; this focused local result does not relabel the other three as freshly executed. The nested Game Logic restart also preserves its actual HTTP and gRPC ports, so the configured readiness destination remains valid. Ten focused WebSocket cross-service cases freshly pass with zero failures, errors or skips, including unchanged persisted LOOK behavior, HTTP-port identity and both service readiness endpoints after restart; fixture/cross-service static checks and formatting pass. This is controlled legacy-flow fixture proof, not deployed recovery or canonical player authority. Controlled nested services and Account/World/Entity fixtures qualify the stated cross-service behavior, not genuine owner custody, protected activation or complete playable closure. -The earlier #3151 full-stack smoke rejected the numeric-only launch before fixture setup and ended with `SESSION_NOT_FOUND`; it remains the baseline failure, not proof of the current source-first candidate. The source-first owner consumes the closed run/project-bound Game Design receipt with actual fresh creation and source evidence, all four immutable launch snapshots (release bundle, artifact state, version state, and persisted launch descriptor), and the fixture policy seal. It pins the exact receipt across reads and binds canonical preparation to the registered source. Game Session obtains its typed fixture carrier only through the trusted data-package parser; `RunOwnedCanonicalLaunchPreparationOwner` exposes `createVerifiedFixtureStartingLaunch` plus independent `readVerifiedFixtureLaunch` only through explicit preparation, with no scheduler. The new `GetRunOwnedFixtureLaunchAssociation` RPC is read-only and reads the canonical repository. The explicit owner is not wired into the retained published `RunOwnedInitialAdmissionFixtureCoordinator` bootstrap or existing `GameInstanceServiceImpl` behavior. This path has no descriptor-resolution or preflight phase and invokes none of the three production Game Design release/version/artifact read RPCs. Generic `StartSession` cannot construct or select the fixture carrier. The receipt also carries the exact Game Session and World Management recipient pins; it does not grant production RPC authority. [Game Design API contracts](../../architecture/microservices/game-design-service/api-contracts.md#isolated-run-owned-authored-world-fixture-receipt) owns receipt production; the normative fixture boundary is [System Architecture: Testing Strategy](../../architecture/system-architecture-testing.md#run-owned-v1-launch-read-evidence), and [Game Session API contracts](../../architecture/microservices/game-session-service/api-contracts.md#implementation-status) records the local consumer consequence. +The earlier #3151 full-stack smoke rejected the numeric-only launch before fixture setup and ended with `SESSION_NOT_FOUND`; it remains the baseline failure, not proof of the current source-first candidate. The source-first owner consumes the closed run/project-bound Game Design receipt with actual fresh creation and source evidence, all four immutable launch snapshots (release bundle, artifact state, version state, and persisted launch descriptor), and the fixture policy seal. It pins the exact receipt across reads and binds canonical preparation to the registered source. Game Session obtains its typed fixture carrier only through the trusted data-package parser; `RunOwnedCanonicalLaunchPreparationOwner` exposes `createVerifiedFixtureStartingLaunch` plus independent `readVerifiedFixtureLaunch` only through explicit preparation, with no scheduler. The new `GetRunOwnedFixtureLaunchAssociation` RPC is read-only and reads the canonical repository. This path has no descriptor-resolution or preflight phase and invokes none of the three production Game Design release/version/artifact read RPCs. Generic `StartSession` cannot construct or select the fixture carrier. The receipt also carries the exact Game Session and World Management recipient pins; it does not grant production RPC authority. [Game Design API contracts](../../architecture/microservices/game-design-service/api-contracts.md#isolated-run-owned-authored-world-fixture-receipt) owns receipt production; the normative fixture boundary is [System Architecture: Testing Strategy](../../architecture/system-architecture-testing.md#run-owned-v1-launch-read-evidence), and [Game Session API contracts](../../architecture/microservices/game-session-service/api-contracts.md#implementation-status) records the local consumer consequence. Historical focused unit tests cover immutable replay, descriptor comparison, certificate-pin mismatch, malformed/unknown evidence, and bundle/template/source, artifact state/epoch, and version state/epoch mismatches; those results do not qualify the current source-first split. The new `RunOwnedCanonicalLaunchPreparationOwnerTest` and fixture association-read tests passed eight and seven cases respectively in the current focused gate described above. All fourteen [fixture capability cases](../../../services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/data/RunOwnedInitialAdmissionFixtureCapabilityTest.java) passed in the 2026-10-12 canonical Game Session full check; the whole unit task ran 2,080 cases with seventeen environment-dependent skips and no failures. This remains historical local unit proof. The prior `aaecdcc92e5de67047a7af80649b30ed773c91c1` revision rebuilt and booted the run-owned Compose images and passed WebSocket and Telnet `WORLDS` → `LOGIN` → `PLAY` → `LOOK` in [runtime run 38190595607](https://github.com/benhook1013/FireMUD/actions/runs/38190595607); that result belongs to that revision. Bounded source proof on `4896eaa8939cd4783106c9dbe0ef8e88515dd6ed` covers 2,207 unit and 39 cross-service cases. Current native PostgreSQL proof comprises 278 unique cases across the 277-case previous pass and the final 10-owner pass, with nine overlapping cases. The raw full integration attempt failed; only the qualified focused owner proof is established. The source-first reconstruction’s fresh and restart packaged `PLAY`/`LOOK` proof is qualified above; these historical native counts retain their original attribution. Source-only containment does not implement production producer handoffs or Account admission; both routed findings remain open and capability ratings are unchanged. @@ -80,7 +84,7 @@ Retained bootstrap correction: V8 recognizes only the unchanged, provenance-back Admission-catalog foundation status: Game Session pointer and audit rows now persist a separate positive `catalogRevision` and stable UUID `realmId`/`playableStateNamespaceId`; repository updates check both pointer version and catalog revision, and player-facing catalog/read projections fail closed on ambiguous tenant catalogs or incomplete identity. Runtime control-plane reads also reject persisted pointers with nonpositive `catalogRevision` or missing `realmId`/`playableStateNamespaceId` before constructing `GameInstanceRuntimeState`, returning `ADMISSION_POINTER_AUTHORITY_UNAVAILABLE` without partial pin/version metadata or pointer entries. Same-tenant world and realm selectors that collide under case-folding now fail closed in authority-backed catalogs and fixture catalogs while preserving the canonical routing tuple and revision. No-caller text `WORLDS`/`REALMS` and gRPC `ListGameplayWorlds`/`ListGameplayRealms` now share a public-production-only projection that retains the existing catalog health and public-realm cardinality checks; internal pointer health reads and explicit private admission/grant checks still see private realm authority. Caller-authorized private discovery remains unavailable until Account/caller integration. Focused regressions cover mixed-case collisions, single-selector resolution, private-only world omission, and private realm omission; validation remains pending. This is implemented whole-response fail-closed behavior, not successful migration or runtime proof. This does not implement a World-owner-validated initial bind, strict `JOIN`, or production activation. The configuration-driven pointer initializer validates configured seed shape without inserting pointer rows, and GS/WMS raw runtime seeding has been removed. Neither configured seeds nor legacy seed configuration provides World lifecycle proof. The extracted 35-path foundation passed a serialized `run-locked-gradle.sh` invocation of `:game-session-service:spotlessJavaApply :game-session-service:test :game-session-service:compileIntegrationTestJava linkCheck lintMarkdown --no-configuration-cache` on 2026-10-02. This executed unit proof and compiled PostgreSQL migration tests; no PostgreSQL/runtime execution proof is claimed. -Initial-admission owner boundary: Retained intent, pointer, audit and terminal storage remain separate from current execution. Fresh canonical Human prepare, commit and abort now refuse before intent, World hold, pointer and audit effects because authenticated Account protection acquisition/currentness and terminal settlement are unavailable. Canonical Game Session `STARTING` allocation and independent readback belong to the explicit `RunOwnedCanonicalLaunchPreparationOwner` call, which has no scheduler. The retained `RunOwnedInitialAdmissionFixtureCoordinator` remains the legacy scheduled bootstrap and uses the legacy World hold/admission path. Canonical World materialization/activation, hold and first `OPEN` remain open. Earlier whole-stack and terminal tests belong to their recorded revisions and do not qualify this current boundary. Current scoped proof is recorded above; no strict Account `JOIN`, production activation or generalized runtime-ID convergence is claimed. +Initial-admission owner boundary: Retained intent, pointer, audit and terminal storage remain separate from current execution. Fresh canonical Human prepare, commit and abort now refuse before intent, World hold, pointer and audit effects because authenticated Account protection acquisition/currentness and terminal settlement are unavailable. Canonical Game Session `STARTING` allocation and independent readback belong to `RunOwnedCanonicalLaunchPreparationOwner`; the scheduled `RunOwnedFixtureFirstOpenCoordinator` then drives canonical World activation, hold and first `OPEN` for the run-owned fixture only. Earlier whole-stack and terminal tests belong to their recorded revisions and do not qualify this current boundary. Current scoped proof is recorded above; no strict Account `JOIN`, production activation or generalized runtime-ID convergence is claimed. The authenticated internal `EnqueueAutomationCommandIfAbsent` and `ScheduleRemoteFollowup` receiving APIs currently fail closed with `FAILED_PRECONDITION` / `automation_admission_receiver_fence_unavailable` before command, coordinator, follow-up, or queue mutation. Ordinary gameplay APIs are unchanged. [GameSessionControlPlaneGrpcServiceTest](../../../services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/service/impl/GameSessionControlPlaneGrpcServiceTest.java) covers the receiving-boundary gate; lower-level admission tests do not prove durable receiver-epoch projection or the cross-service pause-versus-handoff race. The gate and remaining successor proof are recorded in the [Game Session API contract](../../architecture/microservices/game-session-service/api-contracts.md#implementation-status). @@ -113,7 +117,7 @@ These links add decision provenance only; they do not upgrade any Game Session i | Capability | Implementation | Verification | Design | Implementation anchors | Proof anchors | Secondary handoffs | Gap or decision | | --- | --- | --- | --- | --- | --- | --- | --- | -| `GR-1.1` Session front-end and execution routing | `partial`: WebSocket handshake/session bootstrap, protocol parsing, normalized routing, takeover-safe transport registration, and ordinary-gameplay local/remote admission are live; authenticated Automation receiver admission remains gated before mutation, and lease-owner forwarding for independently partitioned regions is not. Its initial-admission owner sub-boundary contributes to `AR-3.1`: durable catalog, retained intent storage, and retained pointer/audit components plus typed owner-proof reads are wired locally; retained intent storage does not establish current fresh reservation wiring. The source-first canonical owner exposes an explicit canonical `STARTING` create/readback path; its focused owner and association-read tests have the earlier qualified results recorded below, but it is not wired into the retained scheduled bootstrap. The published fixture bootstrap remains in place. Fresh canonical Human prepare/commit/abort refuse before effects pending Account protection, while canonical World materialization/activation and first `OPEN` remain unproved. Historical original-owner evidence reads are read-only. These preparations remain inactive and grant no player-admission authority; general `StartSession` retry integration is not claimed. | `proven` for front-door routing through [GameSessionWebSocketHandlerTest](../../../services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/websocket/GameSessionWebSocketHandlerTest.java), [GameSessionWebSocketHandlerIntegrationTest](../../../services/game-session-service/src/test/java/integration/net/firedevops/firemud/gamesession/websocket/GameSessionWebSocketHandlerIntegrationTest.java), [GameSessionWebSocketHandshakeInterceptorTest](../../../services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/websocket/GameSessionWebSocketHandshakeInterceptorTest.java), [SessionRoutingNormalizationServiceTest](../../../services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/service/SessionRoutingNormalizationServiceTest.java), and [GameSessionGrpcServiceTest](../../../services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/service/impl/GameSessionGrpcServiceTest.java). The owner-proof producer is covered by [CanonicalInitialAdmissionOwnerReadGrpcServiceTest](../../../services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/service/impl/CanonicalInitialAdmissionOwnerReadGrpcServiceTest.java). The historical original-owner producer and caller guard are exercised by [HistoricalOriginalStartSessionOwnerEvidenceReadGrpcServiceTest](../../../services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/service/impl/HistoricalOriginalStartSessionOwnerEvidenceReadGrpcServiceTest.java) and [HistoricalOriginalStartSessionOwnerEvidenceReadWorkloadGuardTest](../../../services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/service/impl/HistoricalOriginalStartSessionOwnerEvidenceReadWorkloadGuardTest.java). The current Human bind and abort refusal boundary is covered by [DatabaseCanonicalInitialAdmissionServiceTest](../../../services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/service/impl/DatabaseCanonicalInitialAdmissionServiceTest.java): both refuse before intent, World hold, pointer, or audit effects; this unit proof does not establish a current Human commit or durable terminal settlement. Incomplete Human preparation denial before intent reservation or World acquisition is separately covered by [CanonicalInitialAdmissionIntentRepositoryIntegrationTest](../../../services/game-session-service/src/test/java/integration/net/firedevops/firemud/gamesession/repository/CanonicalInitialAdmissionIntentRepositoryIntegrationTest.java), `incompleteHumanPreparationDeniesBeforeIntentReservationOrWorldAcquire`. Retained attempt, pointer, audit, and history preservation/readback are covered separately by [CanonicalInitialAdmissionRepositoryIntegrationTest](../../../services/game-session-service/src/test/java/integration/net/firedevops/firemud/gamesession/repository/CanonicalInitialAdmissionRepositoryIntegrationTest.java); that retained-storage proof does not establish a successful current Human commit or abort. The source-first explicit canonical preparation and read path has focused test sources in [RunOwnedCanonicalLaunchPreparationOwnerTest](../../../services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/data/RunOwnedCanonicalLaunchPreparationOwnerTest.java) and [GameSessionFixtureLaunchAssociationReadGrpcServiceTest](../../../services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/service/impl/GameSessionFixtureLaunchAssociationReadGrpcServiceTest.java); their eight and seven cases passed on the source-first reconstruction based on `29ba9330f80dd3f2682ab8574c7806be505ba4bb`, as attributed above; they were not rerun on this documentation head and do not establish scheduled canonical preparation, World materialization, or first-`OPEN`. Historical bootstrap tests remain in [RunOwnedInitialAdmissionFixtureCoordinatorTest](../../../services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/data/RunOwnedInitialAdmissionFixtureCoordinatorTest.java), while earlier repository persistence proof is in [GameSessionRunOwnedCanonicalLaunchRepositoryPostgresIntegrationTest](../../../services/game-session-service/src/test/java/integration/net/firedevops/firemud/gamesession/repository/GameSessionRunOwnedCanonicalLaunchRepositoryPostgresIntegrationTest.java). Historical exact-head [Validation run 38049505627](https://github.com/benhook1013/FireMUD/actions/runs/38049505627) on `efcd23e428393e71d10eb406838cee030d283cf6` executed 2,054 unit, 234 integration, and 39 cross-service cases; those 2,327 passing cases predate the current Human refusal boundary. The current scoped [Validation run 38496689054](https://github.com/benhook1013/FireMUD/actions/runs/38496689054) is for exact revision `e9f026aa49bb49c7635abd0055febf520aa18321`, not the whole current HEAD; it passed 2,202 unit, 267 integration, and 39 cross-service cases. Cross-service PostgreSQL race/restart proof and live Compose execution remain unestablished. | [Game Session API contracts](../../architecture/microservices/game-session-service/api-contracts.md); [Game Session initial-admission contract](../../architecture/microservices/game-session-service/api-contracts.md#initial-admission-bind); [World initial-admission bind hold](../../architecture/microservices/world-management-service/api-contracts.md#initial-admission-bind-hold-contract); [Multi-Tenancy realm-catalog and admission-pointer contract](../../architecture/system-architecture-multi-tenancy.md#realm-catalog-and-admission-pointer-contract); [Game Session runtime/data](../../architecture/microservices/game-session-service/runtime-and-data.md); [reconnection](../../architecture/system-architecture-reconnection.md); [run-owned player-flow smoke boundary](../../architecture/system-architecture-testing.md#player-flow-smoke-and-reset-boundaries) | [WebSocket handler](../../../services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/websocket/GameSessionWebSocketHandler.java); [handshake interceptor](../../../services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/websocket/GameSessionWebSocketHandshakeInterceptor.java); [session routing normalization](../../../services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/service/SessionRoutingNormalizationService.java); [Game Session gRPC](../../../services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/service/impl/GameSessionGrpcService.java); [DatabaseInitialAdmissionBindOwnerService.java](../../../services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/service/impl/DatabaseInitialAdmissionBindOwnerService.java); [DatabaseCanonicalInitialAdmissionService.java](../../../services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/service/impl/DatabaseCanonicalInitialAdmissionService.java); [CanonicalInitialAdmissionIntentRepository.java](../../../services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/repository/CanonicalInitialAdmissionIntentRepository.java); [CanonicalInitialAdmissionOwnerReadGrpcService.java](../../../services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/service/impl/CanonicalInitialAdmissionOwnerReadGrpcService.java); [CanonicalInitialAdmissionOwnerReadWorkloadGuard.java](../../../services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/service/impl/CanonicalInitialAdmissionOwnerReadWorkloadGuard.java); [canonical initial-admission owner-proof RPC](../../../protos/game-session/v1/game_session_service.proto); [HistoricalOriginalStartSessionOwnerEvidenceReadGrpcService.java](../../../services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/service/impl/HistoricalOriginalStartSessionOwnerEvidenceReadGrpcService.java); [RunOwnedCanonicalLaunchPreparationOwner.java](../../../services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/data/RunOwnedCanonicalLaunchPreparationOwner.java); [published bootstrap coordinator](../../../services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/data/RunOwnedInitialAdmissionFixtureCoordinator.java) | [CanonicalInitialAdmissionOwnerReadGrpcServiceTest.java](../../../services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/service/impl/CanonicalInitialAdmissionOwnerReadGrpcServiceTest.java); [HistoricalOriginalStartSessionOwnerEvidenceReadGrpcServiceTest.java](../../../services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/service/impl/HistoricalOriginalStartSessionOwnerEvidenceReadGrpcServiceTest.java); [HistoricalOriginalStartSessionOwnerEvidenceReadWorkloadGuardTest.java](../../../services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/service/impl/HistoricalOriginalStartSessionOwnerEvidenceReadWorkloadGuardTest.java); [InitialAdmissionBindOwnerReadTest.java](../../../services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/service/impl/InitialAdmissionBindOwnerReadTest.java); [DatabaseCanonicalInitialAdmissionServiceTest.java](../../../services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/service/impl/DatabaseCanonicalInitialAdmissionServiceTest.java); [CanonicalInitialAdmissionRepositoryIntegrationTest.java](../../../services/game-session-service/src/test/java/integration/net/firedevops/firemud/gamesession/repository/CanonicalInitialAdmissionRepositoryIntegrationTest.java); [CanonicalInitialAdmissionIntentRepositoryIntegrationTest](../../../services/game-session-service/src/test/java/integration/net/firedevops/firemud/gamesession/repository/CanonicalInitialAdmissionIntentRepositoryIntegrationTest.java); [CanonicalGameplayInitialAdmissionIntentRequestIdMigrationIntegrationTest](../../../services/game-session-service/src/test/java/integration/net/firedevops/firemud/gamesession/repository/CanonicalGameplayInitialAdmissionIntentRequestIdMigrationIntegrationTest.java) | `AR-3.1` runtime lifecycle in [Game Authoring](./game-authoring-publishing-and-activation.md); `GR-2.1` World hold and termination fence in the [World runtime tracker](./world-runtime-and-movement.md); `GR-1.3` ownership/fencing in this tracker; `AS-1.5` handoff in [Automation runtime tracker](./automation-and-scheduler-runtime.md); gateway/TCP edge behavior remains a secondary handoff | The initial-admission fixture does not complete the strict Account `JOIN` gate, production activation, or generalized runtime-ID migration. General `StartSession` retry integration, cross-service PostgreSQL race/restart proof, and live Compose execution remain open; ambiguous outcomes continue to fence World termination. The owner boundary is game-instance scoped and does not implement independently partitioned-region forwarding. | +| `GR-1.1` Session front-end and execution routing | `partial`: WebSocket handshake/session bootstrap, protocol parsing, normalized routing, takeover-safe transport registration, and ordinary-gameplay local/remote admission are live; authenticated Automation receiver admission remains gated before mutation, and lease-owner forwarding for independently partitioned regions is not. Its initial-admission owner sub-boundary contributes to `AR-3.1`: durable catalog, retained intent storage, and retained pointer/audit components plus typed owner-proof reads are wired locally; retained intent storage does not establish current fresh reservation wiring. The source-first canonical owner exposes an explicit canonical `STARTING` create/readback path; its focused owner and association-read tests have the earlier qualified results recorded below, but it is not wired into the retained scheduled bootstrap. The published fixture bootstrap remains in place. Fresh canonical Human prepare/commit/abort refuse before effects pending Account protection, while canonical World materialization/activation and first `OPEN` remain unproved. Historical original-owner evidence reads are read-only. These preparations remain inactive and grant no player-admission authority; general `StartSession` retry integration is not claimed. | `proven` for front-door routing through [GameSessionWebSocketHandlerTest](../../../services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/websocket/GameSessionWebSocketHandlerTest.java), [GameSessionWebSocketHandlerIntegrationTest](../../../services/game-session-service/src/test/java/integration/net/firedevops/firemud/gamesession/websocket/GameSessionWebSocketHandlerIntegrationTest.java), [GameSessionWebSocketHandshakeInterceptorTest](../../../services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/websocket/GameSessionWebSocketHandshakeInterceptorTest.java), [SessionRoutingNormalizationServiceTest](../../../services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/service/SessionRoutingNormalizationServiceTest.java), and [GameSessionGrpcServiceTest](../../../services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/service/impl/GameSessionGrpcServiceTest.java). The owner-proof producer is covered by [CanonicalInitialAdmissionOwnerReadGrpcServiceTest](../../../services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/service/impl/CanonicalInitialAdmissionOwnerReadGrpcServiceTest.java). The historical original-owner producer and caller guard are exercised by [HistoricalOriginalStartSessionOwnerEvidenceReadGrpcServiceTest](../../../services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/service/impl/HistoricalOriginalStartSessionOwnerEvidenceReadGrpcServiceTest.java) and [HistoricalOriginalStartSessionOwnerEvidenceReadWorkloadGuardTest](../../../services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/service/impl/HistoricalOriginalStartSessionOwnerEvidenceReadWorkloadGuardTest.java). The current Human bind and abort refusal boundary is covered by [DatabaseCanonicalInitialAdmissionServiceTest](../../../services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/service/impl/DatabaseCanonicalInitialAdmissionServiceTest.java): both refuse before intent, World hold, pointer, or audit effects; this unit proof does not establish a current Human commit or durable terminal settlement. Incomplete Human preparation denial before intent reservation or World acquisition is separately covered by [CanonicalInitialAdmissionIntentRepositoryIntegrationTest](../../../services/game-session-service/src/test/java/integration/net/firedevops/firemud/gamesession/repository/CanonicalInitialAdmissionIntentRepositoryIntegrationTest.java), `incompleteHumanPreparationDeniesBeforeIntentReservationOrWorldAcquire`. Retained attempt, pointer, audit, and history preservation/readback are covered separately by [CanonicalInitialAdmissionRepositoryIntegrationTest](../../../services/game-session-service/src/test/java/integration/net/firedevops/firemud/gamesession/repository/CanonicalInitialAdmissionRepositoryIntegrationTest.java); that retained-storage proof does not establish a successful current Human commit or abort. The source-first explicit canonical preparation and read path has focused test sources in [RunOwnedCanonicalLaunchPreparationOwnerTest](../../../services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/data/RunOwnedCanonicalLaunchPreparationOwnerTest.java) and [GameSessionFixtureLaunchAssociationReadGrpcServiceTest](../../../services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/service/impl/GameSessionFixtureLaunchAssociationReadGrpcServiceTest.java); their eight and seven cases passed on the source-first reconstruction based on `29ba9330f80dd3f2682ab8574c7806be505ba4bb`, as attributed above; they were not rerun on this documentation head and do not establish scheduled canonical preparation, World materialization, or first-`OPEN`. Historical bootstrap tests remain in, while earlier repository persistence proof is in [GameSessionRunOwnedCanonicalLaunchRepositoryPostgresIntegrationTest](../../../services/game-session-service/src/test/java/integration/net/firedevops/firemud/gamesession/repository/GameSessionRunOwnedCanonicalLaunchRepositoryPostgresIntegrationTest.java). Historical exact-head [Validation run 38049505627](https://github.com/benhook1013/FireMUD/actions/runs/38049505627) on `efcd23e428393e71d10eb406838cee030d283cf6` executed 2,054 unit, 234 integration, and 39 cross-service cases; those 2,327 passing cases predate the current Human refusal boundary. The current scoped [Validation run 38496689054](https://github.com/benhook1013/FireMUD/actions/runs/38496689054) is for exact revision `e9f026aa49bb49c7635abd0055febf520aa18321`, not the whole current HEAD; it passed 2,202 unit, 267 integration, and 39 cross-service cases. Cross-service PostgreSQL race/restart proof and live Compose execution remain unestablished. | [Game Session API contracts](../../architecture/microservices/game-session-service/api-contracts.md); [Game Session initial-admission contract](../../architecture/microservices/game-session-service/api-contracts.md#initial-admission-bind); [World initial-admission bind hold](../../architecture/microservices/world-management-service/api-contracts.md#initial-admission-bind-hold-contract); [Multi-Tenancy realm-catalog and admission-pointer contract](../../architecture/system-architecture-multi-tenancy.md#realm-catalog-and-admission-pointer-contract); [Game Session runtime/data](../../architecture/microservices/game-session-service/runtime-and-data.md); [reconnection](../../architecture/system-architecture-reconnection.md); [run-owned player-flow smoke boundary](../../architecture/system-architecture-testing.md#player-flow-smoke-and-reset-boundaries) | [WebSocket handler](../../../services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/websocket/GameSessionWebSocketHandler.java); [handshake interceptor](../../../services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/websocket/GameSessionWebSocketHandshakeInterceptor.java); [session routing normalization](../../../services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/service/SessionRoutingNormalizationService.java); [Game Session gRPC](../../../services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/service/impl/GameSessionGrpcService.java); [DatabaseInitialAdmissionBindOwnerService.java](../../../services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/service/impl/DatabaseInitialAdmissionBindOwnerService.java); [DatabaseCanonicalInitialAdmissionService.java](../../../services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/service/impl/DatabaseCanonicalInitialAdmissionService.java); [CanonicalInitialAdmissionIntentRepository.java](../../../services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/repository/CanonicalInitialAdmissionIntentRepository.java); [CanonicalInitialAdmissionOwnerReadGrpcService.java](../../../services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/service/impl/CanonicalInitialAdmissionOwnerReadGrpcService.java); [CanonicalInitialAdmissionOwnerReadWorkloadGuard.java](../../../services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/service/impl/CanonicalInitialAdmissionOwnerReadWorkloadGuard.java); [canonical initial-admission owner-proof RPC](../../../protos/game-session/v1/game_session_service.proto); [HistoricalOriginalStartSessionOwnerEvidenceReadGrpcService.java](../../../services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/service/impl/HistoricalOriginalStartSessionOwnerEvidenceReadGrpcService.java); [RunOwnedCanonicalLaunchPreparationOwner.java](../../../services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/data/RunOwnedCanonicalLaunchPreparationOwner.java); [fixture first-OPEN coordinator](../../../services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/data/RunOwnedFixtureFirstOpenCoordinator.java) | [CanonicalInitialAdmissionOwnerReadGrpcServiceTest.java](../../../services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/service/impl/CanonicalInitialAdmissionOwnerReadGrpcServiceTest.java); [HistoricalOriginalStartSessionOwnerEvidenceReadGrpcServiceTest.java](../../../services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/service/impl/HistoricalOriginalStartSessionOwnerEvidenceReadGrpcServiceTest.java); [HistoricalOriginalStartSessionOwnerEvidenceReadWorkloadGuardTest.java](../../../services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/service/impl/HistoricalOriginalStartSessionOwnerEvidenceReadWorkloadGuardTest.java); [InitialAdmissionBindOwnerReadTest.java](../../../services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/service/impl/InitialAdmissionBindOwnerReadTest.java); [DatabaseCanonicalInitialAdmissionServiceTest.java](../../../services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/service/impl/DatabaseCanonicalInitialAdmissionServiceTest.java); [CanonicalInitialAdmissionRepositoryIntegrationTest.java](../../../services/game-session-service/src/test/java/integration/net/firedevops/firemud/gamesession/repository/CanonicalInitialAdmissionRepositoryIntegrationTest.java); [CanonicalInitialAdmissionIntentRepositoryIntegrationTest](../../../services/game-session-service/src/test/java/integration/net/firedevops/firemud/gamesession/repository/CanonicalInitialAdmissionIntentRepositoryIntegrationTest.java); [CanonicalGameplayInitialAdmissionIntentRequestIdMigrationIntegrationTest](../../../services/game-session-service/src/test/java/integration/net/firedevops/firemud/gamesession/repository/CanonicalGameplayInitialAdmissionIntentRequestIdMigrationIntegrationTest.java) | `AR-3.1` runtime lifecycle in [Game Authoring](./game-authoring-publishing-and-activation.md); `GR-2.1` World hold and termination fence in the [World runtime tracker](./world-runtime-and-movement.md); `GR-1.3` ownership/fencing in this tracker; `AS-1.5` handoff in [Automation runtime tracker](./automation-and-scheduler-runtime.md); gateway/TCP edge behavior remains a secondary handoff | The initial-admission fixture does not complete the strict Account `JOIN` gate, production activation, or generalized runtime-ID migration. General `StartSession` retry integration, cross-service PostgreSQL race/restart proof, and live Compose execution remain open; ambiguous outcomes continue to fence World termination. The owner boundary is game-instance scoped and does not implement independently partitioned-region forwarding. | | `GR-1.2` Tick timelines, action fairness, queues, and scheduling | `partial`: current bounded scheduler, per-entity queue selection, gameplay-command ordering (including timer/automation-origin work only after materialization as gameplay commands with retained provenance/order fields), durable batch/effect staging, pressure signals, and sealed selected-work manifests for gameplay commands are live; directly selected timer/retry/remote-follow-up source-claim manifests remain target-state; it still uses universal work-item selection and does not implement the accepted separate actor-action/passive-effect lane classification, phase budgets, or lane-preserving retry contract; the complete in-place command-status lifecycle accepted by [ADR 0016](../../architecture/decisions/adr-0016-canonical-gameplay-command-status-lifecycle.md) is not | `drift-found`: the shipped scheduler and queue/effect seams have focused proof, but lane/source classification, separate lane budgets, and passive/inbound non-actor-turn behavior are not proved; the accepted command-status lifecycle in [ADR 0016](../../architecture/decisions/adr-0016-canonical-gameplay-command-status-lifecycle.md) remains unimplemented and is not fully proved | [ticks](../../architecture/system-architecture-ticks.md); [tick concepts and invariants](../../architecture/system-architecture-tick-concepts-and-invariants.md); [tick execution flows](../../architecture/system-architecture-tick-execution-flows.md); [ADR 0016](../../architecture/decisions/adr-0016-canonical-gameplay-command-status-lifecycle.md) | [TickScheduler](../../../services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/service/impl/TickScheduler.java); [TickStagingService](../../../services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/service/impl/TickStagingService.java); [TickBatchExecutionService](../../../services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/service/impl/TickBatchExecutionService.java); [TickServiceImpl](../../../services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/service/impl/TickServiceImpl.java); [Game Session baseline schema](../../../services/game-session-service/src/main/resources/db/migration/V1__baseline.sql); [game-session-service.proto](../../../protos/game-session/v1/game_session_service.proto) | [TickSchedulerTest](../../../services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/service/impl/TickSchedulerTest.java); [TickStagingServiceTest](../../../services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/service/impl/TickStagingServiceTest.java); [TickBatchExecutionServiceTest](../../../services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/service/impl/TickBatchExecutionServiceTest.java); [TickServiceImplTest](../../../services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/service/impl/TickServiceImplTest.java) | `AS-1.4` timer progress and `AS-1.5` handoff in [Automation runtime tracker](./automation-and-scheduler-runtime.md); `GR-1.3` ownership in this tracker | Add the [ADR 0016](../../architecture/decisions/adr-0016-canonical-gameplay-command-status-lifecycle.md) acknowledgement dimensions, authoritative attempt history, bound-tick summary, convergence contract, persistence, and focused proof to `GetGameplayCommandStatus`; separately add TICK-01 source classification, lane/cost metadata, phase budgets, lane-preserving retry identity, and focused actor/passive scheduling proof; adaptive timing and true region-wide scheduling remain separate gaps. | | `GR-1.3` Region leases, fencing, and executor coordination | `partial`: durable runtime ownership, epoch/fence snapshots, pause/resume, stale-owner rejection/requeue, and current runtime-progress publication are live at the game-instance boundary; the TICK-02 Redis lease plus durable executor-fence install/revalidate handshake and true region takeover boundary remain target-state | `proven`: current tests cover fence/scope admission, tick progress, stale execution, and operator reads, but do not prove the TICK-02 lease/fence handshake or takeover reconciliation | [tick concepts and invariants](../../architecture/system-architecture-tick-concepts-and-invariants.md); [Game Session runtime/data](../../architecture/microservices/game-session-service/runtime-and-data.md); [tick failures and operations](../../architecture/system-architecture-tick-failures-and-operations.md) | [RuntimeRegionStatus](../../../services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/entity/RuntimeRegionStatus.java); [runtime ownership read](../../../services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/service/impl/GameSessionRuntimeControlPlaneReadService.java); [TickRuntimeProgressService](../../../services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/service/impl/TickRuntimeProgressService.java); [Game Session baseline schema](../../../services/game-session-service/src/main/resources/db/migration/V1__baseline.sql) | [TickServiceImplTest](../../../services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/service/impl/TickServiceImplTest.java); [TickRuntimeProgressServiceTest](../../../services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/service/impl/TickRuntimeProgressServiceTest.java); [AutomationGameplayCommandAdmissionSupportTest](../../../services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/service/impl/AutomationGameplayCommandAdmissionSupportTest.java) (lower-level helper proof only, not live end-to-end receiver proof); [GameSessionControlPlaneGrpcServiceTest](../../../services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/service/impl/GameSessionControlPlaneGrpcServiceTest.java) | `GR-1.1` front-end routing in this tracker; `AS-1.1` ingress and `AS-1.4` timers in [Automation runtime tracker](./automation-and-scheduler-runtime.md); Redis lease coordination is the shared infrastructure handoff | The current durable owner row and lease boundary are game-instance scoped. Add proof for Redis lease acquisition/loss before and after durable fence installation, same-token revalidation, stale-fence rejection, and takeover reconciliation; true region-partitioned leases, cluster scheduling, and front-end forwarding remain unimplemented. | | `GR-1.4` Runtime recovery, replay, and reconciliation | `partial`: durable command/batch/effect recovery, manifest-digest repair, stale-fence requeue, remote result reconciliation, and bounded restart/reset paths are live; startup recovery re-enqueues old accepted-but-unstaged commands under their existing identity and leaves them `ACCEPTED` when Redis, identity, eligibility, or a raced transition prevents safe materialization; queue/pending loss before durable batch materialization and recovery of `STAGED` batches/effects after Redis loss remain unimplemented; lane-preserving replay and the complete TICK-02 takeover reconciliation remain target-state follow-through | `drift-found`: focused unit recovery tests cover accepted-row re-drive, unchanged retryable state on uncertainty, serializer-free identity/payload-idempotent queue/pending behavior, remote reconciliation, and retryability on Redis/eligibility races, but do not provide combined PostgreSQL/real-Redis restart proof, lane/cost preservation, Redis-loss recovery of `STAGED` state, or the Redis lease plus durable-fence takeover handshake; the real-Redis serializer integration test is present but skipped when Docker is unavailable | [tick failures and operations](../../architecture/system-architecture-tick-failures-and-operations.md); [tick execution flows](../../architecture/system-architecture-tick-execution-flows.md); [reconnection](../../architecture/system-architecture-reconnection.md); [Game Session operations](../../architecture/microservices/game-session-service/operations.md); [ADR 0013](../../architecture/decisions/adr-0013-bounded-invisible-non-edge-restart-recovery.md) | [DatabaseGameplayCommandRecoveryService](../../../services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/service/impl/DatabaseGameplayCommandRecoveryService.java); [GameplayCommandRepository](../../../services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/repository/GameplayCommandRepository.java); [TickQueueControlService](../../../services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/service/impl/TickQueueControlService.java); [TickStagingService](../../../services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/service/impl/TickStagingService.java); [TickBatchExecutionService](../../../services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/service/impl/TickBatchExecutionService.java); [RemoteFollowupRuntimeServiceImpl](../../../services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/service/impl/RemoteFollowupRuntimeServiceImpl.java); [Game Session baseline schema](../../../services/game-session-service/src/main/resources/db/migration/V1__baseline.sql) | [DatabaseGameplayCommandRecoveryServiceTest](../../../services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/service/impl/DatabaseGameplayCommandRecoveryServiceTest.java); [TickQueueControlServiceTest](../../../services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/service/impl/TickQueueControlServiceTest.java); [TickQueueControlServiceRedisIntegrationTest](../../../services/game-session-service/src/test/java/integration/net/firedevops/firemud/gamesession/service/impl/TickQueueControlServiceRedisIntegrationTest.java); [AutomationGameplayCommandAdmissionSupportTest](../../../services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/service/impl/AutomationGameplayCommandAdmissionSupportTest.java) (lower-level helper proof only, not live end-to-end receiver proof); [TickStagingServiceTest](../../../services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/service/impl/TickStagingServiceTest.java); [TickBatchExecutionServiceTest](../../../services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/service/impl/TickBatchExecutionServiceTest.java); [RemoteFollowupRuntimeServiceImplTest](../../../services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/service/impl/RemoteFollowupRuntimeServiceImplTest.java); [RemoteFollowupDrainServiceImplTest](../../../services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/service/impl/RemoteFollowupDrainServiceImplTest.java); [DefaultDurableRemoteFollowupExecutionServiceTest](../../../services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/service/impl/DefaultDurableRemoteFollowupExecutionServiceTest.java) | `GR-1.2` queue/replay and `GR-1.3` fencing in this tracker; `AS-1.5` handoff in [Automation runtime tracker](./automation-and-scheduler-runtime.md); downstream domain services own effect application/reconciliation | Downstream effect ledgers and replay/idempotency consumers beyond the migrated command families, full non-edge restart recovery, broader payload/work-source recovery, and a durable replay/reconciliation controller for Redis-loss `STAGED` command/batch state remain; add focused proof for lane/cost preservation, current epoch/fence validation, old-fence takeover reconciliation, and broader payload/work-source recovery; ADR 0013 is accepted and owns the bounded invisible non-edge restart target. | 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 0bcb63d8de..ae946df241 100644 --- a/design/project-management/implementation-tracking/player-access-and-session.md +++ b/design/project-management/implementation-tracking/player-access-and-session.md @@ -25,14 +25,16 @@ Under ADR 0185 (no data carry-over before v1, proposed in #3459), Compose smoke | Game Session and Account LOGIN Coordination Redis accept plaintext `redis://` | TLS (`rediss://`) Coordination with peer verification | | Game Session initial LOGIN uses a process-local qualification lease | External Coordination qualification authority excluding reset, restore and promotion | | Compose Account JWT signer uses a stand-in Kubernetes API (`dev-tools/smoke/pre-v1-kube-api-standin.py`) and materializer (`dev-tools/smoke/pre-v1-jwt-materializer-standin.py`) | Deployed materializer writing a real Secret, the real cluster API and RBAC for the `jwt-jwks` ConfigMap and validator inventory | +| World runtime installation for the run-owned Compose fixture is read from a root-owned inventory file (`PreV1ComposeRuntimeInstallationSource`) | A deployed installation controller that holds the completed installation and its workload incarnations through each launch commit | | Account signer promotion uses self-attested validator readiness (`PreV1SelfAttestedReadinessDriver`) | A Pod-bound readiness receiver client and orchestrator that verifies each validator Pod's acceptance | +| The run-owned Compose fixture tenant is enrolled into Account from the Game Design receipt as a locator plus the authenticated `ResolveFreshTenantCreation` readback, with a provisioned demo entitlement (`RunOwnedFixtureDemoTenantEnrollmentDriver`) | The Account tenant-creation coordinator and an operator-provisioned entitlement for real tenants | | Direct-text PLAY runs on the existing direct LOGIN until the authenticated LOGIN, WORLDS, REALMS and JOIN receiver lands (stacked straight after UUID PLAY is green) | Deployed Account JWT signer materializer and public-JWKS API binding, protected Coordination Redis (TLS, ACL, AOF acknowledgement) and the external Coordination qualification authority, then PLAY moved onto the authenticated receiver | ### Direct-text scope and JOIN identifier cutover The canonical Account boundary requires non-nil UUID tenant and game-instance identifiers. The held Game Session scope target now takes those UUIDs from `CanonicalPlayableTarget`, and its Account client validates the same canonical shape. JOIN correlation retains exact tenant equality. The numeric transport session identifier remains an independent, bounded positive-long coordinate: its original bytes, including leading zeros, are preserved through scope issuance and JOIN rather than replaced by the proxy connection UUID. -Selected client-wire and Account receiver tests exercise these contracts separately, including malformed identifiers and mismatches. They are not an actual paired Game Session-to-Account RPC or deployed composition proof. The lobby remains unregistered; source custody, genuine cross-service scope/JOIN qualification and public admission remain unfinished. The observed backend PLAY `ENTITLEMENT_UNAVAILABLE` is a separate recorded failure. The temporary CI exception supplies neither successful JOIN/PLAY proof nor runtime activation. +Selected client-wire and Account receiver tests exercise these contracts separately, including malformed identifiers and mismatches. They are not an actual paired Game Session-to-Account RPC or deployed composition proof. The lobby, Account's canonical realm-scope owner and JOIN consumers (`AccountCanonicalRealmAdmissionConfiguration`) and Game Session's Account-only admission decision read (`CanonicalGameplayAdmissionDecisionReadConfiguration`) are now registered, and Account's PLAY receivers (entitlement read, admission lease, tenant capacity) are registered by `AccountGameplayAdmissionReceiversConfiguration`. Paid hosting sources are not composed there, so paid tenants fail closed. Runtime REALMS/JOIN proof and public admission remain unfinished (#3474). The observed backend PLAY `ENTITLEMENT_UNAVAILABLE` is a separate recorded failure. The temporary CI exception supplies neither successful JOIN/PLAY proof nor runtime activation. This is an intentionally breaking preproduction format cutover of the manually composed, currently unregistered lobby. No production rollback or migration compatibility is claimed. Numeric-era retained scope/JOIN bytes are not supported by the canonical UUID decoder; the existing SQL retention and exact-original identity guards remain unchanged. Repository inspection establishes no runtime registration and supplies no inventory of deployed rows. Existing-data verification belongs to future runtime wiring or activation, not a new merge gate or slicing requirement for this PR: before reusing any database populated by an earlier manual composition, establish whether numeric-era companion evidence exists. If it does, preserve that evidence and resolve its retention and recovery requirements before invoking the new owner against it; neither this cutover nor the temporary CI exception authorizes deletion, identity rewriting or retention bypass. Fresh component fixtures do not prove historical compatibility. diff --git a/design/project-management/implementation-tracking/world-runtime-and-movement.md b/design/project-management/implementation-tracking/world-runtime-and-movement.md index 95d73b39b5..f48ce298e3 100644 --- a/design/project-management/implementation-tracking/world-runtime-and-movement.md +++ b/design/project-management/implementation-tracking/world-runtime-and-movement.md @@ -194,6 +194,10 @@ Historical qualification before V1042–V1042.3: the local owner successor conta At that historical frontier, the 75-file default-order installation, installed 34→40→75 upgrade, schema-2 snapshot retention at that 75-file frontier, exact topology/manifest readback, rollback/races and reconstructed-owner retry passed physical execution. The GDS fixed read adapters were registered in a real managed annotation context with actual producer owners before serving their production handlers. Controlled test capabilities and PKI remained distinct from an actual claimed Compose deployment; complete packaged/Spring Boot fresh/restart proof remained open. Historical pre-1037 canonical Human schema-1 allocation retention was unconstructed because its genuine preparation/execution prerequisites were unavailable; no fake Account protection or disabled storage guard supplied that coverage. Historical guarded positive storage was explicitly pinned to 1007.1 and did not qualify current Account/APPLIED authority. Fixture bootstrap, activation, hold acquire/finalize, first OPEN prerequisites and initial placement stayed unavailable; no Entity or operational-region evidence was claimed. The [storage contract](../../architecture/microservices/world-management-service/runtime-and-data.md#fixed-fixture-preparing-owner) owns the local persistence consequence. All four genuine handoffs remain open. +### Fixed fixture activation + +The generic `PrepareWorldInstance` and `ActivatePreparedWorldInstance` RPCs dispatch to the canonical fixture owner when the run-owned fixture is enabled. Activation resolves the authenticated Game Session allocation to the retained association, verifies it inside a writable owner transaction and moves the World row once from its original PREPARING epoch to ACTIVE. [V1070](../../../services/world-management-service/src/main/resources/db/migration/V1070__world_run_owned_fixture_activation.sql) retains one immutable `world_run_owned_fixture_activation` row per instance and its storage guards admit only that exact CAS in the same transaction; bare SQL updates stay refused. Both prepare and activate freeze the current runtime installation's required owners first (Compose uses the pre-v1 inventory-file waiver in the [player access tracker](player-access-and-session.md#pre-v1-gate-waivers)). Focused PostgreSQL proof: `RunOwnedWorldFixedPresetResourcesPostgresIntegrationTest.fixtureActivationMovesOriginalPreparingEpochToActiveOnceAndReplaysExactly`. Fixture holds and first `OPEN` remain open. + ### Retained operational-region identity migration proof Donor proof at code/test source `08dc25f08d1fd0bdcadd416f77c17201d252685d` records one fresh native PostgreSQL case with zero failures, errors or skips. It seeds explicit predecessor-era World and Region rows at V1017, then migrates through V1018 and the current default using the owning World and Saga filesystem migrations. Every prior World and Region column and PostgreSQL row version remains unchanged, together with all prior Flyway history rows. The existing canonical Region UUID remains intact; operational Region identity and the later World realm/catalog fields stay unset. The original preparation function retains its OID and ACL through V1018 and the later private-implementation rename, while both current preparation functions keep PUBLIC execution closed. Later operational-identity and realm/catalog backfill attempts refuse without changing the complete retained rows or their row versions. diff --git a/dev-tools/smoke/pre-v1-signer-fixtures.py b/dev-tools/smoke/pre-v1-signer-fixtures.py index db9257ba11..8728a17789 100644 --- a/dev-tools/smoke/pre-v1-signer-fixtures.py +++ b/dev-tools/smoke/pre-v1-signer-fixtures.py @@ -276,6 +276,72 @@ def main(): "firemud-account-response-envelope-keyring-v1\n" f"active compose-1 {key()}\n" ) + # Pre-v1 waiver: the World runtime installation inventory the run-owned fixture freezes its + # launch owners against (PreV1ComposeRuntimeInstallationSource reads it read-only). + world = out / "world-runtime-installation" + world.mkdir(parents=True, exist_ok=True) + world_inventory = { + "schema": "firemud-runtime-installation-inventory/v1", + "artifactId": "8d6a7f0e-2f0c-4f5e-9a51-0c7d3c2e9b11", + "installationId": "1f3b9c4a-7e2d-4b8a-8f61-5d2e0a9c7b33", + "environment": "local-dev", + "generation": "pre-v1-compose-installation-v1", + "clusterUid": "compose", + "namespaceUid": "compose-dev", + "namespace": "dev", + "sourceCommit": "0" * 40, + "renderedManifestDigest": "sha256:" + sha256_hex(b"docker-compose.yml"), + "declarationsDigest": "sha256:" + sha256_hex(b"pre-v1-compose-declarations"), + "executor": { + "identity": "pre-v1-compose-fixtures/v1", + "versionDigest": "sha256:" + sha256_hex(b"pre-v1-signer-fixtures.py"), + }, + "inputBindings": { + "migrations": [], + "configurations": [], + "mountedResources": [], + "secretContracts": [], + "externalBindings": [], + }, + "members": [ + { + "workloadApiVersion": "v1", + "workloadKind": "Pod", + "workloadNamespace": "dev", + "workloadName": "world-management-service", + "containerKind": "APPLICATION", + "containerName": "world-management-service", + "image": "firemud/world-management-service@sha256:" + sha256_hex(b"compose-world"), + "ownerId": "world-management-service", + "ownership": "RUNTIME_OWNER", + "catalogSources": [ + { + "sourceId": "compose-world-sql", + "contract": "firemud/world/catalog/v1", + "epoch": "1", + "digest": "sha256:" + sha256_hex(b"compose-world-sql"), + } + ], + "families": [ + { + "familyId": "compose-world-state", + "catalogSourceId": "compose-world-sql", + "replacementClass": "S3", + "cleanupContract": { + field: f"firemud/world/{field}/v1" + for field in ("operation", "requestIdentity", "acknowledgement", "retention") + }, + } + ], + } + ], + } + inventory_path = world / "inventory.json" + if inventory_path.exists(): + inventory_path.unlink() + inventory_path.write_text(json.dumps(world_inventory, separators=(",", ":"))) + os.chmod(inventory_path, 0o444) + (out / "identity.json").write_text(json.dumps(identity, indent=2) + "\n") os.chmod(out, 0o755) diff --git a/dev-tools/smoke/run-owned-compose.sh b/dev-tools/smoke/run-owned-compose.sh index c2166394d8..17a2a9cf7c 100644 --- a/dev-tools/smoke/run-owned-compose.sh +++ b/dev-tools/smoke/run-owned-compose.sh @@ -470,7 +470,7 @@ expected = { "publicProductionRealm": True, "requiresCharacterSelection": False, "stateScope": "SHARED", - "characterCreationPolicy": "ALLOW_NEW", + "characterCreationPolicy": "PRESEEDED_ONLY", "gameSessionLeafSha256": game_session_leaf_sha256, "gameSessionUriSan": "spiffe://firemud/ns/dev/sa/game-session-service", "worldManagementLeafSha256": world_management_leaf_sha256, @@ -633,7 +633,7 @@ value = { "publicProductionRealm": True, "requiresCharacterSelection": False, "stateScope": "SHARED", - "characterCreationPolicy": "ALLOW_NEW", + "characterCreationPolicy": "PRESEEDED_ONLY", "gameSessionLeafSha256": game_session_leaf_sha256, "gameSessionUriSan": "spiffe://firemud/ns/dev/sa/game-session-service", "worldManagementLeafSha256": world_management_leaf_sha256, diff --git a/dev-tools/smoke/smoke_common.py b/dev-tools/smoke/smoke_common.py index bb8d22e4db..5fee14c107 100644 --- a/dev-tools/smoke/smoke_common.py +++ b/dev-tools/smoke/smoke_common.py @@ -343,6 +343,19 @@ def run_transport_session( return result +def websocket_fail_closed_play_steps(username, password, world, worlds_expect, login_expect): + """WebSocket steps until PLAY moves onto the canonical admission chain (#3481). + + The run-owned fixture is canonical-only, so the retired numeric WebSocket PLAY must stay + fail-closed after a successful LOGIN; LOOK is proven once PLAY admits through the chain. + """ + return [ + ("WORLDS", [worlds_expect], "WORLDS"), + (f"LOGIN {username} {password}", [login_expect], "LOGIN"), + (f"PLAY {world}", ["ERROR ENTITLEMENT_UNAVAILABLE"], "PLAY"), + ] + + def login_play_look_steps( username, password, diff --git a/dev-tools/tests/compose-grpc-mtls-contract.sh b/dev-tools/tests/compose-grpc-mtls-contract.sh index 1531e559b4..f8300b2560 100644 --- a/dev-tools/tests/compose-grpc-mtls-contract.sh +++ b/dev-tools/tests/compose-grpc-mtls-contract.sh @@ -270,7 +270,8 @@ for service in "${services[@]}"; do done identity_services=( - account-service game-session-service entity-management-service world-management-service game-design-service + account-service game-session-service entity-management-service world-management-service + game-design-service game-logic-service ) declare -A identity_fingerprints=() for service in "${identity_services[@]}"; do @@ -301,6 +302,7 @@ for service in ( "world-management-service", "game-session-service", "game-design-service", + "game-logic-service", "logging-admin-service", ): headers = [index for index, line in enumerate(lines) if line == f" {service}:"] @@ -367,7 +369,10 @@ fixture_keys = ( "FIREMUD_SMOKE_INITIAL_ADMISSION_CAPABILITY_PATH", "FIREMUD_SMOKE_AUTHORED_WORLD_SOURCE_RECEIPT_PATH", ) -fixture_services = ("game-design-service", "game-session-service", "world-management-service") +fixture_services = ( + "account-service", "entity-management-service", "game-design-service", + "game-session-service", "world-management-service", +) for service, block in service_blocks.items(): if service in fixture_services: for key in fixture_keys: @@ -408,7 +413,14 @@ for service, block in service_blocks.items(): assert any(line == f" target: {source_receipt_dir}" for line in block) assert any(line == " read_only: true" for line in block) else: - assert not any(any(key in line for key in fixture_keys) for line in block), service + activation = fixture_keys[2] + if service == "game-logic-service": + assert any(line.startswith(f" {activation}:") for line in block) + restricted_keys = ( + tuple(key for key in fixture_keys if key != activation) + if service == "game-logic-service" else fixture_keys + ) + assert not any(any(key in line for key in restricted_keys) for line in block), service assert not any(capability_path in line for line in block), service assert not any(source_receipt_dir in line for line in block), service assert not any(game_session_leaf_path in line for line in block), service @@ -514,7 +526,10 @@ app_names = { "game-session-service", "logging-admin-service", "social-groups-service", "tcp-proxy-service", "world-management-service", } -fixture_services = ("game-design-service", "game-session-service", "world-management-service") +fixture_services = ( + "account-service", "entity-management-service", "game-design-service", + "game-session-service", "world-management-service", +) for name in app_names: service = services[name] environment = service.get("environment", {}) @@ -530,7 +545,7 @@ for name in app_names: assert service.get("build") is None, f"image-only proof must not build {name}" for name in ( "account-service", "game-session-service", "entity-management-service", - "world-management-service", "game-design-service", "logging-admin-service", + "world-management-service", "game-design-service", "game-logic-service", "logging-admin-service", ): namespace = services[name]["environment"].get("FIREMUD_GRPC_WORKLOAD_NAMESPACE") assert namespace == "dev", (name, namespace) @@ -597,6 +612,16 @@ world_management_receipt_mounts = [mount for mount in world_management.get("volu assert len(world_management_receipt_mounts) == 1, world_management_receipt_mounts assert world_management_receipt_mounts[0]["source"] == source_receipt_source, world_management_receipt_mounts[0] assert world_management_receipt_mounts[0].get("read_only") is True +for name in ("account-service", "entity-management-service"): + service = services[name] + environment = service["environment"] + assert environment.get("FIREMUD_SMOKE_INITIAL_ADMISSION_FIXTURE_ENABLED") == "false", name + assert environment.get("FIREMUD_SMOKE_INITIAL_ADMISSION_CAPABILITY_PATH") == capability_path, name + assert environment.get("FIREMUD_SMOKE_AUTHORED_WORLD_SOURCE_RECEIPT_PATH") == source_receipt_path, name + for target, source in ((capability_path, capability_source), (source_receipt_dir, source_receipt_source)): + mounts = [mount for mount in service.get("volumes", []) if mount.get("target") == target] + assert len(mounts) == 1 and mounts[0]["source"] == source and mounts[0].get("read_only") is True, (name, target) +assert services["game-logic-service"]["environment"].get("FIREMUD_SMOKE_INITIAL_ADMISSION_FIXTURE_ENABLED") == "false" for name, service in services.items(): if name not in fixture_services: assert not any(mount.get("target") == capability_path for mount in service.get("volumes", [])), name diff --git a/dev-tools/tests/run-owned-initial-admission-capability-contract.sh b/dev-tools/tests/run-owned-initial-admission-capability-contract.sh index 6433d785eb..a92fedd32d 100644 --- a/dev-tools/tests/run-owned-initial-admission-capability-contract.sh +++ b/dev-tools/tests/run-owned-initial-admission-capability-contract.sh @@ -66,7 +66,7 @@ assert value["visible"] is True assert value["publicProductionRealm"] is True assert value["requiresCharacterSelection"] is False assert value["stateScope"] == "SHARED" -assert value["characterCreationPolicy"] == "ALLOW_NEW" +assert value["characterCreationPolicy"] == "PRESEEDED_ONLY" assert value["gameSessionUriSan"] == "spiffe://firemud/ns/dev/sa/game-session-service" assert value["worldManagementUriSan"] == "spiffe://firemud/ns/dev/sa/world-management-service" assert len(value["worldManagementLeafSha256"]) == 64 diff --git a/dev-tools/tests/smoke-transport-contract.sh b/dev-tools/tests/smoke-transport-contract.sh index fa9c6f9735..e5831d6e64 100644 --- a/dev-tools/tests/smoke-transport-contract.sh +++ b/dev-tools/tests/smoke-transport-contract.sh @@ -2114,7 +2114,7 @@ for script in \ grep -q 'SMOKE_MUTATION_BOUNDARY=.*' "$script" grep -q 'require_smoke_mutation_boundary' "$script" grep -q 'run-owned-compose' "$script" - [[ "$script" == *"tcp-proxy-service/telnet-login-look-smoke.sh" ]] || grep -q 'login_play_look_steps' "$script" + [[ "$script" == *"tcp-proxy-service/telnet-login-look-smoke.sh" ]] || grep -Eq 'login_play_look_steps|websocket_fail_closed_play_steps' "$script" grep -q 'gameplay_item_container_equipment_steps' "$script" if [[ "$script" == *"game-session-service/websocket-login-look-smoke.sh" ]]; then grep -Fq -- 'venv_directory = repo_root / ".venv-smoke"' "$script" || diff --git a/docker/docker-compose.grpc-mtls.override.yml b/docker/docker-compose.grpc-mtls.override.yml index 39bf432898..ad8c475bf1 100644 --- a/docker/docker-compose.grpc-mtls.override.yml +++ b/docker/docker-compose.grpc-mtls.override.yml @@ -19,8 +19,26 @@ services: environment: <<: *grpc-mtls-environment FIREMUD_GRPC_WORKLOAD_NAMESPACE: dev + FIREMUD_SMOKE_RUN_ID: ${FIREMUD_SMOKE_RUN_ID:-} + FIREMUD_SMOKE_COMPOSE_PROJECT_NAME: ${FIREMUD_SMOKE_COMPOSE_PROJECT_NAME:-} + # Enrolls the fixture's fresh Game Design tenant with a demo entitlement for REALMS/JOIN. + FIREMUD_SMOKE_INITIAL_ADMISSION_FIXTURE_ENABLED: ${FIREMUD_SMOKE_INITIAL_ADMISSION_FIXTURE_ENABLED:-false} + FIREMUD_SMOKE_INITIAL_ADMISSION_CAPABILITY_PATH: /app/run-owned-initial-admission-capability.json + FIREMUD_SMOKE_AUTHORED_WORLD_SOURCE_RECEIPT_PATH: /app/run-owned-authored-world-source/source-receipt.json volumes: - ${FIREMUD_COMPOSE_GRPC_MTLS_CERT_ROOT:?canonical smoke must set a run-owned mTLS certificate root}/workloads/account-service:/app/certs:ro + - type: bind + source: ${FIREMUD_SMOKE_INITIAL_ADMISSION_CAPABILITY_HOST_PATH:-/dev/null} + target: /app/run-owned-initial-admission-capability.json + read_only: true + bind: + create_host_path: false + - type: bind + source: ${FIREMUD_SMOKE_AUTHORED_WORLD_SOURCE_RECEIPT_DIR_HOST_PATH:?run-owned smoke must prepare a claimed authored-world receipt directory} + target: /app/run-owned-authored-world-source + read_only: true + bind: + create_host_path: false gateway: environment: @@ -54,11 +72,28 @@ services: environment: <<: *grpc-mtls-environment FIREMUD_GRPC_WORKLOAD_NAMESPACE: dev + FIREMUD_SMOKE_RUN_ID: ${FIREMUD_SMOKE_RUN_ID:-} + FIREMUD_SMOKE_COMPOSE_PROJECT_NAME: ${FIREMUD_SMOKE_COMPOSE_PROJECT_NAME:-} + FIREMUD_SMOKE_INITIAL_ADMISSION_FIXTURE_ENABLED: ${FIREMUD_SMOKE_INITIAL_ADMISSION_FIXTURE_ENABLED:-false} + FIREMUD_SMOKE_INITIAL_ADMISSION_CAPABILITY_PATH: /app/run-owned-initial-admission-capability.json + FIREMUD_SMOKE_AUTHORED_WORLD_SOURCE_RECEIPT_PATH: /app/run-owned-authored-world-source/source-receipt.json depends_on: account-service: condition: service_healthy volumes: - ${FIREMUD_COMPOSE_GRPC_MTLS_CERT_ROOT:?canonical smoke must set a run-owned mTLS certificate root}/workloads/entity-management-service:/app/certs:ro + - type: bind + source: ${FIREMUD_SMOKE_INITIAL_ADMISSION_CAPABILITY_HOST_PATH:-/dev/null} + target: /app/run-owned-initial-admission-capability.json + read_only: true + bind: + create_host_path: false + - type: bind + source: ${FIREMUD_SMOKE_AUTHORED_WORLD_SOURCE_RECEIPT_DIR_HOST_PATH:?run-owned smoke must prepare a claimed authored-world receipt directory} + target: /app/run-owned-authored-world-source + read_only: true + bind: + create_host_path: false game-design-service: environment: @@ -101,6 +136,8 @@ services: game-logic-service: environment: <<: *grpc-mtls-environment + FIREMUD_GRPC_WORKLOAD_NAMESPACE: dev + FIREMUD_SMOKE_INITIAL_ADMISSION_FIXTURE_ENABLED: ${FIREMUD_SMOKE_INITIAL_ADMISSION_FIXTURE_ENABLED:-false} volumes: - ${FIREMUD_COMPOSE_GRPC_MTLS_CERT_ROOT:?canonical smoke must set a run-owned mTLS certificate root}/workloads/game-logic-service:/app/certs:ro @@ -113,6 +150,8 @@ services: FIREMUD_SMOKE_INITIAL_ADMISSION_FIXTURE_ENABLED: ${FIREMUD_SMOKE_INITIAL_ADMISSION_FIXTURE_ENABLED:-false} FIREMUD_SMOKE_INITIAL_ADMISSION_CAPABILITY_PATH: /app/run-owned-initial-admission-capability.json FIREMUD_SMOKE_AUTHORED_WORLD_SOURCE_RECEIPT_PATH: /app/run-owned-authored-world-source/source-receipt.json + # The canonical fixture drives its first OPEN through the launch-association owner read. + FIREMUD_CANONICAL_GAME_INSTANCE_LAUNCH_ASSOCIATION_OWNER_READ_ENABLED: ${FIREMUD_SMOKE_INITIAL_ADMISSION_FIXTURE_ENABLED:-false} FIREMUD_GAMEPLAY_AUTHENTICATED_LISTENER_ENABLED: "true" FIREMUD_GAMEPLAY_AUTHENTICATED_LISTENER_PORT: "8444" volumes: diff --git a/docker/docker-compose.pre-v1-login.override.yml b/docker/docker-compose.pre-v1-login.override.yml index 9cff9e93da..5e22587a8d 100644 --- a/docker/docker-compose.pre-v1-login.override.yml +++ b/docker/docker-compose.pre-v1-login.override.yml @@ -117,6 +117,7 @@ services: FIREMUD_ACCOUNT_JWT_READINESS_VALIDATION_ENABLED: "true" FIREMUD_ACCOUNT_JWT_READINESS_VALIDATION_PROTECTED_BINDING_PATH: /etc/firemud/account-jwt-readiness/binding.properties FIREMUD_ACCOUNT_GAMEPLAY_LOGIN_ENABLED: "true" + FIREMUD_ACCOUNT_CANONICAL_REALM_ADMISSION_ENABLED: "true" FIREMUD_ACCOUNT_GAMEPLAY_LOGIN_COORDINATION_URI: redis://account_coord_app:pre-v1-account-coordination@redis-coord:6379/0 FIREMUD_ACCOUNT_GAMEPLAY_LOGIN_COORDINATION_COMMAND_TIMEOUT_MILLIS: "2000" FIREMUD_ACCOUNT_GAMEPLAY_LOGIN_COORDINATION_REQUIRED_LOCAL_AOF_COUNT: "1" @@ -132,6 +133,13 @@ services: - pre-v1-jwt-secret:/var/run/secrets/firemud/jwt:ro - pre-v1-jwks-projection:/var/run/secrets/firemud/jwks:ro + world-management-service: + environment: + FIREMUD_WORLD_RUNTIME_INSTALLATION_INVENTORY_PATH: /etc/firemud/world-runtime-installation/inventory.json + volumes: + # Pre-v1 waiver: read-only runtime installation inventory for the run-owned fixture. + - ${FIREMUD_PRE_V1_SIGNER_FIXTURES:?run the pre-v1 signer fixtures first}/world-runtime-installation:/etc/firemud/world-runtime-installation:ro + game-session-service: # Authenticated LOGIN needs a promoted Account signer; start only once it is live. depends_on: diff --git a/protos/entity-management/v1/entity_management_service.proto b/protos/entity-management/v1/entity_management_service.proto index 8fbc886777..15261fbdaa 100644 --- a/protos/entity-management/v1/entity_management_service.proto +++ b/protos/entity-management/v1/entity_management_service.proto @@ -10,6 +10,24 @@ import "entity-management/v1/entity_character_create_service.proto"; option java_package = "net.firedevops.firemud.entitymanagement.v1"; option java_multiple_files = true; +// Verifies physical room-ground absence within an exact run-owned fixture. +service RunOwnedFixtureLookEntityService { + rpc ReadRunOwnedFixtureGround(ReadRunOwnedFixtureGroundRequest) + returns (ReadRunOwnedFixtureGroundResponse); +} + +message ReadRunOwnedFixtureGroundRequest { + shared.v1.RoomInstanceRef room = 1; + // Complete WorldRunOwnedFixtureLifecycleEvidence from the authenticated World owner. + bytes world_fixture_lifecycle = 2; +} + +message ReadRunOwnedFixtureGroundResponse { + shared.v1.RoomInstanceRef room = 1; + string entity_snapshot_id = 2; + bool empty_ground_verified = 3; +} + service EntityManagementService { rpc Ping(PingRequest) returns (PingResponse); rpc CreateCharacter(CreateCharacterRequest) returns (CreateCharacterResponse); diff --git a/protos/game-logic/v1/game_logic_service.proto b/protos/game-logic/v1/game_logic_service.proto index 32f878da26..60c182e260 100644 --- a/protos/game-logic/v1/game_logic_service.proto +++ b/protos/game-logic/v1/game_logic_service.proto @@ -5,10 +5,25 @@ package game_logic.v1; import "entity-management/v1/entity_management_service.proto"; import "shared/v1/errors.proto"; import "shared/v1/instance_refs.proto"; +import "world-management/v1/world_management_service.proto"; option java_package = "net.firedevops.firemud.gamelogic.v1"; option java_multiple_files = true; +// Protected LOOK projection for an already admitted run-owned fixture session. +service RunOwnedFixtureLookService { + rpc ResolveRunOwnedFixtureLook(ResolveRunOwnedFixtureLookRequest) + returns (ResolveRunOwnedFixtureLookResponse); +} + +message ResolveRunOwnedFixtureLookRequest { + world_management.v1.ReadRunOwnedFixtureLookRoomRequest room = 1; +} + +message ResolveRunOwnedFixtureLookResponse { + LookResult look = 1; +} + service GameLogicService { rpc Ping(PingRequest) returns (PingResponse); rpc ExecuteCommand(ExecuteCommandRequest) returns (ExecuteCommandResponse); diff --git a/protos/world-management/v1/world_canonical_instance_lifecycle_read.proto b/protos/world-management/v1/world_canonical_instance_lifecycle_read.proto index 2fe0c25a6b..9194be50a2 100644 --- a/protos/world-management/v1/world_canonical_instance_lifecycle_read.proto +++ b/protos/world-management/v1/world_canonical_instance_lifecycle_read.proto @@ -9,6 +9,9 @@ option java_multiple_files = true; service WorldCanonicalInstanceLifecycleReadService { rpc ReadWorldCanonicalInstanceLifecycle(ReadWorldCanonicalInstanceLifecycleRequest) returns (ReadWorldCanonicalInstanceLifecycleResponse); + // Read-only start room of the exact ACTIVE run-owned fixed fixture. + rpc ReadRunOwnedFixtureStartRoom(ReadRunOwnedFixtureStartRoomRequest) + returns (ReadRunOwnedFixtureStartRoomResponse); } message ReadWorldCanonicalInstanceLifecycleRequest { @@ -20,3 +23,12 @@ message ReadWorldCanonicalInstanceLifecycleResponse { // Complete closed evidence bytes, including the exact request echo and full launch binding. bytes canonical_response_bytes = 1; } + +message ReadRunOwnedFixtureStartRoomRequest { + ReadWorldCanonicalInstanceLifecycleRequest lifecycle = 1; +} + +message ReadRunOwnedFixtureStartRoomResponse { + ReadWorldCanonicalInstanceLifecycleResponse lifecycle = 1; + string room_instance_key = 2; +} diff --git a/protos/world-management/v1/world_management_service.proto b/protos/world-management/v1/world_management_service.proto index 30468bf2f3..580e7fc9a1 100644 --- a/protos/world-management/v1/world_management_service.proto +++ b/protos/world-management/v1/world_management_service.proto @@ -10,6 +10,23 @@ import "world-management/v1/world_canonical_instance_lifecycle_read.proto"; option java_package = "net.firedevops.firemud.worldmanagement.v1"; option java_multiple_files = true; +// Protected World snapshot reads for the exact active run-owned fixture. +service RunOwnedFixtureLookWorldService { + rpc ReadRunOwnedFixtureLookRoom(ReadRunOwnedFixtureLookRoomRequest) + returns (ReadRunOwnedFixtureLookRoomResponse); +} + +message ReadRunOwnedFixtureLookRoomRequest { + ReadWorldCanonicalInstanceLifecycleRequest lifecycle = 1; + string expected_room_instance_key = 2; + string preferred_locale = 3; +} + +message ReadRunOwnedFixtureLookRoomResponse { + ReadWorldCanonicalInstanceLifecycleResponse lifecycle = 1; + RoomSnapshot snapshot = 2; +} + service WorldManagementService { rpc Ping(PingRequest) returns (PingResponse); rpc PrepareWorldInstance(PrepareWorldInstanceRequest) diff --git a/services/account-service/src/main/java/net/firedevops/firemud/accountservice/config/AccountCanonicalRealmAdmissionConfiguration.java b/services/account-service/src/main/java/net/firedevops/firemud/accountservice/config/AccountCanonicalRealmAdmissionConfiguration.java new file mode 100644 index 0000000000..2c5eb71df2 --- /dev/null +++ b/services/account-service/src/main/java/net/firedevops/firemud/accountservice/config/AccountCanonicalRealmAdmissionConfiguration.java @@ -0,0 +1,107 @@ +package net.firedevops.firemud.accountservice.config; + +import java.time.Clock; +import net.firedevops.firemud.accountservice.client.CanonicalGameplayAdmissionDecisionReadClient; +import net.firedevops.firemud.accountservice.repository.AccountConnectScopeRepository; +import net.firedevops.firemud.accountservice.repository.AccountDemoTenantEntitlementRepository; +import net.firedevops.firemud.accountservice.repository.AccountRepository; +import net.firedevops.firemud.accountservice.repository.AccountTenantAuthorityEventRepository; +import net.firedevops.firemud.accountservice.repository.AccountTenantMembershipRepository; +import net.firedevops.firemud.accountservice.repository.FreshTenantIdentityAssociationRepository; +import net.firedevops.firemud.accountservice.service.AccountCanonicalConnectScopeReader; +import net.firedevops.firemud.accountservice.service.AccountCanonicalFirstJoinTerminalCoordinator; +import net.firedevops.firemud.accountservice.service.AccountCanonicalPublicRealmScopeOwner; +import net.firedevops.firemud.accountservice.service.AccountPublicBootstrapEntitlementOwner; +import net.firedevops.firemud.accountservice.service.impl.AccountServiceImpl; +import net.firedevops.firemud.accountservice.service.session.AccountPlayerBootstrapCallerVerifier; +import net.firedevops.firemud.accountservice.service.session.SessionService; +import net.firedevops.firemud.common.config.ServiceEndpointsProperties; +import net.firedevops.firemud.common.grpc.CommonGrpcClientProperties; +import net.firedevops.firemud.common.grpc.GrpcChannelFactory; +import net.firedevops.firemud.common.security.JwtUtil; +import org.springframework.beans.factory.SmartInitializingSingleton; +import org.springframework.beans.factory.annotation.Qualifier; +import org.springframework.beans.factory.annotation.Value; +import org.springframework.boot.autoconfigure.condition.ConditionalOnProperty; +import org.springframework.context.annotation.Bean; +import org.springframework.context.annotation.Configuration; +import org.springframework.transaction.PlatformTransactionManager; + +/** + * Registers the canonical public REALMS issuer and JOIN scope consumers over the Game Session + * admission decision read. Paid hosting sources are composed only by checkout receiving, so paid + * tenants fail closed here; non-paid demo tenants are admitted from their Account entitlement. + */ +@Configuration(proxyBeanMethods = false) +@ConditionalOnProperty( + prefix = "firemud.account.canonical-realm-admission", + name = "enabled", + havingValue = "true") +public class AccountCanonicalRealmAdmissionConfiguration { + + @Bean(initMethod = "init", destroyMethod = "close") + CanonicalGameplayAdmissionDecisionReadClient canonicalGameplayAdmissionDecisionReadClient( + ServiceEndpointsProperties endpoints, + CommonGrpcClientProperties tls, + GrpcChannelFactory channels, + @Value("${firemud.grpc.workload-namespace:}") String namespace) { + return new CanonicalGameplayAdmissionDecisionReadClient(endpoints, tls, channels, namespace); + } + + @Bean + AccountPublicBootstrapEntitlementOwner accountPublicBootstrapEntitlementOwner( + AccountTenantAuthorityEventRepository tenantSources, + AccountDemoTenantEntitlementRepository demos, + @Qualifier("transactionManager") PlatformTransactionManager transactions) { + return new AccountPublicBootstrapEntitlementOwner( + tenantSources, null, demos, transactions, Clock.systemUTC()); + } + + @Bean + AccountCanonicalPublicRealmScopeOwner accountCanonicalPublicRealmScopeOwner( + @Qualifier("jwtUtil") JwtUtil jwt, + AccountRepository accounts, + SessionService sessions, + CanonicalGameplayAdmissionDecisionReadClient targets, + AccountPublicBootstrapEntitlementOwner entitlements, + AccountTenantMembershipRepository memberships, + FreshTenantIdentityAssociationRepository fresh, + AccountTenantAuthorityEventRepository tenantSources, + AccountConnectScopeRepository scopes, + AccountTokenProperties tokens, + @Qualifier("transactionManager") PlatformTransactionManager transactions, + @Value("${firemud.grpc.workload-namespace:}") String namespace) { + return new AccountCanonicalPublicRealmScopeOwner( + new AccountPlayerBootstrapCallerVerifier(jwt, accounts, sessions), + targets, + entitlements, + accounts, + memberships, + fresh, + tenantSources, + scopes, + jwt, + tokens, + Clock.systemUTC(), + transactions, + namespace); + } + + @Bean + SmartInitializingSingleton accountCanonicalScopeConsumersComposition( + AccountServiceImpl primary, + @Qualifier("jwtUtil") JwtUtil jwt, + AccountConnectScopeRepository scopes, + CanonicalGameplayAdmissionDecisionReadClient targets, + AccountTenantAuthorityEventRepository tenantSources, + AccountDemoTenantEntitlementRepository demos, + AccountCanonicalFirstJoinTerminalCoordinator firstJoin, + @Qualifier("transactionManager") PlatformTransactionManager transactions, + @Value("${firemud.grpc.workload-namespace:}") String namespace) { + Clock clock = Clock.systemUTC(); + var reader = new AccountCanonicalConnectScopeReader(jwt, scopes, transactions, clock); + return () -> + primary.setCanonicalScopeConsumers( + reader, targets, tenantSources, demos, null, null, firstJoin, namespace, clock); + } +} diff --git a/services/account-service/src/main/java/net/firedevops/firemud/accountservice/config/AccountGameplayAdmissionReceiversConfiguration.java b/services/account-service/src/main/java/net/firedevops/firemud/accountservice/config/AccountGameplayAdmissionReceiversConfiguration.java new file mode 100644 index 0000000000..0655af109f --- /dev/null +++ b/services/account-service/src/main/java/net/firedevops/firemud/accountservice/config/AccountGameplayAdmissionReceiversConfiguration.java @@ -0,0 +1,171 @@ +package net.firedevops.firemud.accountservice.config; + +import io.grpc.BindableService; +import io.grpc.ServerInterceptors; +import java.time.Clock; +import javax.sql.DataSource; +import net.firedevops.firemud.accountservice.client.AccountOriginalNewFinalAdmissionGrpcReadClient; +import net.firedevops.firemud.accountservice.client.CanonicalGameplayAdmissionDecisionReadClient; +import net.firedevops.firemud.accountservice.repository.AccountAuthorityGenerationRepository; +import net.firedevops.firemud.accountservice.repository.AccountAuthorityOutboxRepository; +import net.firedevops.firemud.accountservice.repository.AccountAuthoritySourceEvidenceRepository; +import net.firedevops.firemud.accountservice.repository.AccountCanonicalRuntimeMembershipSnapshotRepository; +import net.firedevops.firemud.accountservice.repository.AccountConnectScopeRepository; +import net.firedevops.firemud.accountservice.repository.AccountDemoTenantEntitlementRepository; +import net.firedevops.firemud.accountservice.repository.AccountGameplayAdmissionLeaseOwner; +import net.firedevops.firemud.accountservice.repository.AccountGameplayDelegationIssuanceRepository; +import net.firedevops.firemud.accountservice.repository.AccountMembershipPairAuthorityRepository; +import net.firedevops.firemud.accountservice.repository.AccountOriginalNewBoundGameplayCredentialOwner; +import net.firedevops.firemud.accountservice.repository.AccountRepository; +import net.firedevops.firemud.accountservice.repository.AccountTenantAuthorityEventRepository; +import net.firedevops.firemud.accountservice.repository.AccountTenantMembershipRepository; +import net.firedevops.firemud.accountservice.repository.AccountTenantMembershipRoleSnapshotRepository; +import net.firedevops.firemud.accountservice.repository.FreshTenantIdentityAssociationRepository; +import net.firedevops.firemud.accountservice.service.AccountPlayerAdmissionEntitlementOwner; +import net.firedevops.firemud.accountservice.service.AccountTenantCapacityOwner; +import net.firedevops.firemud.accountservice.service.impl.AccountPlayerAdmissionEntitlementGrpcService; +import net.firedevops.firemud.accountservice.service.session.AccountGameplayAdmissionCallerVerifier; +import net.firedevops.firemud.accountservice.service.session.AccountGameplayAdmissionLeaseManualFactory; +import net.firedevops.firemud.accountservice.service.session.AccountGameplayAdmissionLeaseWorkloadGuard; +import net.firedevops.firemud.accountservice.service.session.AccountGameplayDelegationCommittedIssuanceOwner; +import net.firedevops.firemud.accountservice.service.session.AccountGameplayDelegationSigner; +import net.firedevops.firemud.accountservice.service.session.AccountGameplayDelegationTokenRegistry; +import net.firedevops.firemud.accountservice.service.session.AccountJwtJwksTrustedSource; +import net.firedevops.firemud.accountservice.service.session.AccountResponseEnvelopeCryptography; +import net.firedevops.firemud.common.config.ServiceEndpointsProperties; +import net.firedevops.firemud.common.grpc.CommonGrpcClientProperties; +import net.firedevops.firemud.common.grpc.GrpcChannelFactory; +import net.firedevops.firemud.common.grpc.GrpcPeerIdentityInterceptor; +import org.jooq.DSLContext; +import org.springframework.beans.factory.annotation.Qualifier; +import org.springframework.beans.factory.annotation.Value; +import org.springframework.boot.autoconfigure.condition.ConditionalOnExpression; +import org.springframework.context.annotation.Bean; +import org.springframework.context.annotation.Configuration; +import org.springframework.transaction.PlatformTransactionManager; + +/** + * Registers the Account receivers Game Session's final PLAY admission calls: the player entitlement + * read, the gameplay admission lease (with original-new bound credentials) and tenant capacity + * (served through the shared AccountService registration). Each receiver authenticates the exact + * Game Session workload. Paid hosting sources are not composed, so paid tenants fail closed; demo + * tenants admit from their Account entitlement. + */ +@Configuration(proxyBeanMethods = false) +@ConditionalOnExpression( + "${firemud.account.canonical-realm-admission.enabled:false}" + + " and ${firemud.account.gameplay-login.enabled:false}") +public class AccountGameplayAdmissionReceiversConfiguration { + + @Bean(initMethod = "init", destroyMethod = "close") + AccountOriginalNewFinalAdmissionGrpcReadClient accountOriginalNewFinalAdmissionReadClient( + ServiceEndpointsProperties endpoints, + CommonGrpcClientProperties tls, + GrpcChannelFactory channels, + @Value("${firemud.grpc.workload-namespace:}") String namespace) { + return new AccountOriginalNewFinalAdmissionGrpcReadClient(endpoints, tls, channels, namespace); + } + + @Bean + AccountGameplayAdmissionCallerVerifier accountGameplayAdmissionCallerVerifier( + AccountJwtJwksTrustedSource jwks, AccountGameplayDelegationCommittedIssuanceOwner committed) { + return new AccountGameplayAdmissionCallerVerifier(jwks, committed, Clock.systemUTC()); + } + + @Bean + BindableService accountGameplayAdmissionLeaseReceiver( + AccountGameplayAdmissionCallerVerifier verifier, + CanonicalGameplayAdmissionDecisionReadClient decisions, + DataSource dataSource, + AccountGameplayDelegationSigner signer, + AccountGameplayDelegationTokenRegistry registry, + @Qualifier("accountResponseEnvelopeCryptography") AccountResponseEnvelopeCryptography crypto, + AccountOriginalNewFinalAdmissionGrpcReadClient finalReads, + @Value("${firemud.grpc.workload-namespace:}") String namespace) { + var leases = new AccountGameplayAdmissionLeaseOwner(verifier, decisions, namespace, dataSource); + var credentials = + new AccountOriginalNewBoundGameplayCredentialOwner( + dataSource, + namespace, + verifier, + signer, + registry, + crypto, + Clock.systemUTC(), + finalReads); + var receiver = + AccountGameplayAdmissionLeaseManualFactory.createUnregisteredReceiver( + leases, credentials, namespace); + var guard = new AccountGameplayAdmissionLeaseWorkloadGuard(namespace); + return () -> + ServerInterceptors.interceptForward(receiver, new GrpcPeerIdentityInterceptor(), guard); + } + + @Bean + AccountCanonicalRuntimeMembershipSnapshotRepository accountCanonicalRuntimeMembershipSnapshots( + AccountRepository accounts, + AccountAuthorityGenerationRepository generations, + AccountAuthoritySourceEvidenceRepository sources, + AccountTenantAuthorityEventRepository tenantEvents, + FreshTenantIdentityAssociationRepository freshTenants, + AccountTenantMembershipRepository memberships, + AccountMembershipPairAuthorityRepository pairs, + AccountTenantMembershipRoleSnapshotRepository roles, + AccountAuthorityOutboxRepository outbox) { + return new AccountCanonicalRuntimeMembershipSnapshotRepository( + accounts, + generations, + sources, + tenantEvents, + freshTenants, + memberships, + pairs, + roles, + outbox); + } + + @Bean + AccountPlayerAdmissionEntitlementGrpcService accountPlayerAdmissionEntitlementReceiver( + DSLContext dsl, + AccountRepository accounts, + AccountGameplayAdmissionCallerVerifier verifier, + AccountGameplayDelegationIssuanceRepository issuances, + AccountCanonicalRuntimeMembershipSnapshotRepository memberships, + AccountConnectScopeRepository scopes, + AccountDemoTenantEntitlementRepository demos, + AccountTenantAuthorityEventRepository tenantSources, + CanonicalGameplayAdmissionDecisionReadClient decisions, + @Qualifier("transactionManager") PlatformTransactionManager transactions, + @Value("${firemud.grpc.workload-namespace:}") String namespace) { + var owner = + new AccountPlayerAdmissionEntitlementOwner( + dsl, + accounts, + verifier, + issuances, + memberships, + scopes, + null, + null, + demos, + tenantSources, + decisions, + transactions, + Clock.systemUTC(), + namespace); + return new AccountPlayerAdmissionEntitlementGrpcService(owner, namespace); + } + + @Bean + AccountTenantCapacityOwner accountTenantCapacityOwner( + DSLContext dsl, + AccountRepository accounts, + AccountCanonicalRuntimeMembershipSnapshotRepository memberships, + AccountGameplayDelegationIssuanceRepository issuances, + AccountConnectScopeRepository scopes, + @Qualifier("transactionManager") PlatformTransactionManager transactions, + @Value("${firemud.grpc.workload-namespace:}") String namespace) { + return new AccountTenantCapacityOwner( + dsl, accounts, memberships, issuances, scopes, transactions, Clock.systemUTC(), namespace); + } +} diff --git a/services/account-service/src/main/java/net/firedevops/firemud/accountservice/config/RunOwnedFixtureDemoTenantConfiguration.java b/services/account-service/src/main/java/net/firedevops/firemud/accountservice/config/RunOwnedFixtureDemoTenantConfiguration.java new file mode 100644 index 0000000000..8d9bdbed8d --- /dev/null +++ b/services/account-service/src/main/java/net/firedevops/firemud/accountservice/config/RunOwnedFixtureDemoTenantConfiguration.java @@ -0,0 +1,65 @@ +package net.firedevops.firemud.accountservice.config; + +import java.io.IOException; +import java.nio.file.Path; +import net.firedevops.firemud.accountservice.client.GameDesignFreshTenantIdentityClient; +import net.firedevops.firemud.accountservice.data.RunOwnedFixtureDemoTenantEnrollmentDriver; +import net.firedevops.firemud.accountservice.repository.AccountAuthorityGenerationRepository; +import net.firedevops.firemud.accountservice.repository.AccountDemoTenantEntitlementRepository; +import net.firedevops.firemud.accountservice.repository.FreshTenantIdentityAssociationRepository; +import net.firedevops.firemud.accountservice.service.FreshTenantIdentityEnrollmentService; +import net.firedevops.firemud.common.config.ServiceEndpointsProperties; +import net.firedevops.firemud.common.grpc.CommonGrpcClientProperties; +import net.firedevops.firemud.common.grpc.GrpcChannelFactory; +import org.springframework.beans.factory.annotation.Qualifier; +import org.springframework.beans.factory.annotation.Value; +import org.springframework.boot.autoconfigure.condition.ConditionalOnProperty; +import org.springframework.context.annotation.Bean; +import org.springframework.context.annotation.Configuration; +import org.springframework.transaction.PlatformTransactionManager; +import org.springframework.transaction.TransactionDefinition; +import org.springframework.transaction.support.TransactionTemplate; + +/** Enrolls the run-owned Compose fixture tenant and its demo entitlement into Account. */ +@Configuration(proxyBeanMethods = false) +@ConditionalOnProperty( + name = "FIREMUD_SMOKE_INITIAL_ADMISSION_FIXTURE_ENABLED", + havingValue = "true") +public class RunOwnedFixtureDemoTenantConfiguration { + + @Bean(destroyMethod = "close") + GameDesignFreshTenantIdentityClient runOwnedFixtureGameDesignTenantIdentityClient( + ServiceEndpointsProperties endpoints, + CommonGrpcClientProperties tls, + GrpcChannelFactory channels, + @Value("${firemud.grpc.workload-namespace:}") String namespace) + throws IOException { + var client = new GameDesignFreshTenantIdentityClient(endpoints, tls, channels, namespace); + client.init(); + return client; + } + + @Bean + RunOwnedFixtureDemoTenantEnrollmentDriver runOwnedFixtureDemoTenantEnrollmentDriver( + GameDesignFreshTenantIdentityClient gameDesign, + FreshTenantIdentityAssociationRepository fresh, + AccountAuthorityGenerationRepository generations, + AccountDemoTenantEntitlementRepository demos, + @Qualifier("transactionManager") PlatformTransactionManager transactions, + @Value("${FIREMUD_SMOKE_INITIAL_ADMISSION_CAPABILITY_PATH:}") String capabilityPath, + @Value("${FIREMUD_SMOKE_AUTHORED_WORLD_SOURCE_RECEIPT_PATH:}") String receiptPath, + @Value("${FIREMUD_SMOKE_RUN_ID:}") String runId, + @Value("${FIREMUD_SMOKE_COMPOSE_PROJECT_NAME:}") String composeProjectName) { + var importTransaction = new TransactionTemplate(transactions); + importTransaction.setPropagationBehavior(TransactionDefinition.PROPAGATION_REQUIRES_NEW); + importTransaction.setIsolationLevel(TransactionDefinition.ISOLATION_SERIALIZABLE); + return new RunOwnedFixtureDemoTenantEnrollmentDriver( + new FreshTenantIdentityEnrollmentService(gameDesign, fresh, generations, importTransaction), + demos, + transactions, + Path.of(capabilityPath), + Path.of(receiptPath), + runId, + composeProjectName); + } +} diff --git a/services/account-service/src/main/java/net/firedevops/firemud/accountservice/data/RunOwnedFixtureDemoTenantEnrollmentDriver.java b/services/account-service/src/main/java/net/firedevops/firemud/accountservice/data/RunOwnedFixtureDemoTenantEnrollmentDriver.java new file mode 100644 index 0000000000..3257ccc9cf --- /dev/null +++ b/services/account-service/src/main/java/net/firedevops/firemud/accountservice/data/RunOwnedFixtureDemoTenantEnrollmentDriver.java @@ -0,0 +1,134 @@ +package net.firedevops.firemud.accountservice.data; + +import java.io.IOException; +import java.io.InputStream; +import java.nio.charset.StandardCharsets; +import java.nio.file.Files; +import java.nio.file.Path; +import java.util.Objects; +import java.util.UUID; +import java.util.concurrent.atomic.AtomicBoolean; +import net.firedevops.firemud.accountservice.dto.DemoTenantEntitlementRequest; +import net.firedevops.firemud.accountservice.repository.AccountDemoTenantEntitlementRepository; +import net.firedevops.firemud.accountservice.service.FreshTenantIdentityEnrollmentService; +import net.firedevops.firemud.common.smoke.RunOwnedInitialAdmissionFixtureWireCodec; +import net.firedevops.firemud.common.tenant.FreshTenantCreationEvidence; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; +import org.springframework.scheduling.annotation.Scheduled; +import org.springframework.transaction.PlatformTransactionManager; +import org.springframework.transaction.TransactionDefinition; +import org.springframework.transaction.support.TransactionTemplate; + +/** + * Enrolls the run-owned Compose fixture's fresh Game Design tenant into Account and provisions its + * non-paid demo entitlement, so public REALMS and JOIN can admit players to it. The fixture receipt + * only locates the creation; Account imports the authenticated Game Design readback. Retries until + * Game Design has committed the fixture, and replays idempotently after a restart. + */ +public final class RunOwnedFixtureDemoTenantEnrollmentDriver { + private static final Logger LOG = + LoggerFactory.getLogger(RunOwnedFixtureDemoTenantEnrollmentDriver.class); + private static final long RETRY_INTERVAL_MS = 10_000L; + private static final int MAX_FILE_BYTES = 16 * 1024; + private static final DemoTenantEntitlementRequest.Quotas FIXTURE_QUOTAS = + new DemoTenantEntitlementRequest.Quotas(3L, 2L, 4096L); + + private final FreshTenantIdentityEnrollmentService enrollment; + private final AccountDemoTenantEntitlementRepository demos; + private final TransactionTemplate transaction; + private final Path capabilityPath; + private final Path receiptPath; + private final String runId; + private final String composeProjectName; + private final AtomicBoolean enrolled = new AtomicBoolean(); + + public RunOwnedFixtureDemoTenantEnrollmentDriver( + FreshTenantIdentityEnrollmentService enrollment, + AccountDemoTenantEntitlementRepository demos, + PlatformTransactionManager transactions, + Path capabilityPath, + Path receiptPath, + String runId, + String composeProjectName) { + this.enrollment = Objects.requireNonNull(enrollment, "enrollment"); + this.demos = Objects.requireNonNull(demos, "demos"); + this.capabilityPath = Objects.requireNonNull(capabilityPath, "capabilityPath"); + this.receiptPath = Objects.requireNonNull(receiptPath, "receiptPath"); + this.runId = requireText(runId, "runId"); + this.composeProjectName = requireText(composeProjectName, "composeProjectName"); + transaction = new TransactionTemplate(Objects.requireNonNull(transactions, "transactions")); + transaction.setPropagationBehavior(TransactionDefinition.PROPAGATION_REQUIRES_NEW); + transaction.setIsolationLevel(TransactionDefinition.ISOLATION_SERIALIZABLE); + } + + @Scheduled(initialDelay = RETRY_INTERVAL_MS, fixedDelay = RETRY_INTERVAL_MS) + public void enrollWhenReady() { + if (enrolled.get()) return; + try { + FreshTenantCreationEvidence creation = enroll(); + enrolled.set(true); + LOG.info( + "Run-owned fixture tenant {} enrolled with its demo entitlement", + creation.canonicalTenantId()); + } catch (IOException | RuntimeException notYet) { + LOG.warn("Run-owned fixture tenant enrollment not complete yet: {}", notYet.toString()); + } + } + + public boolean enrolled() { + return enrolled.get(); + } + + FreshTenantCreationEvidence enroll() throws IOException { + var capability = RunOwnedInitialAdmissionFixtureWireCodec.parseCapability(read(capabilityPath)); + if (!runId.equals(capability.runId()) + || !composeProjectName.equals(capability.composeProjectName())) { + throw new IllegalStateException("Fixture capability belongs to another run"); + } + if (!Files.exists(receiptPath)) { + throw new IllegalStateException("Game Design has not published the fixture receipt yet"); + } + var receipt = + RunOwnedInitialAdmissionFixtureWireCodec.parseSourceReceipt(read(receiptPath), capability); + FreshTenantCreationEvidence located = Objects.requireNonNull(receipt.creationEvidence()); + // The receipt is an untrusted locator; the import uses Game Design's authenticated readback. + FreshTenantCreationEvidence creation = + enrollment.enroll(located.creationRequestId(), located.requestDigest()); + var request = + new DemoTenantEntitlementRequest( + UUID.nameUUIDFromBytes( + ("firemud.run-owned-fixture.demo-entitlement:" + creation.creationRequestId()) + .getBytes(StandardCharsets.UTF_8)), + creation.canonicalTenantId(), + creation.creationRequestId(), + creation.requestDigest(), + null, + null, + null, + true, + true, + true, + true, + FIXTURE_QUOTAS); + transaction.executeWithoutResult(status -> demos.provision(request, creation)); + return creation; + } + + private static byte[] read(Path path) throws IOException { + try (InputStream input = Files.newInputStream(path)) { + byte[] bytes = input.readNBytes(MAX_FILE_BYTES + 1); + if (bytes.length > MAX_FILE_BYTES) { + throw new IllegalStateException("Fixture file exceeds its size bound: " + path); + } + return bytes; + } + } + + private static String requireText(String value, String name) { + if (value == null || value.isBlank()) { + throw new IllegalArgumentException(name + " is required"); + } + return value; + } +} diff --git a/services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/AccountPlayerAdmissionEntitlementOwner.java b/services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/AccountPlayerAdmissionEntitlementOwner.java index cbf025174b..dcb9aef626 100644 --- a/services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/AccountPlayerAdmissionEntitlementOwner.java +++ b/services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/AccountPlayerAdmissionEntitlementOwner.java @@ -106,8 +106,13 @@ public AccountPlayerAdmissionEntitlementOwner( this.issuances = Objects.requireNonNull(issuances); this.memberships = Objects.requireNonNull(memberships); this.scopes = Objects.requireNonNull(scopes); - this.hosting = Objects.requireNonNull(hosting); - this.observer = Objects.requireNonNull(observer); + if ((hosting == null) != (observer == null)) { + throw new IllegalArgumentException( + "Paid hosting sources are composed together or not at all"); + } + // Null when checkout receiving is not composed; paid tenants then fail closed. + this.hosting = hosting; + this.observer = observer; this.demos = Objects.requireNonNull(demos); this.sources = Objects.requireNonNull(sources); this.targets = Objects.requireNonNull(targets); @@ -156,6 +161,9 @@ public RuntimePlayerAdmissionEntitlementEvidence evaluate( private RuntimePlayerAdmissionEntitlementEvidence capturePaidSources( Request request, VerifiedCaller caller, Prepared prepared) { + if (hosting == null) { + throw unavailable(); + } var fence = inSourceTransaction( () -> { diff --git a/services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/AccountPublicBootstrapEntitlementOwner.java b/services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/AccountPublicBootstrapEntitlementOwner.java index 1f3cb4c545..d21a58c91c 100644 --- a/services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/AccountPublicBootstrapEntitlementOwner.java +++ b/services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/AccountPublicBootstrapEntitlementOwner.java @@ -38,7 +38,8 @@ public AccountPublicBootstrapEntitlementOwner( PlatformTransactionManager transactions, Clock clock) { this.sources = Objects.requireNonNull(sources); - this.hosting = Objects.requireNonNull(hosting); + // Null when checkout receiving is not composed; paid tenants then fail closed. + this.hosting = hosting; this.demos = Objects.requireNonNull(demos); this.clock = Objects.requireNonNull(clock); transaction = new TransactionTemplate(Objects.requireNonNull(transactions)); @@ -69,8 +70,9 @@ public Evaluation evaluate(UUID tenantId) { Evaluation evaluation = switch (prepared.selection().kind()) { case PAID_HOSTING -> - hosting.readCurrentAndCapture( - tenantId, receipt -> capturePaid(tenantId, prepared.selection(), receipt)); + requirePaidHosting() + .readCurrentAndCapture( + tenantId, receipt -> capturePaid(tenantId, prepared.selection(), receipt)); case NON_PAID_DEMO -> Objects.requireNonNull( transaction.execute(status -> captureDemo(tenantId, prepared))); @@ -82,6 +84,13 @@ public Evaluation evaluate(UUID tenantId) { } } + private AccountHostingSubscriptionLifecycleService requirePaidHosting() { + if (hosting == null) { + throw new IllegalStateException("Paid hosting entitlement source is not composed"); + } + return hosting; + } + private Evaluation capturePaid( UUID tenantId, SourceSelection selected, AccountHostingSubscriptionCurrentReceipt receipt) { requireSourceTransaction(); diff --git a/services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/FreshTenantIdentityEnrollmentService.java b/services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/FreshTenantIdentityEnrollmentService.java index c711ac879a..3d0978955f 100644 --- a/services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/FreshTenantIdentityEnrollmentService.java +++ b/services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/FreshTenantIdentityEnrollmentService.java @@ -3,6 +3,7 @@ import edu.umd.cs.findbugs.annotations.SuppressFBWarnings; import java.util.Objects; import java.util.UUID; +import java.util.function.Consumer; import net.firedevops.firemud.accountservice.client.GameDesignFreshTenantIdentityClient; import net.firedevops.firemud.accountservice.repository.AccountAuthorityGenerationRepository; import net.firedevops.firemud.accountservice.repository.FreshTenantIdentityAssociationRepository; @@ -44,6 +45,18 @@ public FreshTenantIdentityEnrollmentService( * imports, reads back, and initializes the UUID tenant generation without resetting it. */ public FreshTenantCreationEvidence enroll(UUID creationRequestId, String expectedDigest) { + return enrollAndInitialize(creationRequestId, expectedDigest, ignored -> {}); + } + + /** + * Runs Account-owned initialization in the same transaction as the authenticated identity import. + * The initializer must verify any additional source and handle exact replays. + */ + public FreshTenantCreationEvidence enrollAndInitialize( + UUID creationRequestId, + String expectedDigest, + Consumer initializeAccount) { + Objects.requireNonNull(initializeAccount, "Account owner initialization is required"); if (creationRequestId == null || creationRequestId.equals(new UUID(0L, 0L)) || !GameTenantCreationDigest.isDigest(expectedDigest)) { @@ -81,6 +94,7 @@ public FreshTenantCreationEvidence enroll(UUID creationRequestId, String expecte "Fresh Account tenant association readback differs from owner evidence"); } generationRepository.initializeTenantIfAbsent(readback.canonicalTenantId()); + initializeAccount.accept(readback); return readback; }); return Objects.requireNonNull( diff --git a/services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/impl/AccountGrpcService.java b/services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/impl/AccountGrpcService.java index eb469c7a02..e6ab7861a4 100644 --- a/services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/impl/AccountGrpcService.java +++ b/services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/impl/AccountGrpcService.java @@ -97,6 +97,35 @@ void canonicalGameplayReceiver(ObjectProvider + owner) { + var available = owner.getIfAvailable(); + tenantCapacity = + available == null + ? null + : new AccountTenantCapacityGrpcService(available, workloadNamespace); + } + + @Override + public void commitTenantCapacityAdmission( + net.firedevops.firemud.account.v1.CommitTenantCapacityAdmissionRequest request, + StreamObserver + observer) { + if (tenantCapacity == null) { + observer.onError( + io.grpc.Status.UNIMPLEMENTED + .withDescription("Tenant capacity admission is not composed") + .asRuntimeException()); + return; + } + tenantCapacity.commitTenantCapacityAdmission(request, observer); + } + public AccountGrpcService(PingService pingService, AccountService accountService) { this(pingService, accountService, null, null); } diff --git a/services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/impl/AccountServiceImpl.java b/services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/impl/AccountServiceImpl.java index c32b739f58..32e6309c42 100644 --- a/services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/impl/AccountServiceImpl.java +++ b/services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/impl/AccountServiceImpl.java @@ -518,14 +518,18 @@ public void setCanonicalScopeConsumers( if (!net.firedevops.firemud.common.grpc.GrpcPeerIdentity.isValidNamespace(namespace)) { throw new IllegalArgumentException("Canonical Account workload namespace required"); } + if ((hosting == null) != (observer == null)) { + throw new IllegalArgumentException( + "Paid hosting sources are composed together or not at all"); + } canonicalScopeConsumers = new CanonicalScopeConsumers( Objects.requireNonNull(reader), Objects.requireNonNull(targets), Objects.requireNonNull(tenantSources), Objects.requireNonNull(demos), - Objects.requireNonNull(hosting), - Objects.requireNonNull(observer), + hosting, + observer, Objects.requireNonNull(firstJoin), namespace, Objects.requireNonNull(clock)); @@ -639,7 +643,7 @@ private CanonicalJoinPreparation prepareCanonicalJoin( operation, source, null, - consumers.hosting().prepareCurrentRead(scope.tenantId())); + consumers.paidHosting().prepareCurrentRead(scope.tenantId())); case NON_PAID_DEMO -> new CanonicalJoinPreparation( operation, source, consumers.demos().readCurrent(scope.tenantId()), null); @@ -683,7 +687,7 @@ private CanonicalJoinResult commitCanonicalJoin( final long entitlementVersion; if (prepared.fence() != null) { AccountHostingSubscriptionCurrentReceipt receipt = - consumers.hosting().readCurrent(prepared.fence(), observation); + consumers.paidHosting().readCurrent(prepared.fence(), observation); gameplayAvailable = receipt.gameplayAvailable(); allowPublicJoin = receipt.allowPublicJoin(); entitlementVersion = receipt.entitlementVersion(); @@ -718,7 +722,7 @@ private CanonicalJoinResult commitCanonicalJoin( scope, requestId, callerBinding, - prepared.fence() == null ? null : consumers.hosting(), + prepared.fence() == null ? null : consumers.paidHosting(), prepared.fence(), observation); requireCanonicalScopeFresh(consumers, scope); @@ -772,7 +776,26 @@ private record CanonicalScopeConsumers( StripeHostingSubscriptionObserver observer, AccountCanonicalFirstJoinTerminalCoordinator firstJoin, String namespace, - Clock clock) {} + Clock clock) { + /** + * Paid hosting is composed only with checkout receiving; without it paid tenants fail closed. + */ + AccountHostingSubscriptionLifecycleRepository paidHosting() { + if (hosting == null) { + throw new AuthenticationException( + "ENTITLEMENT_UNAVAILABLE", "Paid hosting entitlement source is not composed"); + } + return hosting; + } + + StripeHostingSubscriptionObserver paidObserver() { + if (observer == null) { + throw new AuthenticationException( + "ENTITLEMENT_UNAVAILABLE", "Paid hosting provider observer is not composed"); + } + return observer; + } + } private record CanonicalJoinPreparation( CanonicalJoinOperationEvidence operation, @@ -809,7 +832,7 @@ private BootstrapCharacterAuthority prepareBootstrapCharacterAuthority( ? consumers.demos().readCurrent(scope.tenantId()) : null, source.kind() == AccountTenantAuthorityEventRepository.SourceKind.PAID_HOSTING - ? consumers.hosting().prepareCurrentRead(scope.tenantId()) + ? consumers.paidHosting().prepareCurrentRead(scope.tenantId()) : null, consumers.clock().instant()); } catch (RuntimeException failure) { @@ -864,7 +887,7 @@ private void requireBootstrapCharacterAuthority( throw new IllegalStateException("Bootstrap entitlement source changed"); } if (prepared.fence() != null) { - var receipt = consumers.hosting().readCurrent(prepared.fence(), observation); + var receipt = consumers.paidHosting().readCurrent(prepared.fence(), observation); gameplayAvailable = receipt.gameplayAvailable(); allowPublicJoin = receipt.allowPublicJoin(); } else { @@ -913,7 +936,7 @@ private StripeHostingSubscriptionObserver.Result observeBootstrapCharacterSource CanonicalScopeConsumers consumers, BootstrapCharacterAuthority prepared) { if (prepared.fence() == null) return null; try { - return consumers.observer().observe(prepared.fence().binding()); + return consumers.paidObserver().observe(prepared.fence().binding()); } catch (RuntimeException failure) { throw new AuthenticationException( "ENTITLEMENT_UNAVAILABLE", "Bootstrap provider source is unavailable", failure); @@ -1095,7 +1118,7 @@ private JoinPublicProductionResult joinCanonicalPublicProduction( observation = prepared.fence() == null ? null - : consumers.observer().observe(prepared.fence().binding()); + : consumers.paidObserver().observe(prepared.fence().binding()); if (!target.equals(readCanonicalScopeTarget(consumers, scope))) { throw new AuthenticationException("CONNECT_SCOPE_MISMATCH", STALE_CONNECT_SCOPE_MESSAGE); } diff --git a/services/account-service/src/main/resources/application.yml b/services/account-service/src/main/resources/application.yml index 42ff8731f9..88bd60ebc9 100644 --- a/services/account-service/src/main/resources/application.yml +++ b/services/account-service/src/main/resources/application.yml @@ -114,6 +114,15 @@ firemud: - account.v1.AccountService/GetTenantEntitlementsForRuntime - account.v1.AccountService/IssueDirectTextConnectScope - account.v1.AccountService/JoinPublicProductionMembership + - account.v1.AccountService/CommitTenantCapacityAdmission + - account.v1.AccountPlayerAdmissionEntitlementReadService/ReadPlayerAdmissionEntitlement + - account.v1.AccountGameplayAdmissionLeaseService/AbortNeverAdmittedGameplayAdmissionLease + - account.v1.AccountGameplayAdmissionLeaseService/AcquireGameplayAdmissionLease + - account.v1.AccountGameplayAdmissionLeaseService/FinalizeGameplayAdmissionLease + - account.v1.AccountGameplayAdmissionLeaseService/ReadGameplayAdmissionLease + - account.v1.AccountGameplayAdmissionLeaseService/AbortGameplayAdmissionLease + - account.v1.AccountGameplayAdmissionLeaseService/IssueOriginalNewGameplayCredential + - account.v1.AccountGameplayAdmissionLeaseService/ConfirmOriginalNewGameplayAdmission - account.v1.RuntimeAccountIdentityService/ResolveRuntimeAccountIdentity - account.v1.AccountActorStagingEligibilityService/ResolvePreseededActorStagingEligibility - account.v1.StartSessionOperatorAuthorizationService/IssueHumanOperatorAuthorizationReference diff --git a/services/account-service/src/main/resources/db/migration/V1048__run_owned_fixture_player_capacity_birth.sql b/services/account-service/src/main/resources/db/migration/V1048__run_owned_fixture_player_capacity_birth.sql new file mode 100644 index 0000000000..d727713d5c --- /dev/null +++ b/services/account-service/src/main/resources/db/migration/V1048__run_owned_fixture_player_capacity_birth.sql @@ -0,0 +1,138 @@ +-- The run-owned smoke fixture is created by Game Design without a human creator Account. +-- Only the Account transaction importing that exact fresh fixture can establish player usage. +CREATE TABLE account_run_owned_fixture_capacity_birth ( + tenant_uuid UUID PRIMARY KEY + REFERENCES account_fresh_tenant_identity_associations(canonical_tenant_id), + fixture_operation_id UUID NOT NULL UNIQUE, + run_id VARCHAR(128) NOT NULL CHECK (run_id ~ '^[a-z0-9][a-z0-9-]*$'), + compose_project VARCHAR(128) NOT NULL UNIQUE, + creation_evidence_digest VARCHAR(71) NOT NULL + CHECK (creation_evidence_digest ~ '^sha256:[0-9a-f]{64}$'), + fixture_policy_evidence_digest VARCHAR(71) NOT NULL + CHECK (fixture_policy_evidence_digest ~ '^sha256:[0-9a-f]{64}$'), + CHECK (compose_project = 'firemud-smoke-' || run_id + OR (run_id ~ '^gha-[0-9a-f]{64}$' AND compose_project ~ '^smoke-full-[0-9]+-[0-9]+$')) +); + +ALTER TABLE account_tenant_capacity_usage + ALTER COLUMN bootstrap_request_id DROP NOT NULL; +ALTER TABLE account_tenant_capacity_usage + ADD COLUMN fixture_birth_tenant_uuid UUID + REFERENCES account_run_owned_fixture_capacity_birth(tenant_uuid); +ALTER TABLE account_tenant_capacity_usage + ADD CONSTRAINT account_tenant_capacity_has_one_birth_source CHECK ( + (bootstrap_request_id IS NOT NULL AND fixture_birth_tenant_uuid IS NULL) + OR (bootstrap_request_id IS NULL AND fixture_birth_tenant_uuid IS NOT NULL + AND fixture_birth_tenant_uuid = tenant_uuid AND owner_service = 'game-session-service') + ); + +-- [jooq ignore start] +CREATE FUNCTION account_tenant_capacity_has_current_birth(usage_row account_tenant_capacity_usage) +RETURNS BOOLEAN LANGUAGE SQL AS $$ + SELECT EXISTS ( + SELECT 1 FROM account_fresh_tenant_identity_associations birth + WHERE birth.canonical_tenant_id = usage_row.tenant_uuid + AND birth.evidence_digest = usage_row.creation_evidence_digest + AND birth.capacity_birth_transaction = pg_current_xact_id()::TEXT + AND ( + (usage_row.fixture_birth_tenant_uuid IS NULL AND EXISTS ( + SELECT 1 FROM account_tenant_creation_bootstrap_operations bootstrap + WHERE bootstrap.request_id = usage_row.bootstrap_request_id + AND bootstrap.tenant_uuid = usage_row.tenant_uuid + AND bootstrap.status = 'COMMITTED' + AND bootstrap.gameplay_admission_allowed IS FALSE + AND bootstrap.baseline_event_sequence = 0 + AND bootstrap.creation_operation_id = birth.operation_id + )) + OR (usage_row.bootstrap_request_id IS NULL + AND usage_row.fixture_birth_tenant_uuid = birth.canonical_tenant_id + AND usage_row.owner_service = 'game-session-service' + AND birth.target_namespace = 'dev' + AND EXISTS ( + SELECT 1 FROM account_run_owned_fixture_capacity_birth fixture + WHERE fixture.tenant_uuid = birth.canonical_tenant_id + AND fixture.fixture_operation_id = birth.creation_request_id + AND fixture.creation_evidence_digest = birth.evidence_digest + )) + ) + ); +$$; + +CREATE OR REPLACE FUNCTION account_tenant_capacity_usage_insert_guard() RETURNS TRIGGER LANGUAGE plpgsql AS $$ +BEGIN + IF NEW.held_units <> 0 OR NEW.used_units <> 0 OR NEW.usage_revision <> 1 + OR NOT account_tenant_capacity_has_current_birth(NEW) THEN + RAISE EXCEPTION 'Capacity usage initialization requires same-transaction new-tenant birth' + USING ERRCODE = '23514'; + END IF; + RETURN NEW; +END; +$$; + +CREATE OR REPLACE FUNCTION account_tenant_capacity_usage_update_guard() RETURNS TRIGGER LANGUAGE plpgsql AS $$ +BEGIN + IF NEW.tenant_uuid IS DISTINCT FROM OLD.tenant_uuid OR NEW.owner_service IS DISTINCT FROM OLD.owner_service + OR NEW.bootstrap_request_id IS DISTINCT FROM OLD.bootstrap_request_id + OR NEW.fixture_birth_tenant_uuid IS DISTINCT FROM OLD.fixture_birth_tenant_uuid + OR NEW.creation_evidence_digest IS DISTINCT FROM OLD.creation_evidence_digest + OR NEW.usage_revision <> OLD.usage_revision + 1 THEN + RAISE EXCEPTION 'Capacity usage identity is immutable and revision must advance once' USING ERRCODE = '23514'; + END IF; + RETURN NEW; +END; +$$; + +CREATE OR REPLACE FUNCTION account_tenant_capacity_conservation_guard() RETURNS TRIGGER LANGUAGE plpgsql AS $$ +BEGIN + IF TG_OP IN ('DELETE', 'TRUNCATE') OR pg_trigger_depth() < 2 THEN + RAISE EXCEPTION 'Capacity conservation is writable only by its nested owner triggers' + USING ERRCODE = '23514'; + END IF; + IF TG_OP = 'INSERT' THEN + IF NEW.held_units <> 0 OR NEW.used_units <> 0 OR NOT EXISTS ( + SELECT 1 FROM account_tenant_capacity_usage usage + WHERE usage.tenant_uuid = NEW.tenant_uuid AND usage.owner_service = NEW.owner_service + AND usage.held_units = 0 AND usage.used_units = 0 AND usage.usage_revision = 1 + AND account_tenant_capacity_has_current_birth(usage)) THEN + RAISE EXCEPTION 'Capacity conservation birth requires exact same-transaction zero usage' + USING ERRCODE = '23514'; + END IF; + ELSIF NEW.tenant_uuid IS DISTINCT FROM OLD.tenant_uuid + OR NEW.owner_service IS DISTINCT FROM OLD.owner_service + OR NEW.used_units < OLD.used_units + OR (NEW.held_units > OLD.held_units AND NEW.used_units <> OLD.used_units) + OR (NEW.used_units > OLD.used_units + AND OLD.held_units::NUMERIC - NEW.held_units <> NEW.used_units::NUMERIC - OLD.used_units) THEN + RAISE EXCEPTION 'Capacity conservation permits only immutable-key reservation deltas' + USING ERRCODE = '23514'; + END IF; + RETURN NEW; +END; +$$; + +CREATE FUNCTION account_run_owned_fixture_capacity_birth_guard() RETURNS TRIGGER LANGUAGE plpgsql AS $$ +BEGIN + IF TG_OP <> 'INSERT' THEN + RAISE EXCEPTION 'Run-owned fixture capacity birth is immutable' USING ERRCODE = '23514'; + END IF; + IF EXISTS (SELECT 1 FROM account_tenant_membership + WHERE tenant_uuid = NEW.tenant_uuid AND gameplay_admission_allowed IS TRUE) THEN + RAISE EXCEPTION 'Run-owned fixture player usage is not demonstrably empty' USING ERRCODE = '23514'; + END IF; + + -- The existing usage and conservation triggers check the same-transaction owner source. + -- The fixture does not establish a World Management capacity baseline. + INSERT INTO account_tenant_capacity_usage + (tenant_uuid, owner_service, fixture_birth_tenant_uuid, creation_evidence_digest, + held_units, used_units, usage_revision) + VALUES (NEW.tenant_uuid, 'game-session-service', NEW.tenant_uuid, NEW.creation_evidence_digest, 0, 0, 1); + RETURN NULL; +END; +$$; +CREATE TRIGGER account_run_owned_fixture_capacity_birth_owner + AFTER INSERT OR UPDATE OR DELETE ON account_run_owned_fixture_capacity_birth + FOR EACH ROW EXECUTE FUNCTION account_run_owned_fixture_capacity_birth_guard(); +CREATE TRIGGER account_run_owned_fixture_capacity_birth_no_truncate + BEFORE TRUNCATE ON account_run_owned_fixture_capacity_birth + FOR EACH STATEMENT EXECUTE FUNCTION account_run_owned_fixture_capacity_birth_guard(); +-- [jooq ignore stop] diff --git a/services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/repository/AccountCapacityEvaluationRetentionInspectionPostgresIntegrationTest.java b/services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/repository/AccountCapacityEvaluationRetentionInspectionPostgresIntegrationTest.java index 3ecd7bf5e4..f3fdfbef72 100644 --- a/services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/repository/AccountCapacityEvaluationRetentionInspectionPostgresIntegrationTest.java +++ b/services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/repository/AccountCapacityEvaluationRetentionInspectionPostgresIntegrationTest.java @@ -273,6 +273,7 @@ void populatedMixedCohortKeepsExactImagesAcrossBoundedPolicyAndUnqualifiedReads( var beforeMigration = rowImages(dsl); var guards = guardImages(dsl); configure(data, schema).load().migrate(); + assertRetainedUsageHasNoFixtureBirth(dsl); assertThat(rowImages(dsl)).isEqualTo(beforeMigration); assertThat(guardImages(dsl)).isEqualTo(guards); var conservation = @@ -382,6 +383,7 @@ private static void verifyForwardMigration(boolean populated) { configure(data, schema).load().migrate(); + assertRetainedUsageHasNoFixtureBirth(dsl); assertThat(rowImages(dsl)).isEqualTo(beforeRows); assertThat(guardImages(dsl)).isEqualTo(beforeGuards); assertThat( @@ -482,11 +484,20 @@ private static List rowImages(DSLContext dsl) { + "FROM account_tenant_capacity_recovery_evidence r UNION ALL " + "SELECT 'reservation', (to_jsonb(r) || jsonb_build_object('xmin', r.xmin::text))::text " + "FROM account_tenant_capacity_reservations r UNION ALL " - + "SELECT 'usage', (to_jsonb(u) || jsonb_build_object('xmin', u.xmin::text))::text " + + "SELECT 'usage', ((to_jsonb(u) - 'fixture_birth_tenant_uuid') " + + "|| jsonb_build_object('xmin', u.xmin::text))::text " + "FROM account_tenant_capacity_usage u) retained ORDER BY family, image") .getValues("image", String.class); } + private static void assertRetainedUsageHasNoFixtureBirth(DSLContext dsl) { + assertThat( + dsl.fetchCount( + DSL.table("account_tenant_capacity_usage"), + DSL.field("fixture_birth_tenant_uuid").isNotNull())) + .isZero(); + } + private static List guardImages(DSLContext dsl) { return dsl.fetch( "SELECT pg_get_triggerdef(oid) AS definition FROM pg_trigger WHERE NOT tgisinternal " diff --git a/services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/repository/AccountTenantCapacityMigrationPostgresIntegrationTest.java b/services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/repository/AccountTenantCapacityMigrationPostgresIntegrationTest.java index 1b1b56c1c8..da0c637df0 100644 --- a/services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/repository/AccountTenantCapacityMigrationPostgresIntegrationTest.java +++ b/services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/repository/AccountTenantCapacityMigrationPostgresIntegrationTest.java @@ -135,6 +135,96 @@ void freshAndPopulated1040Through1041UpgradesPreserveRowsHistoryAndScopeReservat verify1040Upgrade(true); } + @Test + void onlyAnExactFreshFixtureBirthInitializesPlayerUsageAndConservation() { + String schema = "capacity_fixture_" + UUID.randomUUID().toString().replace("-", ""); + var admin = new JdbcTemplate(POSTGRES.dataSource()); + admin.execute("CREATE SCHEMA " + schema); + var data = POSTGRES.dataSource(schema); + try { + configureFlyway(data, schema, "1047").migrate(); + var dsl = DSL.using(new TransactionAwareDataSourceProxy(data), SQLDialect.POSTGRES); + var transaction = new TransactionTemplate(new DataSourceTransactionManager(data)); + var fixtures = new FreshTenantIdentityAssociationRepository(dsl, "dev"); + var retained = source("dev"); + transaction.executeWithoutResult(status -> fixtures.importVerified(retained)); + + configureFlyway(data, schema, "1048").migrate(); + var retainedReadback = + transaction.execute(status -> fixtures.read(retained.canonicalTenantId())); + assertThat(retainedReadback).contains(retained); + assertThatThrownBy( + () -> + transaction.executeWithoutResult( + status -> { + fixtures.importVerified(retained); + insertFixtureBirth(dsl, retained, retained.creationRequestId()); + })) + .hasRootCauseInstanceOf(SQLException.class); + assertThat(dsl.fetchCount(DSL.table("account_run_owned_fixture_capacity_birth"))).isZero(); + assertThat(dsl.fetchCount(DSL.table("account_tenant_capacity_usage"))).isZero(); + + var fresh = source("dev"); + assertThatThrownBy( + () -> + transaction.executeWithoutResult( + status -> { + fixtures.importVerified(fresh); + insertFixtureBirth(dsl, fresh, UUID.randomUUID()); + })) + .hasRootCauseInstanceOf(SQLException.class); + var rolledBack = transaction.execute(status -> fixtures.read(fresh.canonicalTenantId())); + assertThat(rolledBack).isEmpty(); + + for (int attempt = 0; attempt < 2; attempt++) { + transaction.executeWithoutResult( + status -> { + fixtures.importVerified(fresh); + insertFixtureBirth(dsl, fresh, fresh.creationRequestId()); + }); + } + assertThat( + dsl.fetch( + "SELECT owner_service, held_units, used_units, usage_revision" + + " FROM account_tenant_capacity_usage" + + " WHERE fixture_birth_tenant_uuid = ?", + fresh.canonicalTenantId()) + .map(Record::intoList)) + .containsExactly(List.of("game-session-service", 0L, 0L, 1L)); + assertThat( + dsl.fetch( + "SELECT owner_service, held_units, used_units" + + " FROM account_tenant_capacity_conservation WHERE tenant_uuid = ?", + fresh.canonicalTenantId()) + .map(Record::intoList)) + .containsExactly(List.of("game-session-service", 0L, 0L)); + assertThat(dsl.fetchCount(DSL.table("account_run_owned_fixture_capacity_birth"))).isOne(); + assertThatThrownBy( + () -> + dsl.execute( + "UPDATE account_run_owned_fixture_capacity_birth SET run_id = run_id")) + .hasRootCauseInstanceOf(SQLException.class); + } finally { + admin.execute("DROP SCHEMA " + schema + " CASCADE"); + } + } + + private static void insertFixtureBirth( + DSLContext dsl, FreshTenantCreationEvidence source, UUID fixtureOperationId) { + String run = source.canonicalTenantId().toString(); + dsl.execute( + "INSERT INTO account_run_owned_fixture_capacity_birth" + + " (tenant_uuid, fixture_operation_id, run_id, compose_project, creation_evidence_digest," + + " fixture_policy_evidence_digest) VALUES (?, ?, ?, ?, ?, ?)" + + " ON CONFLICT (tenant_uuid) DO NOTHING", + source.canonicalTenantId(), + fixtureOperationId, + run, + "firemud-smoke-" + run, + source.evidenceDigest(), + "sha256:" + "1".repeat(64)); + } + private static void verify1040Upgrade(boolean populated) { String schema = "capacity_trigger_" + UUID.randomUUID().toString().replace("-", ""); new JdbcTemplate(POSTGRES.dataSource()).execute("CREATE SCHEMA " + schema); @@ -734,13 +824,18 @@ private static Completion completion(StoredOperation operation) { } private static FreshTenantCreationEvidence source() { + return source("prod"); + } + + private static FreshTenantCreationEvidence source(String namespace) { UUID request = UUID.randomUUID(), operation = UUID.randomUUID(), tenant = UUID.randomUUID(); String slug = "capacity-" + UUID.randomUUID().toString().substring(0, 8); - String digest = GameTenantCreationDigest.requestDigest("prod", request, slug, "Capacity", null); + String digest = + GameTenantCreationDigest.requestDigest(namespace, request, slug, "Capacity", null); long row = Math.abs((long) tenant.hashCode()) + 1; return new FreshTenantCreationEvidence( 1, - "prod", + namespace, request, operation, digest, @@ -749,6 +844,6 @@ private static FreshTenantCreationEvidence source() { slug, "NEW_GAME_ROW", GameTenantCreationDigest.evidenceDigest( - "prod", request, operation, digest, tenant, row, slug, "NEW_GAME_ROW")); + namespace, request, operation, digest, tenant, row, slug, "NEW_GAME_ROW")); } } diff --git a/services/common-platform-core/src/main/java/net/firedevops/firemud/common/smoke/RunOwnedInitialAdmissionFixtureWireCodec.java b/services/common-platform-core/src/main/java/net/firedevops/firemud/common/smoke/RunOwnedInitialAdmissionFixtureWireCodec.java index 1a7002584f..9b80ad9d00 100644 --- a/services/common-platform-core/src/main/java/net/firedevops/firemud/common/smoke/RunOwnedInitialAdmissionFixtureWireCodec.java +++ b/services/common-platform-core/src/main/java/net/firedevops/firemud/common/smoke/RunOwnedInitialAdmissionFixtureWireCodec.java @@ -57,7 +57,7 @@ public final class RunOwnedInitialAdmissionFixtureWireCodec { public static final String REALM_SLUG = "production"; public static final String REALM_DISPLAY_NAME = "Live Realm"; public static final String STATE_SCOPE = "SHARED"; - public static final String CHARACTER_CREATION_POLICY = "ALLOW_NEW"; + public static final String CHARACTER_CREATION_POLICY = "PRESEEDED_ONLY"; public static final String FIXTURE_POLICY_SEAL_SCHEMA = "firemud.run-owned-fixture-policy-seal.v1"; diff --git a/services/common-platform-core/src/main/java/net/firedevops/firemud/common/world/WorldCanonicalInitialAdmissionHoldState.java b/services/common-platform-core/src/main/java/net/firedevops/firemud/common/world/WorldCanonicalInitialAdmissionHoldState.java index 4c72e7064d..4c5721d391 100644 --- a/services/common-platform-core/src/main/java/net/firedevops/firemud/common/world/WorldCanonicalInitialAdmissionHoldState.java +++ b/services/common-platform-core/src/main/java/net/firedevops/firemud/common/world/WorldCanonicalInitialAdmissionHoldState.java @@ -25,13 +25,17 @@ public record WorldCanonicalInitialAdmissionHoldState( WorldCanonicalInitialAdmissionHold.HoldIdentity holdIdentity, HoldStatus holdStatus, - WorldCanonicalInstanceLifecycleEvidence lifecycleEvidence) { + WorldCanonicalInstanceLifecycleEvidence lifecycleEvidence, + WorldRunOwnedFixtureLifecycleEvidence fixtureLifecycleEvidence) { public static final String SCHEMA = "world-canonical-initial-admission-hold-state/v1"; public static final int MAX_CANONICAL_BYTES = 4 * 1024 * 1024; private static final int MAX_HOLD_IDENTITY_BYTES = 64 * 1024; private static final int MAX_LIFECYCLE_EVIDENCE_BYTES = 2 * 1024 * 1024; private static final Set FIELDS = Set.of("schema", "holdIdentityBytesBase64", "holdStatus", "lifecycleEvidenceBytesBase64"); + private static final Set FIXTURE_FIELDS = + Set.of( + "schema", "holdIdentityBytesBase64", "holdStatus", "fixtureLifecycleEvidenceBytesBase64"); private static final JsonMapper JSON = JsonMapper.builder() .enable(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES) @@ -42,14 +46,73 @@ public record WorldCanonicalInitialAdmissionHoldState( public WorldCanonicalInitialAdmissionHoldState { Objects.requireNonNull(holdIdentity, "holdIdentity"); Objects.requireNonNull(holdStatus, "holdStatus"); - Objects.requireNonNull(lifecycleEvidence, "lifecycleEvidence"); - requireTargetBinding(holdIdentity, lifecycleEvidence); + if ((lifecycleEvidence == null) == (fixtureLifecycleEvidence == null)) { + throw new IllegalArgumentException( + "Canonical World hold state requires exactly one Human or fixture lifecycle observation"); + } + requireTargetBinding( + holdIdentity, lifecycleRequestOf(lifecycleEvidence, fixtureLifecycleEvidence)); + byte[] lifecycleBytes = + lifecycleEvidence != null + ? lifecycleEvidence.canonicalBytes() + : fixtureLifecycleEvidence.canonicalBytes(); if (holdIdentity.canonicalBytes().length > MAX_HOLD_IDENTITY_BYTES - || lifecycleEvidence.canonicalBytes().length > MAX_LIFECYCLE_EVIDENCE_BYTES) { + || lifecycleBytes.length > MAX_LIFECYCLE_EVIDENCE_BYTES) { throw new IllegalArgumentException("Canonical World hold-state evidence exceeds its limit"); } } + /** Existing Human hold-state constructor retained at its call sites. */ + public WorldCanonicalInitialAdmissionHoldState( + WorldCanonicalInitialAdmissionHold.HoldIdentity holdIdentity, + HoldStatus holdStatus, + WorldCanonicalInstanceLifecycleEvidence lifecycleEvidence) { + this( + holdIdentity, + holdStatus, + Objects.requireNonNull(lifecycleEvidence, "lifecycleEvidence"), + null); + } + + /** Run-owned fixture hold state, observed with its fixture lifecycle evidence. */ + public static WorldCanonicalInitialAdmissionHoldState runOwnedFixture( + WorldCanonicalInitialAdmissionHold.HoldIdentity holdIdentity, + HoldStatus holdStatus, + WorldRunOwnedFixtureLifecycleEvidence fixtureLifecycleEvidence) { + return new WorldCanonicalInitialAdmissionHoldState( + holdIdentity, + holdStatus, + null, + Objects.requireNonNull(fixtureLifecycleEvidence, "fixtureLifecycleEvidence")); + } + + public boolean isRunOwnedFixture() { + return fixtureLifecycleEvidence != null; + } + + /** The lifecycle read request echoed by whichever owner observation this state carries. */ + public WorldCanonicalInstanceLifecycleEvidence.Request lifecycleRequest() { + return lifecycleRequestOf(lifecycleEvidence, fixtureLifecycleEvidence); + } + + public String lifecycleStatus() { + return lifecycleEvidence != null + ? lifecycleEvidence.lifecycleStatus() + : fixtureLifecycleEvidence.lifecycleStatus(); + } + + public long lifecycleEpoch() { + return lifecycleEvidence != null + ? lifecycleEvidence.lifecycleEpoch() + : fixtureLifecycleEvidence.lifecycleEpoch(); + } + + private static WorldCanonicalInstanceLifecycleEvidence.Request lifecycleRequestOf( + WorldCanonicalInstanceLifecycleEvidence human, + WorldRunOwnedFixtureLifecycleEvidence fixture) { + return human != null ? human.request() : fixture.request(); + } + /** * Exact canonical readback bytes, including immutable identity and complete current lifecycle. */ @@ -60,9 +123,15 @@ public byte[] canonicalBytes() { "holdIdentityBytesBase64", Base64.getEncoder().encodeToString(holdIdentity.canonicalBytes())); value.put("holdStatus", holdStatus.name()); - value.put( - "lifecycleEvidenceBytesBase64", - Base64.getEncoder().encodeToString(lifecycleEvidence.canonicalBytes())); + if (lifecycleEvidence != null) { + value.put( + "lifecycleEvidenceBytesBase64", + Base64.getEncoder().encodeToString(lifecycleEvidence.canonicalBytes())); + } else { + value.put( + "fixtureLifecycleEvidenceBytesBase64", + Base64.getEncoder().encodeToString(fixtureLifecycleEvidence.canonicalBytes())); + } try { byte[] canonical = Rfc8785CanonicalJson.canonicalizeUtf8(JSON.writeValueAsString(value)); if (canonical.length > MAX_CANONICAL_BYTES) { @@ -81,8 +150,8 @@ public byte[] canonicalBytes() { */ public boolean isPendingAtExpectedActiveEpoch() { return holdStatus == HoldStatus.PENDING - && "ACTIVE".equals(lifecycleEvidence.lifecycleStatus()) - && lifecycleEvidence.lifecycleEpoch() == holdIdentity.request().activeLifecycleEpoch(); + && "ACTIVE".equals(lifecycleStatus()) + && lifecycleEpoch() == holdIdentity.request().activeLifecycleEpoch(); } /** Decodes only complete, canonical, bounded state and both exact nested owner records. */ @@ -93,12 +162,15 @@ public static WorldCanonicalInitialAdmissionHoldState fromStored(byte[] stored) } try { JsonNode root = JSON.readTree(strictUtf8(stored)); - requireFields(root); + boolean fixture = requireFields(root); if (!SCHEMA.equals(text(root, "schema"))) { throw new IllegalArgumentException("Unsupported canonical World hold-state schema"); } byte[] identityBytes = decodeBase64(root, "holdIdentityBytesBase64"); - byte[] lifecycleBytes = decodeBase64(root, "lifecycleEvidenceBytesBase64"); + byte[] lifecycleBytes = + decodeBase64( + root, + fixture ? "fixtureLifecycleEvidenceBytesBase64" : "lifecycleEvidenceBytesBase64"); if (identityBytes.length == 0 || identityBytes.length > MAX_HOLD_IDENTITY_BYTES || lifecycleBytes.length == 0 @@ -108,11 +180,17 @@ public static WorldCanonicalInitialAdmissionHoldState fromStored(byte[] stored) } WorldCanonicalInitialAdmissionHold.HoldIdentity identity = WorldCanonicalInitialAdmissionHold.HoldIdentity.fromStored(identityBytes); - WorldCanonicalInstanceLifecycleEvidence lifecycle = - WorldCanonicalInstanceLifecycleEvidence.fromStored(lifecycleBytes); + HoldStatus status = parseStatus(text(root, "holdStatus")); WorldCanonicalInitialAdmissionHoldState state = - new WorldCanonicalInitialAdmissionHoldState( - identity, parseStatus(text(root, "holdStatus")), lifecycle); + fixture + ? runOwnedFixture( + identity, + status, + WorldRunOwnedFixtureLifecycleEvidence.fromStored(lifecycleBytes)) + : new WorldCanonicalInitialAdmissionHoldState( + identity, + status, + WorldCanonicalInstanceLifecycleEvidence.fromStored(lifecycleBytes)); if (!Arrays.equals(stored, state.canonicalBytes())) { throw new IllegalArgumentException("Canonical World hold-state evidence is not canonical"); } @@ -124,9 +202,8 @@ public static WorldCanonicalInitialAdmissionHoldState fromStored(byte[] stored) private static void requireTargetBinding( WorldCanonicalInitialAdmissionHold.HoldIdentity identity, - WorldCanonicalInstanceLifecycleEvidence lifecycle) { + WorldCanonicalInstanceLifecycleEvidence.Request current) { var hold = identity.request(); - var current = lifecycle.request(); if (!hold.targetNamespace().equals(current.targetNamespace()) || !hold.canonicalTenantId().equals(current.canonicalTenantId()) || !hold.worldSlug().equals(current.worldSlug()) @@ -184,16 +261,17 @@ private static String text(JsonNode object, String field) { return value.textValue(); } - private static void requireFields(JsonNode object) { + /** Returns true for the fixture field set; any other shape is rejected. */ + private static boolean requireFields(JsonNode object) { if (object == null || !object.isObject()) { throw new IllegalArgumentException("Canonical World hold-state evidence must be an object"); } Set actual = new java.util.HashSet<>(); object.propertyNames().forEach(actual::add); - if (!actual.equals(FIELDS)) { - throw new IllegalArgumentException( - "Canonical World hold-state evidence has missing or unsupported fields"); - } + if (actual.equals(FIELDS)) return false; + if (actual.equals(FIXTURE_FIELDS)) return true; + throw new IllegalArgumentException( + "Canonical World hold-state evidence has missing or unsupported fields"); } public enum HoldStatus { diff --git a/services/common-platform-core/src/test/java/net/firedevops/firemud/common/smoke/RunOwnedInitialAdmissionFixtureWireCodecTest.java b/services/common-platform-core/src/test/java/net/firedevops/firemud/common/smoke/RunOwnedInitialAdmissionFixtureWireCodecTest.java index 86582e03dd..bcbcf1b01a 100644 --- a/services/common-platform-core/src/test/java/net/firedevops/firemud/common/smoke/RunOwnedInitialAdmissionFixtureWireCodecTest.java +++ b/services/common-platform-core/src/test/java/net/firedevops/firemud/common/smoke/RunOwnedInitialAdmissionFixtureWireCodecTest.java @@ -357,7 +357,7 @@ private static void assertInvalidReceiptBytes(byte[] bytes) { private static String validCapabilityJson() { return """ - {"schema":"%s","runId":"%s","composeProjectName":"%s","operationId":"%s","tenantId":7,"gameTemplateId":17,"ownerAccountId":27,"worldSlug":"demo","worldDisplayName":"Demo World","realmSlug":"production","realmDisplayName":"Live Realm","visible":true,"publicProductionRealm":true,"requiresCharacterSelection":false,"stateScope":"SHARED","characterCreationPolicy":"ALLOW_NEW","gameSessionLeafSha256":"%s","gameSessionUriSan":"%s","caCertificateSha256":"%s","worldManagementUriSan":"%s","worldManagementLeafSha256":"%s","claimDigest":"%s"}\ + {"schema":"%s","runId":"%s","composeProjectName":"%s","operationId":"%s","tenantId":7,"gameTemplateId":17,"ownerAccountId":27,"worldSlug":"demo","worldDisplayName":"Demo World","realmSlug":"production","realmDisplayName":"Live Realm","visible":true,"publicProductionRealm":true,"requiresCharacterSelection":false,"stateScope":"SHARED","characterCreationPolicy":"PRESEEDED_ONLY","gameSessionLeafSha256":"%s","gameSessionUriSan":"%s","caCertificateSha256":"%s","worldManagementUriSan":"%s","worldManagementLeafSha256":"%s","claimDigest":"%s"}\ """ .formatted( RunOwnedInitialAdmissionFixtureWireCodec.CAPABILITY_SCHEMA, diff --git a/services/entity-management-service/src/main/java/net/firedevops/firemud/entitymanagement/service/impl/RunOwnedFixtureLookEntityGrpcService.java b/services/entity-management-service/src/main/java/net/firedevops/firemud/entitymanagement/service/impl/RunOwnedFixtureLookEntityGrpcService.java new file mode 100644 index 0000000000..7e66cfbba9 --- /dev/null +++ b/services/entity-management-service/src/main/java/net/firedevops/firemud/entitymanagement/service/impl/RunOwnedFixtureLookEntityGrpcService.java @@ -0,0 +1,180 @@ +package net.firedevops.firemud.entitymanagement.service.impl; + +import edu.umd.cs.findbugs.annotations.SuppressFBWarnings; +import io.grpc.Status; +import io.grpc.stub.StreamObserver; +import java.io.IOException; +import java.nio.file.Files; +import java.nio.file.Path; +import net.firedevops.firemud.common.grpc.GrpcPeerIdentity; +import net.firedevops.firemud.common.prev1.PreV1GateWaivers; +import net.firedevops.firemud.common.security.GrpcWorkloadOnlyGuard; +import net.firedevops.firemud.common.smoke.RunOwnedInitialAdmissionFixtureWireCodec; +import net.firedevops.firemud.common.world.WorldRunOwnedFixtureLifecycleEvidence; +import net.firedevops.firemud.entitymanagement.v1.ReadRunOwnedFixtureGroundRequest; +import net.firedevops.firemud.entitymanagement.v1.ReadRunOwnedFixtureGroundResponse; +import net.firedevops.firemud.entitymanagement.v1.RunOwnedFixtureLookEntityServiceGrpc; +import org.jooq.DSLContext; +import org.springframework.beans.factory.annotation.Qualifier; +import org.springframework.beans.factory.annotation.Value; +import org.springframework.boot.autoconfigure.condition.ConditionalOnExpression; +import org.springframework.core.env.Environment; +import org.springframework.grpc.server.service.GrpcService; +import org.springframework.transaction.PlatformTransactionManager; +import org.springframework.transaction.TransactionDefinition; +import org.springframework.transaction.support.TransactionTemplate; + +/** + * Entity-owned ground absence for the exact fresh fixture. Populated scopes require canonical + * Entity ownership and are held. The receipt and fixed run capability qualify the scope, and the + * actual holder tables establish absence. + */ +@GrpcService +@ConditionalOnExpression( + "${FIREMUD_SMOKE_INITIAL_ADMISSION_FIXTURE_ENABLED:false}" + + " and ${firemud.pre-v1.gate-waivers.enabled:false}") +public final class RunOwnedFixtureLookEntityGrpcService + extends RunOwnedFixtureLookEntityServiceGrpc.RunOwnedFixtureLookEntityServiceImplBase { + private static final int MAX_FIXTURE_FILE_BYTES = 16 * 1024; + private static final String GROUND_SOURCE_EXISTS = + "SELECT EXISTS (SELECT 1 FROM room_ground_inventory WHERE game_instance_id = ?" + + " UNION ALL SELECT 1 FROM container_instances WHERE game_instance_id = ?" + + " UNION ALL SELECT 1 FROM item_instances WHERE game_instance_id = ?" + + " UNION ALL SELECT 1 FROM item_stacks WHERE game_instance_id = ?)"; + + private final DSLContext dsl; + private final TransactionTemplate transaction; + private final String namespace; + private final String runId; + private final String composeProject; + private final Path capabilityPath; + private final Path receiptPath; + + @SuppressFBWarnings( + value = "EI_EXPOSE_REP2", + justification = "Reads fixture ground state through the shared jOOQ context.") + public RunOwnedFixtureLookEntityGrpcService( + DSLContext dsl, + @Qualifier("transactionManager") PlatformTransactionManager transactions, + Environment environment, + @Value("${firemud.grpc.workload-namespace:}") String namespace, + @Value("${FIREMUD_SMOKE_RUN_ID:}") String runId, + @Value("${FIREMUD_SMOKE_COMPOSE_PROJECT_NAME:}") String composeProject, + @Value("${FIREMUD_SMOKE_INITIAL_ADMISSION_CAPABILITY_PATH:}") String capabilityPath, + @Value("${FIREMUD_SMOKE_AUTHORED_WORLD_SOURCE_RECEIPT_PATH:}") String receiptPath) { + if (!PreV1GateWaivers.from(environment).enabled() + || !GrpcPeerIdentity.isValidNamespace(namespace) + || runId.isBlank() + || composeProject.isBlank()) { + throw new IllegalArgumentException("A run-owned fixture Entity scope is required"); + } + this.dsl = dsl; + transaction = new TransactionTemplate(transactions); + transaction.setReadOnly(true); + transaction.setPropagationBehavior(TransactionDefinition.PROPAGATION_REQUIRES_NEW); + transaction.setIsolationLevel(TransactionDefinition.ISOLATION_REPEATABLE_READ); + transaction.setTimeout(2); + this.namespace = namespace; + this.runId = runId; + this.composeProject = composeProject; + this.capabilityPath = Path.of(capabilityPath); + this.receiptPath = Path.of(receiptPath); + } + + @Override + public void readRunOwnedFixtureGround( + ReadRunOwnedFixtureGroundRequest request, + StreamObserver observer) { + var refusal = + GrpcWorkloadOnlyGuard.refusal(GrpcPeerIdentity.current(), "game-logic-service", namespace); + if (refusal.isPresent()) { + observer.onError(refusal.get().asRuntimeException()); + return; + } + final WorldRunOwnedFixtureLifecycleEvidence world; + var room = request.getRoom(); + try { + if (!request.hasRoom() + || !request.getUnknownFields().asMap().isEmpty() + || !room.getUnknownFields().asMap().isEmpty() + || !room.getRoomInstanceId().matches("R-[1-9][0-9]{0,18}")) { + throw new IllegalArgumentException("An exact fixture room is required"); + } + world = + WorldRunOwnedFixtureLifecycleEvidence.fromStored( + request.getWorldFixtureLifecycle().toByteArray()); + if (!world.request().canonicalTenantId().toString().equals(room.getTenantId()) + || !world.request().canonicalGameInstanceId().toString().equals(room.getGameInstanceId()) + || !world.request().targetNamespace().equals(namespace) + || !"ACTIVE".equals(world.lifecycleStatus())) { + throw new IllegalArgumentException("The fixture room differs from the current World scope"); + } + } catch (IllegalArgumentException invalid) { + observer.onError(Status.INVALID_ARGUMENT.asRuntimeException()); + return; + } + try { + var verified = readFixture(); + if (!verified + .creationEvidence() + .canonicalTenantId() + .equals(world.request().canonicalTenantId()) + || !verified + .fixturePolicySeal() + .evidenceDigest() + .equals(world.fixtureProvenanceDigest())) { + observer.onError(Status.PERMISSION_DENIED.asRuntimeException()); + return; + } + // The instance UUID is globally unique. Inspect every actual holder family at that UUID + // without adopting a numeric tenant or guessing the ownership of any populated row. + String game = room.getGameInstanceId(); + Boolean populated = + transaction.execute( + status -> { + dsl.execute("SET LOCAL statement_timeout = '1000ms'"); + return (Boolean) dsl.fetchValue(GROUND_SOURCE_EXISTS, game, game, game, game); + }); + if (!Boolean.FALSE.equals(populated) + || !verified.fixturePolicySeal().equals(readFixture().fixturePolicySeal())) { + observer.onError(Status.FAILED_PRECONDITION.asRuntimeException()); + return; + } + } catch (IOException | RuntimeException unavailable) { + observer.onError(Status.UNAVAILABLE.asRuntimeException()); + return; + } + observer.onNext( + ReadRunOwnedFixtureGroundResponse.newBuilder() + .setRoom(room) + .setEntitySnapshotId( + room.getTenantId() + + ":" + + room.getGameInstanceId() + + ":" + + room.getRoomInstanceId()) + .setEmptyGroundVerified(true) + .build()); + observer.onCompleted(); + } + + private RunOwnedInitialAdmissionFixtureWireCodec.SourceReceipt readFixture() throws IOException { + var capability = RunOwnedInitialAdmissionFixtureWireCodec.parseCapability(read(capabilityPath)); + if (!runId.equals(capability.runId()) + || !composeProject.equals(capability.composeProjectName())) { + throw new IllegalStateException("Fixture capability does not belong to this run"); + } + return RunOwnedInitialAdmissionFixtureWireCodec.parseSourceReceipt( + read(receiptPath), capability); + } + + private static byte[] read(Path path) throws IOException { + try (var input = Files.newInputStream(path)) { + byte[] bytes = input.readNBytes(MAX_FIXTURE_FILE_BYTES + 1); + if (bytes.length > MAX_FIXTURE_FILE_BYTES) { + throw new IllegalStateException("Fixture source exceeds its wire bound"); + } + return bytes; + } + } +} diff --git a/services/entity-management-service/src/main/resources/application.yml b/services/entity-management-service/src/main/resources/application.yml index dc3d49415d..a037332dfe 100644 --- a/services/entity-management-service/src/main/resources/application.yml +++ b/services/entity-management-service/src/main/resources/application.yml @@ -74,6 +74,7 @@ firemud: path-pattern: /.well-known/** grpc: public-methods: + - entity_management.v1.RunOwnedFixtureLookEntityService/ReadRunOwnedFixtureGround - entity_management.v1.EntityManagementService/Ping grpc: workload-namespace: ${FIREMUD_GRPC_WORKLOAD_NAMESPACE:} diff --git a/services/entity-management-service/src/test/java/unit/net/firedevops/firemud/entitymanagement/security/CanonicalGameplayRosterPeerInterceptorTest.java b/services/entity-management-service/src/test/java/unit/net/firedevops/firemud/entitymanagement/security/CanonicalGameplayRosterPeerInterceptorTest.java index ca7568a1b6..c91e3b8793 100644 --- a/services/entity-management-service/src/test/java/unit/net/firedevops/firemud/entitymanagement/security/CanonicalGameplayRosterPeerInterceptorTest.java +++ b/services/entity-management-service/src/test/java/unit/net/firedevops/firemud/entitymanagement/security/CanonicalGameplayRosterPeerInterceptorTest.java @@ -224,7 +224,9 @@ void applicationYamlKeepsRosterMethodsOutsideJwtBypassAllowlist() { .toList(); assertThat(publicMethods) - .containsExactly("entity_management.v1.EntityManagementService/Ping") + .containsExactly( + "entity_management.v1.RunOwnedFixtureLookEntityService/ReadRunOwnedFixtureGround", + "entity_management.v1.EntityManagementService/Ping") .doesNotContain( CanonicalGameplayRosterPeerInterceptor.METHOD_NAME, CanonicalGameplayRosterPeerInterceptor.SELECTED_ASSIGNMENT_METHOD_NAME, diff --git a/services/game-design-service/src/main/resources/db/migration/V1035__run_owned_fixture_preseeded_only_policy.sql b/services/game-design-service/src/main/resources/db/migration/V1035__run_owned_fixture_preseeded_only_policy.sql new file mode 100644 index 0000000000..ebb569fa8c --- /dev/null +++ b/services/game-design-service/src/main/resources/db/migration/V1035__run_owned_fixture_preseeded_only_policy.sql @@ -0,0 +1,23 @@ +-- The run-owned fixture realm admits only preseeded characters, matching the canonical PLAY chain +-- (Account entitlement and Game Session admission accept PRESEEDED_ONLY). Pre-v1 fixture rows are +-- throwaway; no retained row is rewritten. +-- [jooq ignore start] +DO $migration$ +DECLARE + guard_name TEXT; + current_guard TEXT; + anchor TEXT := $anchor$'characterCreationPolicy', 'ALLOW_NEW'$anchor$; +BEGIN + FOREACH guard_name IN ARRAY ARRAY[ + 'guard_published_realm_policy_set()', + 'guard_published_policy_inventory_v2()'] LOOP + SELECT pg_get_functiondef(guard_name::REGPROCEDURE) INTO STRICT current_guard; + IF (length(current_guard)-length(replace(current_guard,anchor,'')))/length(anchor) <> 1 THEN + RAISE EXCEPTION 'Expected exactly one fixture creation policy in %', guard_name; + END IF; + EXECUTE replace(current_guard, anchor, + $replacement$'characterCreationPolicy', 'PRESEEDED_ONLY'$replacement$); + END LOOP; +END; +$migration$; +-- [jooq ignore stop] diff --git a/services/game-design-service/src/sharedTest/java/net/firedevops/firemud/gamedesign/data/TestDataSeederIntegrationSupport.java b/services/game-design-service/src/sharedTest/java/net/firedevops/firemud/gamedesign/data/TestDataSeederIntegrationSupport.java index dfd63e52e0..e97401ee5a 100644 --- a/services/game-design-service/src/sharedTest/java/net/firedevops/firemud/gamedesign/data/TestDataSeederIntegrationSupport.java +++ b/services/game-design-service/src/sharedTest/java/net/firedevops/firemud/gamedesign/data/TestDataSeederIntegrationSupport.java @@ -474,7 +474,7 @@ protected Fixture prepareFixture(Path testDirectory, boolean prepareExistingOwne capability.put("publicProductionRealm", true); capability.put("requiresCharacterSelection", false); capability.put("stateScope", "SHARED"); - capability.put("characterCreationPolicy", "ALLOW_NEW"); + capability.put("characterCreationPolicy", "PRESEEDED_ONLY"); capability.put("gameSessionLeafSha256", leafDigest); capability.put("gameSessionUriSan", SESSION_URI_SAN); capability.put("worldManagementLeafSha256", worldManagementLeafDigest); diff --git a/services/game-design-service/src/test/java/unit/net/firedevops/firemud/gamedesign/data/TestDataSeederTest.java b/services/game-design-service/src/test/java/unit/net/firedevops/firemud/gamedesign/data/TestDataSeederTest.java index b2da73bad2..1c07a55ec1 100644 --- a/services/game-design-service/src/test/java/unit/net/firedevops/firemud/gamedesign/data/TestDataSeederTest.java +++ b/services/game-design-service/src/test/java/unit/net/firedevops/firemud/gamedesign/data/TestDataSeederTest.java @@ -516,7 +516,7 @@ void rejectsWrongOwnerAccountBeforeAnySeederOwnerWrites(@TempDir Path directory) Path capabilityPath = directory.resolve("run-owned-initial-admission-capability.json"); String capabilityJson = """ - {"schema":"%s","runId":"%s","composeProjectName":"%s","operationId":"%s","tenantId":1,"gameTemplateId":17,"ownerAccountId":27,"worldSlug":"demo","worldDisplayName":"Demo World","realmSlug":"production","realmDisplayName":"Live Realm","visible":true,"publicProductionRealm":true,"requiresCharacterSelection":false,"stateScope":"SHARED","characterCreationPolicy":"ALLOW_NEW","gameSessionLeafSha256":"%s","gameSessionUriSan":"%s","caCertificateSha256":"%s","worldManagementUriSan":"%s","worldManagementLeafSha256":"%s","claimDigest":"%s"}%n\ + {"schema":"%s","runId":"%s","composeProjectName":"%s","operationId":"%s","tenantId":1,"gameTemplateId":17,"ownerAccountId":27,"worldSlug":"demo","worldDisplayName":"Demo World","realmSlug":"production","realmDisplayName":"Live Realm","visible":true,"publicProductionRealm":true,"requiresCharacterSelection":false,"stateScope":"SHARED","characterCreationPolicy":"PRESEEDED_ONLY","gameSessionLeafSha256":"%s","gameSessionUriSan":"%s","caCertificateSha256":"%s","worldManagementUriSan":"%s","worldManagementLeafSha256":"%s","claimDigest":"%s"}%n\ """ .formatted( RunOwnedInitialAdmissionFixtureWireCodec.CAPABILITY_SCHEMA, diff --git a/services/game-logic-service/src/main/java/net/firedevops/firemud/gamelogic/config/GameLogicGrpcClientConfig.java b/services/game-logic-service/src/main/java/net/firedevops/firemud/gamelogic/config/GameLogicGrpcClientConfig.java index 4818baa611..fa643c1b3c 100644 --- a/services/game-logic-service/src/main/java/net/firedevops/firemud/gamelogic/config/GameLogicGrpcClientConfig.java +++ b/services/game-logic-service/src/main/java/net/firedevops/firemud/gamelogic/config/GameLogicGrpcClientConfig.java @@ -8,11 +8,17 @@ import net.firedevops.firemud.common.grpc.BlockingGrpcStubCustomizer; import net.firedevops.firemud.common.grpc.CommonGrpcClientProperties; import net.firedevops.firemud.common.grpc.GrpcChannelFactory; +import net.firedevops.firemud.common.grpc.GrpcServerPeerIdentityCallCredentials; +import net.firedevops.firemud.common.grpc.GrpcServerPeerIdentityClientInterceptor; import net.firedevops.firemud.entitymanagement.v1.EntityManagementServiceGrpc; import net.firedevops.firemud.entitymanagement.v1.EntityManagementServiceGrpc.EntityManagementServiceBlockingStub; +import net.firedevops.firemud.entitymanagement.v1.RunOwnedFixtureLookEntityServiceGrpc; import net.firedevops.firemud.socialgroups.v1.SocialGroupsServiceGrpc; +import net.firedevops.firemud.worldmanagement.v1.RunOwnedFixtureLookWorldServiceGrpc; import net.firedevops.firemud.worldmanagement.v1.WorldManagementServiceGrpc; import net.firedevops.firemud.worldmanagement.v1.WorldManagementServiceGrpc.WorldManagementServiceBlockingStub; +import org.springframework.beans.factory.annotation.Value; +import org.springframework.boot.autoconfigure.condition.ConditionalOnExpression; import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.Configuration; import org.springframework.context.annotation.Lazy; @@ -76,6 +82,30 @@ public SocialGroupsServiceGrpc.SocialGroupsServiceBlockingStub socialGroupsStub( SocialGroupsServiceGrpc.newBlockingStub(socialChannel).withCompression("gzip")); } + @Bean + @ConditionalOnExpression( + "${FIREMUD_SMOKE_INITIAL_ADMISSION_FIXTURE_ENABLED:false}" + + " and ${firemud.pre-v1.gate-waivers.enabled:false}") + RunOwnedFixtureLookWorldServiceGrpc.RunOwnedFixtureLookWorldServiceBlockingStub + fixtureLookWorldStub(@Value("${firemud.grpc.workload-namespace:}") String namespace) { + String peer = "spiffe://firemud/ns/" + namespace + "/sa/world-management-service"; + return RunOwnedFixtureLookWorldServiceGrpc.newBlockingStub(worldChannel) + .withCallCredentials(new GrpcServerPeerIdentityCallCredentials(peer)) + .withInterceptors(new GrpcServerPeerIdentityClientInterceptor(peer)); + } + + @Bean + @ConditionalOnExpression( + "${FIREMUD_SMOKE_INITIAL_ADMISSION_FIXTURE_ENABLED:false}" + + " and ${firemud.pre-v1.gate-waivers.enabled:false}") + RunOwnedFixtureLookEntityServiceGrpc.RunOwnedFixtureLookEntityServiceBlockingStub + fixtureLookEntityStub(@Value("${firemud.grpc.workload-namespace:}") String namespace) { + String peer = "spiffe://firemud/ns/" + namespace + "/sa/entity-management-service"; + return RunOwnedFixtureLookEntityServiceGrpc.newBlockingStub(entityChannel) + .withCallCredentials(new GrpcServerPeerIdentityCallCredentials(peer)) + .withInterceptors(new GrpcServerPeerIdentityClientInterceptor(peer)); + } + private > T customize(T stub) { return stubCustomizer.customize(stub); } diff --git a/services/game-logic-service/src/main/java/net/firedevops/firemud/gamelogic/service/LookAggregationService.java b/services/game-logic-service/src/main/java/net/firedevops/firemud/gamelogic/service/LookAggregationService.java index 4c085b9042..845c46df4a 100644 --- a/services/game-logic-service/src/main/java/net/firedevops/firemud/gamelogic/service/LookAggregationService.java +++ b/services/game-logic-service/src/main/java/net/firedevops/firemud/gamelogic/service/LookAggregationService.java @@ -38,38 +38,38 @@ public class LookAggregationService { public LookResult resolve(LookRequest request) { try (GameplayLoggingContext ignored = GameplayLoggingContext.from(request)) { - RoomSnapshot snapshot = fetchSnapshot(request); - ListRoomEntitiesResponse entityResponse = fetchEntities(request); - requireSameReadFence(snapshot, entityResponse); - - LookResult.Builder builder = - LookResult.newBuilder() - .setRoomInstance( - RoomInstanceRef.newBuilder() - .setTenantId(snapshot.getTenantId()) - .setGameInstanceId(snapshot.getGameInstanceId()) - .setRoomInstanceId(snapshot.getRoomInstanceId()) - .build()) - .setRoomName(snapshot.getRoomName()) - .setShortDescription(snapshot.getShortDescription()) - .setLongDescription(snapshot.getLongDescription()) - .setWorldSnapshotId(snapshot.getWorldSnapshotId()) - .setEntitySnapshotId(entityResponse.getEntitySnapshotId()) - .setLookSnapshotId(snapshot.getWorldSnapshotId()) - .addAllRoomFlags(snapshot.getRoomFlagsList()) - .setAmbientState(toAmbientState(snapshot.getAmbientState())); - - snapshot.getExitsList().forEach(exit -> builder.addExits(toLookExit(exit))); - entityResponse.getEntitiesList().stream() - .map(this::toRoomEntity) - .forEach(builder::addEntities); - - LookResult result = builder.build(); - LOG.debug("Rendered LOOK text:\n{}", renderer.render(result)); - return result; + return project(fetchSnapshot(request), fetchEntities(request)); } } + public LookResult project(RoomSnapshot snapshot, ListRoomEntitiesResponse entityResponse) { + requireSameReadFence(snapshot, entityResponse); + + LookResult.Builder builder = + LookResult.newBuilder() + .setRoomInstance( + RoomInstanceRef.newBuilder() + .setTenantId(snapshot.getTenantId()) + .setGameInstanceId(snapshot.getGameInstanceId()) + .setRoomInstanceId(snapshot.getRoomInstanceId()) + .build()) + .setRoomName(snapshot.getRoomName()) + .setShortDescription(snapshot.getShortDescription()) + .setLongDescription(snapshot.getLongDescription()) + .setWorldSnapshotId(snapshot.getWorldSnapshotId()) + .setEntitySnapshotId(entityResponse.getEntitySnapshotId()) + .setLookSnapshotId(snapshot.getWorldSnapshotId()) + .addAllRoomFlags(snapshot.getRoomFlagsList()) + .setAmbientState(toAmbientState(snapshot.getAmbientState())); + + snapshot.getExitsList().forEach(exit -> builder.addExits(toLookExit(exit))); + entityResponse.getEntitiesList().stream().map(this::toRoomEntity).forEach(builder::addEntities); + + LookResult result = builder.build(); + LOG.debug("Rendered LOOK text:\n{}", renderer.render(result)); + return result; + } + private RoomSnapshot fetchSnapshot(LookRequest request) { try { GetRoomSnapshotResponse response = diff --git a/services/game-logic-service/src/main/java/net/firedevops/firemud/gamelogic/service/impl/RunOwnedFixtureLookGrpcService.java b/services/game-logic-service/src/main/java/net/firedevops/firemud/gamelogic/service/impl/RunOwnedFixtureLookGrpcService.java new file mode 100644 index 0000000000..9faa004be6 --- /dev/null +++ b/services/game-logic-service/src/main/java/net/firedevops/firemud/gamelogic/service/impl/RunOwnedFixtureLookGrpcService.java @@ -0,0 +1,128 @@ +package net.firedevops.firemud.gamelogic.service.impl; + +import io.grpc.Status; +import io.grpc.StatusRuntimeException; +import io.grpc.stub.StreamObserver; +import java.util.concurrent.TimeUnit; +import net.firedevops.firemud.common.grpc.GrpcPeerIdentity; +import net.firedevops.firemud.common.prev1.PreV1GateWaivers; +import net.firedevops.firemud.common.security.GrpcWorkloadOnlyGuard; +import net.firedevops.firemud.common.world.WorldCanonicalInstanceLifecycleGrpcCodec; +import net.firedevops.firemud.entitymanagement.v1.ListRoomEntitiesResponse; +import net.firedevops.firemud.entitymanagement.v1.ReadRunOwnedFixtureGroundRequest; +import net.firedevops.firemud.entitymanagement.v1.RunOwnedFixtureLookEntityServiceGrpc.RunOwnedFixtureLookEntityServiceBlockingStub; +import net.firedevops.firemud.gamelogic.service.LookAggregationService; +import net.firedevops.firemud.gamelogic.v1.LookResult; +import net.firedevops.firemud.gamelogic.v1.ResolveRunOwnedFixtureLookRequest; +import net.firedevops.firemud.gamelogic.v1.ResolveRunOwnedFixtureLookResponse; +import net.firedevops.firemud.gamelogic.v1.RunOwnedFixtureLookServiceGrpc; +import net.firedevops.firemud.shared.v1.RoomInstanceRef; +import net.firedevops.firemud.worldmanagement.v1.RunOwnedFixtureLookWorldServiceGrpc.RunOwnedFixtureLookWorldServiceBlockingStub; +import org.springframework.beans.factory.annotation.Value; +import org.springframework.boot.autoconfigure.condition.ConditionalOnExpression; +import org.springframework.core.env.Environment; +import org.springframework.grpc.server.service.GrpcService; + +/** Game Logic owns the combined World and Entity view for an admitted fixture player. */ +@GrpcService +@ConditionalOnExpression( + "${FIREMUD_SMOKE_INITIAL_ADMISSION_FIXTURE_ENABLED:false}" + + " and ${firemud.pre-v1.gate-waivers.enabled:false}") +public final class RunOwnedFixtureLookGrpcService + extends RunOwnedFixtureLookServiceGrpc.RunOwnedFixtureLookServiceImplBase { + private final RunOwnedFixtureLookWorldServiceBlockingStub world; + private final RunOwnedFixtureLookEntityServiceBlockingStub entity; + private final LookAggregationService look; + private final String namespace; + + public RunOwnedFixtureLookGrpcService( + RunOwnedFixtureLookWorldServiceBlockingStub world, + RunOwnedFixtureLookEntityServiceBlockingStub entity, + LookAggregationService look, + Environment environment, + @Value("${firemud.grpc.workload-namespace:}") String namespace) { + if (!PreV1GateWaivers.from(environment).enabled() + || !GrpcPeerIdentity.isValidNamespace(namespace)) { + throw new IllegalArgumentException("An enabled run-owned LOOK scope is required"); + } + this.world = world; + this.entity = entity; + this.look = look; + this.namespace = namespace; + } + + @Override + public void resolveRunOwnedFixtureLook( + ResolveRunOwnedFixtureLookRequest wire, + StreamObserver observer) { + var refusal = + GrpcWorkloadOnlyGuard.refusal( + GrpcPeerIdentity.current(), "game-session-service", namespace); + if (refusal.isPresent()) { + observer.onError(refusal.get().asRuntimeException()); + return; + } + LookResult view; + try { + if (!wire.hasRoom() || !wire.getUnknownFields().asMap().isEmpty()) { + throw new IllegalArgumentException("The exact fixture room request is required"); + } + var request = wire.getRoom(); + var selector = WorldCanonicalInstanceLifecycleGrpcCodec.fromRequest(request.getLifecycle()); + if (!request.getUnknownFields().asMap().isEmpty() + || !namespace.equals(selector.targetNamespace())) { + throw new IllegalArgumentException("The exact fixture World selector is required"); + } + var first = world.withDeadlineAfter(2, TimeUnit.SECONDS).readRunOwnedFixtureLookRoom(request); + var active = + WorldCanonicalInstanceLifecycleGrpcCodec.fromFixtureResponse( + selector, first.getLifecycle()); + var snapshot = first.getSnapshot(); + var room = + RoomInstanceRef.newBuilder() + .setTenantId(selector.canonicalTenantId().toString()) + .setGameInstanceId(selector.canonicalGameInstanceId().toString()) + .setRoomInstanceId(request.getExpectedRoomInstanceKey()) + .build(); + if (!"ACTIVE".equals(active.lifecycleStatus()) + || !first.hasSnapshot() + || !room.getTenantId().equals(snapshot.getTenantId()) + || !room.getGameInstanceId().equals(snapshot.getGameInstanceId()) + || !room.getRoomInstanceId().equals(snapshot.getRoomInstanceId())) { + throw Status.FAILED_PRECONDITION.asRuntimeException(); + } + var ground = + entity + .withDeadlineAfter(2, TimeUnit.SECONDS) + .readRunOwnedFixtureGround( + ReadRunOwnedFixtureGroundRequest.newBuilder() + .setRoom(room) + .setWorldFixtureLifecycle(first.getLifecycle().getCanonicalResponseBytes()) + .build()); + if (!ground.getEmptyGroundVerified() || !room.equals(ground.getRoom())) { + throw Status.FAILED_PRECONDITION.asRuntimeException(); + } + if (!first.equals( + world.withDeadlineAfter(2, TimeUnit.SECONDS).readRunOwnedFixtureLookRoom(request))) { + throw Status.FAILED_PRECONDITION.asRuntimeException(); + } + view = + look.project( + snapshot, + ListRoomEntitiesResponse.newBuilder() + .setEntitySnapshotId(ground.getEntitySnapshotId()) + .build()); + } catch (StatusRuntimeException sourceFailure) { + observer.onError(Status.fromCode(sourceFailure.getStatus().getCode()).asRuntimeException()); + return; + } catch (IllegalArgumentException invalid) { + observer.onError(Status.INVALID_ARGUMENT.asRuntimeException()); + return; + } catch (RuntimeException unavailable) { + observer.onError(Status.UNAVAILABLE.asRuntimeException()); + return; + } + observer.onNext(ResolveRunOwnedFixtureLookResponse.newBuilder().setLook(view).build()); + observer.onCompleted(); + } +} diff --git a/services/game-logic-service/src/main/resources/application.yml b/services/game-logic-service/src/main/resources/application.yml index 972d39e002..ac710b032c 100644 --- a/services/game-logic-service/src/main/resources/application.yml +++ b/services/game-logic-service/src/main/resources/application.yml @@ -65,12 +65,15 @@ firemud: inventory-enabled: true command-history-enabled: true grpc: + workload-namespace: ${FIREMUD_GRPC_WORKLOAD_NAMESPACE:} cert-chain: ${FIREMUD_GRPC_CERT_CHAIN_PATH:certs/client.crt} private-key: ${FIREMUD_GRPC_PRIVATE_KEY_PATH:certs/client.key} ca-cert: ${FIREMUD_GRPC_CA_CERT_PATH:certs/ca.crt} auth: grpc: force-internal-service-outbound: true + public-methods: + - game_logic.v1.RunOwnedFixtureLookService/ResolveRunOwnedFixtureLook server: compression: diff --git a/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/client/WorldCanonicalInitialAdmissionHoldClient.java b/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/client/WorldCanonicalInitialAdmissionHoldClient.java index c29ae72332..5526c5a2b7 100644 --- a/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/client/WorldCanonicalInitialAdmissionHoldClient.java +++ b/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/client/WorldCanonicalInitialAdmissionHoldClient.java @@ -172,7 +172,7 @@ public WorldCanonicalInitialAdmissionHoldState readState( throw new IllegalArgumentException( "World initial-admission state changed the exact immutable hold identity"); } - if (!lifecycleRequest.equals(state.lifecycleEvidence().request())) { + if (!lifecycleRequest.equals(state.lifecycleRequest())) { throw new IllegalArgumentException( "World initial-admission state changed the complete lifecycle read request"); } diff --git a/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/config/CanonicalGameplayAdmissionDecisionReadConfiguration.java b/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/config/CanonicalGameplayAdmissionDecisionReadConfiguration.java new file mode 100644 index 0000000000..81b9bf1165 --- /dev/null +++ b/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/config/CanonicalGameplayAdmissionDecisionReadConfiguration.java @@ -0,0 +1,56 @@ +package net.firedevops.firemud.gamesession.config; + +import java.io.IOException; +import net.firedevops.firemud.common.config.ServiceEndpointsProperties; +import net.firedevops.firemud.common.grpc.CommonGrpcClientProperties; +import net.firedevops.firemud.common.grpc.GrpcChannelFactory; +import net.firedevops.firemud.common.world.WorldCanonicalInstanceLifecycleClient; +import net.firedevops.firemud.gamesession.repository.CanonicalGameInstanceLaunchAssociationRepository; +import net.firedevops.firemud.gamesession.repository.CanonicalGameplayAdmissionAbortManualFactory; +import net.firedevops.firemud.gamesession.service.CanonicalPlayerRouteReadService; +import net.firedevops.firemud.gamesession.service.CanonicalPublishedPlayerRouteReadService; +import net.firedevops.firemud.gamesession.service.impl.CanonicalGameplayAdmissionDecisionReadGrpcService; +import org.jooq.DSLContext; +import org.springframework.beans.factory.annotation.Value; +import org.springframework.boot.autoconfigure.condition.ConditionalOnExpression; +import org.springframework.context.annotation.Bean; +import org.springframework.context.annotation.Configuration; + +/** + * Registers Account's canonical REALMS discovery and JOIN resolution read over the canonical player + * route, published realm and launch association owners. The receiver authenticates its exact + * Account mTLS peer itself; the negative never-admitted read stays unavailable here. + */ +@Configuration(proxyBeanMethods = false) +@ConditionalOnExpression( + "${firemud.canonical-gameplay-roster-owner-read.enabled:false}" + + " and ${firemud.canonical-game-instance-launch-association-owner-read.enabled:false}") +public class CanonicalGameplayAdmissionDecisionReadConfiguration { + + @Bean(destroyMethod = "close") + WorldCanonicalInstanceLifecycleClient canonicalAdmissionWorldLifecycleClient( + ServiceEndpointsProperties endpoints, + CommonGrpcClientProperties tlsProperties, + GrpcChannelFactory channelFactory, + @Value("${firemud.grpc.workload-namespace:}") String workloadNamespace) + throws IOException { + var client = + new WorldCanonicalInstanceLifecycleClient( + endpoints, tlsProperties, channelFactory, workloadNamespace); + client.init(); + return client; + } + + @Bean + CanonicalGameplayAdmissionDecisionReadGrpcService + canonicalGameplayAdmissionDecisionReadGrpcService( + DSLContext dsl, + CanonicalPlayerRouteReadService routeReader, + CanonicalPublishedPlayerRouteReadService publishedReader, + CanonicalGameInstanceLaunchAssociationRepository launchReader, + WorldCanonicalInstanceLifecycleClient world, + @Value("${firemud.grpc.workload-namespace:}") String workloadNamespace) { + return CanonicalGameplayAdmissionAbortManualFactory.createDecisionReadReceiver( + dsl, workloadNamespace, routeReader, publishedReader, launchReader, world); + } +} diff --git a/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/config/RunOwnedFixtureFirstOpenConfiguration.java b/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/config/RunOwnedFixtureFirstOpenConfiguration.java new file mode 100644 index 0000000000..09bebdf7de --- /dev/null +++ b/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/config/RunOwnedFixtureFirstOpenConfiguration.java @@ -0,0 +1,99 @@ +package net.firedevops.firemud.gamesession.config; + +import java.io.IOException; +import net.firedevops.firemud.common.config.ServiceEndpointsProperties; +import net.firedevops.firemud.common.grpc.CommonGrpcClientProperties; +import net.firedevops.firemud.common.grpc.GrpcChannelFactory; +import net.firedevops.firemud.gamesession.client.WorldCanonicalInitialAdmissionHoldClient; +import net.firedevops.firemud.gamesession.client.WorldManagementClient; +import net.firedevops.firemud.gamesession.data.RunOwnedCanonicalLaunchPreparationOwner; +import net.firedevops.firemud.gamesession.data.RunOwnedFixtureFirstOpenCoordinator; +import net.firedevops.firemud.gamesession.data.RunOwnedFixtureFirstOpenDriver; +import net.firedevops.firemud.gamesession.repository.CanonicalGameInstanceLaunchAssociationRepository; +import net.firedevops.firemud.gamesession.repository.CanonicalInitialAdmissionIntentRepository; +import net.firedevops.firemud.gamesession.repository.CanonicalInitialAdmissionRepository; +import net.firedevops.firemud.gamesession.repository.GameSessionCanonicalAdmissionPointerRepository; +import net.firedevops.firemud.gamesession.repository.GameSessionCanonicalRealmCatalogRepository; +import net.firedevops.firemud.gamesession.repository.GameplayAdmissionPointerEventRepository; +import net.firedevops.firemud.gamesession.repository.RunOwnedFixtureRuntimeCompletionRepository; +import net.firedevops.firemud.gamesession.service.impl.AuthenticatedCanonicalInitialAdmissionWorldVerifier; +import org.jooq.DSLContext; +import org.springframework.beans.factory.annotation.Qualifier; +import org.springframework.beans.factory.annotation.Value; +import org.springframework.boot.autoconfigure.condition.ConditionalOnExpression; +import org.springframework.context.annotation.Bean; +import org.springframework.context.annotation.Configuration; +import org.springframework.transaction.PlatformTransactionManager; + +/** + * Composes the canonical run-owned Compose fixture through its first OPEN. Requires the canonical + * launch-association owner read (which supplies the launch and initial-admission repositories) and + * registers the catalog and pointer owners those and the player route read need. + */ +@Configuration(proxyBeanMethods = false) +@ConditionalOnExpression( + "${FIREMUD_SMOKE_INITIAL_ADMISSION_FIXTURE_ENABLED:false}" + + " and ${firemud.canonical-game-instance-launch-association-owner-read.enabled:false}") +public class RunOwnedFixtureFirstOpenConfiguration { + + @Bean + GameSessionCanonicalRealmCatalogRepository runOwnedFixtureCanonicalRealmCatalogRepository( + DSLContext dsl, + @Qualifier("transactionManager") PlatformTransactionManager transactionManager, + @Value("${firemud.grpc.workload-namespace:}") String workloadNamespace) { + return new GameSessionCanonicalRealmCatalogRepository( + dsl, transactionManager, workloadNamespace); + } + + @Bean + GameSessionCanonicalAdmissionPointerRepository runOwnedFixtureCanonicalAdmissionPointerRepository( + DSLContext dsl, GameSessionCanonicalRealmCatalogRepository catalogRepository) { + return new GameSessionCanonicalAdmissionPointerRepository( + dsl, catalogRepository, new GameplayAdmissionPointerEventRepository(dsl)); + } + + @Bean(destroyMethod = "close") + WorldCanonicalInitialAdmissionHoldClient runOwnedFixtureWorldHoldClient( + ServiceEndpointsProperties endpoints, + CommonGrpcClientProperties tlsProperties, + GrpcChannelFactory channelFactory, + @Value("${firemud.grpc.workload-namespace:}") String workloadNamespace) + throws IOException { + var client = + new WorldCanonicalInitialAdmissionHoldClient( + endpoints, tlsProperties, channelFactory, workloadNamespace); + client.init(); + return client; + } + + @Bean + RunOwnedFixtureFirstOpenCoordinator runOwnedFixtureFirstOpenCoordinator( + DSLContext dsl, + RunOwnedCanonicalLaunchPreparationOwner launchOwner, + WorldManagementClient world, + CanonicalGameInstanceLaunchAssociationRepository launches, + GameSessionCanonicalRealmCatalogRepository catalogRepository, + WorldCanonicalInitialAdmissionHoldClient holds, + CanonicalInitialAdmissionRepository admissions, + @Qualifier("transactionManager") PlatformTransactionManager transactionManager, + @Value("${firemud.grpc.workload-namespace:}") String workloadNamespace) { + var intents = new CanonicalInitialAdmissionIntentRepository(dsl, catalogRepository, launches); + return new RunOwnedFixtureFirstOpenCoordinator( + launchOwner, + world, + launches, + intents, + holds, + admissions, + new RunOwnedFixtureRuntimeCompletionRepository(dsl, launches), + new AuthenticatedCanonicalInitialAdmissionWorldVerifier(holds, intents, workloadNamespace), + transactionManager, + workloadNamespace); + } + + @Bean + RunOwnedFixtureFirstOpenDriver runOwnedFixtureFirstOpenDriver( + RunOwnedFixtureFirstOpenCoordinator coordinator) { + return new RunOwnedFixtureFirstOpenDriver(coordinator); + } +} diff --git a/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/data/RunOwnedFixtureFirstOpenCoordinator.java b/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/data/RunOwnedFixtureFirstOpenCoordinator.java new file mode 100644 index 0000000000..3a049b0ed5 --- /dev/null +++ b/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/data/RunOwnedFixtureFirstOpenCoordinator.java @@ -0,0 +1,263 @@ +package net.firedevops.firemud.gamesession.data; + +import java.util.Objects; +import java.util.Optional; +import java.util.UUID; +import java.util.function.Supplier; +import net.firedevops.firemud.common.grpc.GrpcPeerIdentity; +import net.firedevops.firemud.common.world.WorldCanonicalInitialAdmissionHold; +import net.firedevops.firemud.common.world.WorldCanonicalInitialAdmissionHold.HoldIdentity; +import net.firedevops.firemud.common.world.WorldCanonicalInstanceLifecycleEvidence; +import net.firedevops.firemud.gamedesign.v1.LaunchDescriptor; +import net.firedevops.firemud.gamesession.client.WorldCanonicalInitialAdmissionHoldClient; +import net.firedevops.firemud.gamesession.client.WorldManagementClient; +import net.firedevops.firemud.gamesession.dto.CanonicalGameInstanceLaunchAssociation; +import net.firedevops.firemud.gamesession.dto.CanonicalInitialAdmissionOwnerProof; +import net.firedevops.firemud.gamesession.dto.CanonicalInitialAdmissionRequest; +import net.firedevops.firemud.gamesession.dto.CanonicalInitialAdmissionWorldProof; +import net.firedevops.firemud.gamesession.repository.CanonicalGameInstanceLaunchAssociationRepository; +import net.firedevops.firemud.gamesession.repository.CanonicalInitialAdmissionIntentRepository; +import net.firedevops.firemud.gamesession.repository.CanonicalInitialAdmissionRepository; +import net.firedevops.firemud.gamesession.repository.RunOwnedFixtureRuntimeCompletionRepository; +import net.firedevops.firemud.gamesession.service.CanonicalInitialAdmissionWorldVerifier; +import net.firedevops.firemud.worldmanagement.v1.WorldInstanceLifecycleSnapshot; +import net.firedevops.firemud.worldmanagement.v1.WorldInstanceLifecycleStatus; +import org.springframework.transaction.PlatformTransactionManager; +import org.springframework.transaction.TransactionDefinition; +import org.springframework.transaction.support.TransactionSynchronizationManager; +import org.springframework.transaction.support.TransactionTemplate; + +/** + * Drives the canonical run-owned Compose fixture from its verified source receipt to its first OPEN + * pointer: Game Session STARTING launch, World prepare and activate, the intent and World + * initial-admission hold, the PENDING attempt, World verification, STARTING to RUNNING, and the + * pointer commit. + * + *

Every step is an existing owner's exact, replay-safe operation, so a restart resumes from the + * retained state. Remote calls run outside SQL transactions; each Game Session write uses its own + * READ COMMITTED transaction. The fixture carries its policy-seal evidence in place of a Human + * Account StartSession tuple and never grants player admission. + */ +public final class RunOwnedFixtureFirstOpenCoordinator { + private final RunOwnedCanonicalLaunchPreparationOwner launchOwner; + private final WorldManagementClient world; + private final CanonicalGameInstanceLaunchAssociationRepository launches; + private final CanonicalInitialAdmissionIntentRepository intents; + private final WorldCanonicalInitialAdmissionHoldClient holds; + private final CanonicalInitialAdmissionRepository admissions; + private final RunOwnedFixtureRuntimeCompletionRepository completions; + private final CanonicalInitialAdmissionWorldVerifier verifier; + private final TransactionTemplate writeTransaction; + private final String workloadNamespace; + + public RunOwnedFixtureFirstOpenCoordinator( + RunOwnedCanonicalLaunchPreparationOwner launchOwner, + WorldManagementClient world, + CanonicalGameInstanceLaunchAssociationRepository launches, + CanonicalInitialAdmissionIntentRepository intents, + WorldCanonicalInitialAdmissionHoldClient holds, + CanonicalInitialAdmissionRepository admissions, + RunOwnedFixtureRuntimeCompletionRepository completions, + CanonicalInitialAdmissionWorldVerifier verifier, + PlatformTransactionManager transactionManager, + String workloadNamespace) { + this.launchOwner = Objects.requireNonNull(launchOwner, "launchOwner"); + this.world = Objects.requireNonNull(world, "world"); + this.launches = Objects.requireNonNull(launches, "launches"); + this.intents = Objects.requireNonNull(intents, "intents"); + this.holds = Objects.requireNonNull(holds, "holds"); + this.admissions = Objects.requireNonNull(admissions, "admissions"); + this.completions = Objects.requireNonNull(completions, "completions"); + this.verifier = Objects.requireNonNull(verifier, "verifier"); + if (!GrpcPeerIdentity.isValidNamespace(workloadNamespace)) { + throw new IllegalArgumentException("Canonical Game Session workload namespace required"); + } + this.workloadNamespace = workloadNamespace; + writeTransaction = + new TransactionTemplate(Objects.requireNonNull(transactionManager, "transactionManager")); + writeTransaction.setIsolationLevel(TransactionDefinition.ISOLATION_READ_COMMITTED); + writeTransaction.setPropagationBehavior(TransactionDefinition.PROPAGATION_REQUIRES_NEW); + } + + /** Runs or resumes the fixture to its committed first OPEN and returns the owner proof. */ + public CanonicalInitialAdmissionOwnerProof openFirstRealm() { + requireNoAmbientTransaction(); + var prepared = launchOwner.prepareFixedVerifiedFixtureLaunch(); + var launch = prepared.launch(); + var catalog = launch.catalog().snapshot(); + long gameSessionTenantId = launch.catalog().association().gameSessionTenantId(); + String requestId = + "run-owned-fixture-" + prepared.launchEvidence().fixtureCapability().operationId(); + + Optional retained = + admissions.read(workloadNamespace, requestId); + if (retained.isPresent() + && retained.orElseThrow().outcome() + != CanonicalInitialAdmissionOwnerProof.Outcome.PENDING) { + return retained.orElseThrow(); + } + + long activeEpoch = + activateWorld( + gameSessionTenantId, + launch.gameInstanceId(), + prepared.launchEvidence().gameTemplateId(), + prepared.launchEvidence().launchDescriptor()); + + CanonicalGameInstanceLaunchAssociation association = + launches + .readForInitialAdmission( + workloadNamespace, catalog.tenantId(), catalog.realmId(), launch.gameInstanceUuid()) + .orElseThrow( + () -> new IllegalStateException("Fixture launch association is unavailable")) + .association(); + if (!association.isRunOwnedFixture()) { + throw new IllegalStateException("Fixture coordinator found a Human launch association"); + } + UUID canonicalVersionId = association.canonicalVersionId(); + String requestDigest = + CanonicalInitialAdmissionRequest.computeRequestDigest( + workloadNamespace, + catalog.tenantId(), + catalog.worldSlug(), + catalog.realmId(), + catalog.playableStateNamespaceId(), + catalog.stateScope(), + launch.gameInstanceUuid(), + canonicalVersionId, + activeEpoch, + catalog.catalogRevision(), + CanonicalInitialAdmissionRequest.OriginKind.NO_PRIOR_POINTER, + null, + requestId); + var holdRequest = + new WorldCanonicalInitialAdmissionHold.Request( + workloadNamespace, + catalog.tenantId(), + catalog.worldSlug(), + catalog.realmId(), + catalog.playableStateNamespaceId(), + catalog.stateScope(), + launch.gameInstanceUuid(), + canonicalVersionId, + activeEpoch, + requestId, + requestDigest, + WorldCanonicalInitialAdmissionHold.InitialAdmissionOrigin.NO_PRIOR_POINTER, + catalog.catalogRevision(), + null); + var lifecycleRequest = + new WorldCanonicalInstanceLifecycleEvidence.Request( + WorldCanonicalInstanceLifecycleEvidence.Request.SCHEMA_VERSION, + UUID.randomUUID(), + workloadNamespace, + catalog.tenantId(), + catalog.worldSlug(), + launch.gameInstanceUuid(), + catalog.playableStateNamespaceId(), + catalog.stateScope(), + true, + association.controlPlaneRequestId(), + canonicalVersionId, + association.descriptor().requestDigest(), + association.descriptor().resultDigest(), + association.attestationDigest()); + + write(() -> intents.reserveFixtureStarting(holdRequest, lifecycleRequest)); + requireNoAmbientTransaction(); + HoldIdentity identity = holds.acquire(holdRequest, lifecycleRequest); + write(() -> intents.attachFixtureStarting(holdRequest, identity)); + + var request = + new CanonicalInitialAdmissionRequest( + workloadNamespace, + catalog.tenantId(), + catalog.worldSlug(), + catalog.realmId(), + catalog.playableStateNamespaceId(), + catalog.stateScope(), + launch.gameInstanceUuid(), + canonicalVersionId, + activeEpoch, + catalog.catalogRevision(), + CanonicalInitialAdmissionRequest.OriginKind.NO_PRIOR_POINTER, + null, + requestId, + requestDigest, + identity.holdId(), + identity.holdFence(), + identity.holdBindingDigest()); + write(() -> admissions.reserveFixtureStarting(request)); + requireNoAmbientTransaction(); + CanonicalInitialAdmissionWorldProof worldProof = verifier.verify(request); + write(() -> completions.complete(request, worldProof)); + write(() -> admissions.commitFixture(request, worldProof)); + + CanonicalInitialAdmissionOwnerProof committed = + admissions + .read(workloadNamespace, requestId) + .orElseThrow(() -> new IllegalStateException("Fixture first OPEN was not retained")); + if (committed.outcome() != CanonicalInitialAdmissionOwnerProof.Outcome.COMMITTED) { + throw new IllegalStateException("Fixture first OPEN did not commit"); + } + return committed; + } + + /** Prepares and activates the fixture World instance, returning its ACTIVE lifecycle epoch. */ + private long activateWorld( + long gameSessionTenantId, + long gameInstanceId, + long gameTemplateId, + LaunchDescriptor descriptor) { + var prepared = + world.prepareWorldInstance( + gameSessionTenantId, + gameInstanceId, + gameTemplateId, + descriptor.getControlPlaneRequestId(), + descriptor.getLaunchDescriptorId(), + descriptor.getVersionId(), + descriptor.getScriptPatchVersion(), + descriptor.getRuntimeFlagsJson(), + descriptor.getGenerationConfigRevision(), + descriptor.getReleaseBundleId(), + descriptor.getPublishedReleaseBundleRef(), + descriptor.getVersionStateEpoch(), + descriptor.getRemapSetId()); + if (prepared.hasError() || !prepared.hasWorldInstance()) { + throw new IllegalStateException( + "Fixture World preparation failed: " + + (prepared.hasError() ? prepared.getError().getCode() : "no World snapshot")); + } + WorldInstanceLifecycleSnapshot snapshot = prepared.getWorldInstance(); + if (snapshot.getStatus() + == WorldInstanceLifecycleStatus.WORLD_INSTANCE_LIFECYCLE_STATUS_PREPARING) { + var activated = + world.activatePreparedWorldInstance( + gameSessionTenantId, gameInstanceId, snapshot.getLifecycleEpoch()); + if (activated.hasError() || !activated.hasWorldInstance()) { + throw new IllegalStateException( + "Fixture World activation failed: " + + (activated.hasError() ? activated.getError().getCode() : "no World snapshot")); + } + snapshot = activated.getWorldInstance(); + } + if (snapshot.getStatus() + != WorldInstanceLifecycleStatus.WORLD_INSTANCE_LIFECYCLE_STATUS_ACTIVE) { + throw new IllegalStateException("Fixture World instance is not ACTIVE"); + } + return snapshot.getLifecycleEpoch(); + } + + private void write(Supplier owner) { + writeTransaction.execute(status -> owner.get()); + } + + private static void requireNoAmbientTransaction() { + if (TransactionSynchronizationManager.isActualTransactionActive() + || TransactionSynchronizationManager.isSynchronizationActive()) { + throw new IllegalStateException( + "Fixture first OPEN coordination requires no ambient owner transaction"); + } + } +} diff --git a/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/data/RunOwnedFixtureFirstOpenDriver.java b/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/data/RunOwnedFixtureFirstOpenDriver.java new file mode 100644 index 0000000000..b312c9a7f0 --- /dev/null +++ b/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/data/RunOwnedFixtureFirstOpenDriver.java @@ -0,0 +1,41 @@ +package net.firedevops.firemud.gamesession.data; + +import java.util.Objects; +import java.util.concurrent.atomic.AtomicBoolean; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; +import org.springframework.scheduling.annotation.Scheduled; + +/** + * Retries the canonical run-owned fixture until its first OPEN commits. Each run resumes from the + * owners' retained state; a failure is logged and retried on the next tick. + */ +public final class RunOwnedFixtureFirstOpenDriver { + private static final Logger LOG = LoggerFactory.getLogger(RunOwnedFixtureFirstOpenDriver.class); + private static final long RETRY_INTERVAL_MS = 10_000L; + + private final RunOwnedFixtureFirstOpenCoordinator coordinator; + private final AtomicBoolean opened = new AtomicBoolean(); + + public RunOwnedFixtureFirstOpenDriver(RunOwnedFixtureFirstOpenCoordinator coordinator) { + this.coordinator = Objects.requireNonNull(coordinator, "coordinator"); + } + + @Scheduled(initialDelay = RETRY_INTERVAL_MS, fixedDelay = RETRY_INTERVAL_MS) + public void openWhenReady() { + if (opened.get()) return; + try { + var proof = coordinator.openFirstRealm(); + opened.set(true); + LOG.info( + "Run-owned fixture first OPEN committed (pointerVersion={})", + proof.committedPointerVersion()); + } catch (RuntimeException notYet) { + LOG.warn("Run-owned fixture first OPEN not complete yet: {}", notYet.toString()); + } + } + + public boolean opened() { + return opened.get(); + } +} diff --git a/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/data/RunOwnedInitialAdmissionFixtureCoordinator.java b/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/data/RunOwnedInitialAdmissionFixtureCoordinator.java deleted file mode 100644 index 2c59a056a7..0000000000 --- a/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/data/RunOwnedInitialAdmissionFixtureCoordinator.java +++ /dev/null @@ -1,589 +0,0 @@ -package net.firedevops.firemud.gamesession.data; - -import java.nio.charset.StandardCharsets; -import java.nio.file.Path; -import java.security.MessageDigest; -import java.security.NoSuchAlgorithmException; -import java.util.HexFormat; -import java.util.Objects; -import java.util.UUID; -import java.util.concurrent.atomic.AtomicBoolean; -import java.util.concurrent.atomic.AtomicInteger; -import java.util.concurrent.atomic.AtomicReference; -import net.firedevops.firemud.common.grpc.CommonGrpcClientProperties; -import net.firedevops.firemud.entitymanagement.v1.PlayableStateScope; -import net.firedevops.firemud.gamesession.client.WorldManagementClient; -import net.firedevops.firemud.gamesession.dto.GameInstanceDto; -import net.firedevops.firemud.gamesession.dto.StartSessionRequest; -import net.firedevops.firemud.gamesession.entity.InitialAdmissionBindAttempt; -import net.firedevops.firemud.gamesession.entity.InitialAdmissionBindCatalog; -import net.firedevops.firemud.gamesession.service.GameInstanceService; -import net.firedevops.firemud.gamesession.service.InitialAdmissionBindCatalogDescriptor; -import net.firedevops.firemud.gamesession.service.InitialAdmissionBindHoldBinding; -import net.firedevops.firemud.gamesession.service.InitialAdmissionBindOwnerProof; -import net.firedevops.firemud.gamesession.service.InitialAdmissionBindOwnerProof.Outcome; -import net.firedevops.firemud.gamesession.service.InitialAdmissionBindOwnerService; -import net.firedevops.firemud.gamesession.service.InitialAdmissionBindRequest; -import net.firedevops.firemud.gamesession.service.RunOwnedInitialLaunchResult; -import net.firedevops.firemud.worldmanagement.v1.AcquireInitialAdmissionBindHoldResponse; -import net.firedevops.firemud.worldmanagement.v1.InitialAdmissionBindHold; -import net.firedevops.firemud.worldmanagement.v1.InitialAdmissionBindHoldStatus; -import org.slf4j.Logger; -import org.slf4j.LoggerFactory; -import org.springframework.beans.factory.annotation.Value; -import org.springframework.scheduling.annotation.Scheduled; -import org.springframework.stereotype.Component; - -/** Bounded, internal-only bootstrap for an explicitly claimed run-owned Compose fixture. */ -@Component -public final class RunOwnedInitialAdmissionFixtureCoordinator { - private static final Logger logger = - LoggerFactory.getLogger(RunOwnedInitialAdmissionFixtureCoordinator.class); - private static final int MAX_ATTEMPTS = 12; - private static final long RETRY_INTERVAL_MS = 5_000L; - private static final String RUNNING = "RUNNING"; - private static final String DIGEST_DOMAIN = "firemud.run-owned-initial-admission-bind.v1"; - - private final boolean enabled; - private final String capabilityPath; - private final String sourceReceiptPath; - private final String runId; - private final String composeProjectName; - private final CommonGrpcClientProperties grpcProperties; - private final GameInstanceService gameInstanceService; - private final InitialAdmissionBindOwnerService ownerService; - private final WorldManagementClient worldManagementClient; - private final AtomicInteger attempts = new AtomicInteger(); - private final AtomicBoolean inProgress = new AtomicBoolean(); - private final AtomicBoolean finished = new AtomicBoolean(); - private final AtomicReference acceptedCapability = - new AtomicReference<>(); - private final AtomicReference - acceptedSourceReceipt = new AtomicReference<>(); - - public RunOwnedInitialAdmissionFixtureCoordinator( - @Value("${FIREMUD_SMOKE_INITIAL_ADMISSION_FIXTURE_ENABLED:false}") boolean enabled, - @Value("${FIREMUD_SMOKE_INITIAL_ADMISSION_CAPABILITY_PATH:}") String capabilityPath, - @Value("${FIREMUD_SMOKE_AUTHORED_WORLD_SOURCE_RECEIPT_PATH:}") String sourceReceiptPath, - @Value("${FIREMUD_SMOKE_RUN_ID:}") String runId, - @Value("${FIREMUD_SMOKE_COMPOSE_PROJECT_NAME:}") String composeProjectName, - CommonGrpcClientProperties grpcProperties, - GameInstanceService gameInstanceService, - InitialAdmissionBindOwnerService ownerService, - WorldManagementClient worldManagementClient) { - this.enabled = enabled; - this.capabilityPath = capabilityPath; - this.sourceReceiptPath = sourceReceiptPath; - this.runId = runId; - this.composeProjectName = composeProjectName; - this.grpcProperties = Objects.requireNonNull(grpcProperties, "grpcProperties"); - this.gameInstanceService = Objects.requireNonNull(gameInstanceService, "gameInstanceService"); - this.ownerService = Objects.requireNonNull(ownerService, "ownerService"); - this.worldManagementClient = - Objects.requireNonNull(worldManagementClient, "worldManagementClient"); - } - - @Scheduled(initialDelay = RETRY_INTERVAL_MS, fixedDelay = RETRY_INTERVAL_MS) - void retryRunOwnedFixtureBootstrap() { - if (!enabled || finished.get() || !inProgress.compareAndSet(false, true)) { - return; - } - int attempt = attempts.incrementAndGet(); - if (attempt > MAX_ATTEMPTS) { - finished.set(true); - inProgress.set(false); - return; - } - - try { - RunOwnedInitialAdmissionFixtureCapability capability = - RunOwnedInitialAdmissionFixtureCapability.load( - declaredCapabilityPath(), runId, composeProjectName, grpcProperties); - RunOwnedInitialAdmissionFixtureCapability firstCapability = - acceptedCapability.updateAndGet(existing -> existing == null ? capability : existing); - if (!firstCapability.equals(capability)) { - throw unresolved(); - } - RunOwnedInitialAdmissionFixtureCapability.SourceReceipt sourceReceipt = - RunOwnedInitialAdmissionFixtureCapability.loadSourceReceipt( - declaredSourceReceiptPath(), runId, composeProjectName, capability, grpcProperties); - RunOwnedInitialAdmissionFixtureCapability.SourceReceipt firstSourceReceipt = - acceptedSourceReceipt.updateAndGet( - existing -> existing == null ? sourceReceipt : existing); - if (!firstSourceReceipt.equals(sourceReceipt)) { - throw unresolved(); - } - BootstrapResult result = coordinate(capability, sourceReceipt); - if (result == BootstrapResult.COMMITTED) { - finished.set(true); - logger.info( - "Run-owned initial-admission fixture committed; World hold reconciliation remains" - + " asynchronous."); - } else if (result == BootstrapResult.ABORTED) { - finished.set(true); - logger.warn( - "Run-owned initial-admission fixture has a durable abort; World retains ownership of" - + " hold reconciliation."); - } - } catch (RuntimeException exception) { - SafeDiagnostic diagnostic = safeDiagnostic(exception); - if (attempt >= MAX_ATTEMPTS) { - finished.set(true); - logger.error( - "Run-owned initial-admission fixture did not reach a verified terminal result after" - + " the bounded retry budget; World hold state remains owner-controlled." - + " exceptionType={} errorCode={} message={}", - diagnostic.exceptionType(), - diagnostic.errorCode(), - diagnostic.message()); - } else { - logger.warn( - "Run-owned initial-admission fixture attempt {}/{} remains unresolved; the same" - + " stable operation identity will be retried. exceptionType={} errorCode={}" - + " message={}", - attempt, - MAX_ATTEMPTS, - diagnostic.exceptionType(), - diagnostic.errorCode(), - diagnostic.message()); - } - } finally { - inProgress.set(false); - } - } - - BootstrapResult coordinate( - RunOwnedInitialAdmissionFixtureCapability capability, - RunOwnedInitialAdmissionFixtureCapability.SourceReceipt sourceReceipt) { - Objects.requireNonNull(capability, "capability"); - requireExactSourceReceipt(capability, sourceReceipt); - RunOwnedInitialAdmissionLaunchEvidence launchEvidence = - RunOwnedInitialAdmissionLaunchEvidence.fromVerifiedSourceReceipt(capability, sourceReceipt); - RunOwnedInitialLaunchResult launch = - gameInstanceService.startRunOwnedInitialLaunch( - new StartSessionRequest( - capability.tenantId(), - capability.gameTemplateId(), - capability.operationId(), - capability.ownerAccountId()), - launchEvidence); - GameInstanceDto target = requireExactRunningTarget(launch, capability); - - InitialAdmissionBindCatalogDescriptor descriptor = - new InitialAdmissionBindCatalogDescriptor( - capability.tenantId(), - capability.gameTemplateId(), - capability.worldSlug(), - capability.worldDisplayName(), - capability.realmSlug(), - capability.realmDisplayName(), - capability.requiresCharacterSelection()); - InitialAdmissionBindCatalog catalog = - ownerService.registerPublicSharedFixtureCatalog(descriptor); - requireExactCatalog(catalog, descriptor); - - long gameInstanceId = target.id(); - long versionId = target.versionId(); - long activeLifecycleEpoch = launch.activeLifecycleEpoch(); - String requestDigest = - requestDigest(capability, catalog, gameInstanceId, versionId, activeLifecycleEpoch); - InitialAdmissionBindRequest request = - new InitialAdmissionBindRequest( - capability.tenantId(), - capability.worldSlug(), - capability.realmSlug(), - capability.operationId(), - requestDigest, - gameInstanceId, - versionId, - activeLifecycleEpoch); - InitialAdmissionBindAttempt attempt = ownerService.beginIntent(request); - requireExactAttempt(attempt, request, catalog, null, null); - - AcquireInitialAdmissionBindHoldResponse response = - worldManagementClient.acquireInitialAdmissionBindHold( - capability.tenantId(), - gameInstanceId, - versionId, - activeLifecycleEpoch, - capability.operationId(), - requestDigest, - catalog.realmId(), - catalog.playableStateNamespaceId(), - PlayableStateScope.PLAYABLE_STATE_SCOPE_SHARED, - catalog.catalogRevision()); - if (response == null || response.hasError() || !response.hasHold()) { - throw unresolved(); - } - InitialAdmissionBindHold hold = response.getHold(); - InitialAdmissionBindHoldBinding binding = - requireExactHold(hold, request, catalog, gameInstanceId, versionId, activeLifecycleEpoch); - - if (isTerminalHoldStatus(hold.getStatus())) { - return resultFromProof( - ownerService.read(binding), binding, attempt, request.initialAdmissionRequestId()); - } - if (!isRetryableHoldStatus(hold.getStatus())) { - throw unresolved(); - } - - InitialAdmissionBindAttempt attached = ownerService.attachHold(binding); - requireExactAttempt(attached, request, catalog, binding.holdId(), binding.holdFence()); - InitialAdmissionBindOwnerProof proof = - attached.status() == InitialAdmissionBindAttempt.Status.PENDING - ? ownerService.commit(binding) - : ownerService.read(binding); - return resultFromProof(proof, binding, attached, request.initialAdmissionRequestId()); - } - - private Path declaredCapabilityPath() { - if (capabilityPath == null || capabilityPath.isBlank()) { - throw unresolved(); - } - try { - return Path.of(capabilityPath); - } catch (RuntimeException exception) { - throw unresolved(); - } - } - - private Path declaredSourceReceiptPath() { - if (sourceReceiptPath == null || sourceReceiptPath.isBlank()) { - throw unresolved(); - } - try { - return Path.of(sourceReceiptPath); - } catch (RuntimeException exception) { - throw unresolved(); - } - } - - static void requireExactSourceReceipt( - RunOwnedInitialAdmissionFixtureCapability capability, - RunOwnedInitialAdmissionFixtureCapability.SourceReceipt receipt) { - if (receipt == null - || !RunOwnedInitialAdmissionFixtureCapability.SOURCE_RECEIPT_SCHEMA.equals(receipt.schema()) - || !capability.runId().equals(receipt.runId()) - || !capability.composeProjectName().equals(receipt.composeProjectName()) - || !capability.operationId().equals(receipt.fixtureOperationId()) - || !RunOwnedInitialAdmissionFixtureCapability.SOURCE_RECEIPT_OWNER_SERVICE.equals( - receipt.ownerService()) - || !capability.gameSessionUriSan().equals(receipt.gameSessionUriSan()) - || !capability.gameSessionLeafSha256().equals(receipt.gameSessionLeafSha256()) - || !capability.caCertificateSha256().equals(receipt.caCertificateSha256()) - || !capability.worldManagementUriSan().equals(receipt.worldManagementUriSan()) - || !capability.worldManagementLeafSha256().equals(receipt.worldManagementLeafSha256()) - || receipt.sourceEvidence() == null - || !RunOwnedInitialAdmissionFixtureCapability.SOURCE_TARGET_NAMESPACE.equals( - receipt.sourceEvidence().targetNamespace()) - || receipt.launchReadEvidence() == null - || receipt.launchReadEvidence().launchDescriptor() == null - || !RunOwnedInitialAdmissionFixtureCapability.LAUNCH_READ_EVIDENCE_SCHEMA.equals( - receipt.launchReadEvidence().schema()) - || receipt.launchReadEvidence().gameTemplateId() != capability.gameTemplateId() - || !capability - .operationId() - .equals(receipt.sourceEvidence().registrationRequestId().toString()) - || !capability.worldSlug().equals(receipt.sourceEvidence().worldSlug()) - || !capability.worldDisplayName().equals(receipt.sourceEvidence().worldDisplayName()) - || !Long.toString(capability.tenantId()) - .equals(receipt.sourceEvidence().sourceGameTenantKey())) { - throw unresolved(); - } - } - - private static GameInstanceDto requireExactRunningTarget( - RunOwnedInitialLaunchResult launch, RunOwnedInitialAdmissionFixtureCapability capability) { - if (launch == null || launch.gameInstance() == null || launch.activeLifecycleEpoch() <= 0L) { - throw unresolved(); - } - GameInstanceDto target = launch.gameInstance(); - if (target.id() == null - || target.id() <= 0L - || target.tenantId() == null - || target.tenantId() != capability.tenantId() - || target.gameTemplateId() == null - || target.gameTemplateId() != capability.gameTemplateId() - || target.ownerAccountId() == null - || target.ownerAccountId() != capability.ownerAccountId() - || target.versionId() == null - || target.versionId() <= 0L - || target.launchDescriptorId() == null - || target.launchDescriptorId().isBlank() - || !RUNNING.equals(target.status())) { - throw unresolved(); - } - return target; - } - - private static void requireExactCatalog( - InitialAdmissionBindCatalog catalog, InitialAdmissionBindCatalogDescriptor descriptor) { - if (catalog == null - || catalog.realmId() == null - || catalog.playableStateNamespaceId() == null - || catalog.tenantId() != descriptor.tenantId() - || catalog.gameTemplateId() != descriptor.gameTemplateId() - || !descriptor.worldSlug().equals(catalog.worldSlug()) - || !descriptor.worldDisplayName().equals(catalog.worldDisplayName()) - || !descriptor.realmSlug().equals(catalog.realmSlug()) - || !descriptor.realmDisplayName().equals(catalog.realmDisplayName()) - || catalog.catalogRevision() <= 0L - || !catalog.visible() - || !catalog.publicProductionRealm() - || catalog.requiresCharacterSelection() != descriptor.requiresCharacterSelection() - || !RunOwnedInitialAdmissionFixtureCapability.STATE_SCOPE.equals(catalog.stateScope()) - || !RunOwnedInitialAdmissionFixtureCapability.CHARACTER_CREATION_POLICY.equals( - catalog.characterCreationPolicy())) { - throw unresolved(); - } - } - - private static void requireExactAttempt( - InitialAdmissionBindAttempt attempt, - InitialAdmissionBindRequest request, - InitialAdmissionBindCatalog catalog, - String holdId, - String holdFence) { - if (attempt == null - || attempt.attemptId() == null - || attempt.tenantId() != request.tenantId() - || !request.initialAdmissionRequestId().equals(attempt.initialAdmissionRequestId()) - || !request.requestDigest().equals(attempt.requestDigest()) - || !catalog.realmId().equals(attempt.realmId()) - || !catalog.playableStateNamespaceId().equals(attempt.playableStateNamespaceId()) - || !RunOwnedInitialAdmissionFixtureCapability.STATE_SCOPE.equals( - attempt.playableStateScope()) - || !attempt.expectedNoPriorPointer() - || attempt.catalogRevision() != catalog.catalogRevision() - || attempt.gameInstanceId() != request.gameInstanceId() - || attempt.versionId() != request.versionId() - || attempt.activeLifecycleEpoch() != request.activeLifecycleEpoch() - || (holdId != null && !holdId.equals(asCanonicalUuid(attempt.holdId()))) - || (holdFence != null && !holdFence.equals(asCanonicalUuid(attempt.holdFence())))) { - throw unresolved(); - } - } - - private static InitialAdmissionBindHoldBinding requireExactHold( - InitialAdmissionBindHold hold, - InitialAdmissionBindRequest request, - InitialAdmissionBindCatalog catalog, - long gameInstanceId, - long versionId, - long activeLifecycleEpoch) { - if (hold == null - || !isCanonicalUuid(hold.getHoldId()) - || !isCanonicalUuid(hold.getHoldFence()) - || !Long.toString(request.tenantId()).equals(hold.getTenantId()) - || !catalog.realmId().toString().equals(hold.getRealmUuid()) - || !catalog - .playableStateNamespaceId() - .toString() - .equals(hold.getPlayableStateNamespaceUuid()) - || hold.getPlayableStateScope() != PlayableStateScope.PLAYABLE_STATE_SCOPE_SHARED - || !Long.toString(gameInstanceId).equals(hold.getGameInstanceId()) - || !Long.toString(versionId).equals(hold.getVersionId()) - || hold.getActiveLifecycleEpoch() != activeLifecycleEpoch - || !request.initialAdmissionRequestId().equals(hold.getInitialAdmissionRequestId()) - || !request.requestDigest().equals(hold.getRequestDigest()) - || !hold.getExpectedNoPriorPointer() - || hold.getExpectedCatalogRevision() != catalog.catalogRevision() - || hold.getStatus() - == InitialAdmissionBindHoldStatus.INITIAL_ADMISSION_BIND_HOLD_STATUS_UNSPECIFIED) { - throw unresolved(); - } - return new InitialAdmissionBindHoldBinding( - hold.getHoldId(), - hold.getHoldFence(), - request.tenantId(), - hold.getRealmUuid(), - hold.getPlayableStateNamespaceUuid(), - RunOwnedInitialAdmissionFixtureCapability.STATE_SCOPE, - gameInstanceId, - versionId, - activeLifecycleEpoch, - request.initialAdmissionRequestId(), - request.requestDigest(), - true, - catalog.catalogRevision()); - } - - private static BootstrapResult resultFromProof( - InitialAdmissionBindOwnerProof proof, - InitialAdmissionBindHoldBinding binding, - InitialAdmissionBindAttempt attempt, - String expectedRequestId) { - if (!matchesExactProof(proof, binding, attempt, expectedRequestId)) { - throw unresolved(); - } - if (proof.outcome() == Outcome.COMMITTED) { - return BootstrapResult.COMMITTED; - } - if (proof.outcome() == Outcome.ABORTED && proof.futureCommitPrevented()) { - return BootstrapResult.ABORTED; - } - throw unresolved(); - } - - private static boolean matchesExactProof( - InitialAdmissionBindOwnerProof proof, - InitialAdmissionBindHoldBinding binding, - InitialAdmissionBindAttempt attempt, - String expectedRequestId) { - if (proof == null - || proof.holdId() == null - || !binding.holdId().equals(proof.holdId()) - || !binding.holdFence().equals(proof.holdFence()) - || proof.tenantId() != binding.tenantId() - || !binding.realmUuid().equals(proof.realmUuid()) - || !binding.playableStateNamespaceUuid().equals(proof.playableStateNamespaceUuid()) - || !binding.playableStateScope().equals(proof.playableStateScope()) - || proof.gameInstanceId() != binding.gameInstanceId() - || proof.versionId() != binding.versionId() - || proof.activeLifecycleEpoch() != binding.activeLifecycleEpoch() - || !expectedRequestId.equals(proof.initialAdmissionRequestId()) - || !binding.requestDigest().equals(proof.requestDigest()) - || proof.expectedNoPriorPointer() != binding.expectedNoPriorPointer() - || proof.expectedCatalogRevision() != binding.expectedCatalogRevision() - || attempt == null - || !attempt.attemptId().toString().equals(proof.ownerProofId())) { - return false; - } - - if (proof.outcome() == Outcome.COMMITTED) { - return proof.pointerAuditId() != null - && isCanonicalPositiveLong(proof.pointerAuditId()) - && proof.pointerVersion() == 1L - && binding.requestDigest().equals(proof.pointerAuditRequestDigest()) - && !proof.futureCommitPrevented(); - } - if (proof.outcome() == Outcome.ABORTED) { - return proof.pointerAuditId() == null - && proof.pointerVersion() == 0L - && proof.pointerAuditRequestDigest() == null - && proof.futureCommitPrevented(); - } - return false; - } - - private static boolean isTerminalHoldStatus(InitialAdmissionBindHoldStatus status) { - return status == InitialAdmissionBindHoldStatus.INITIAL_ADMISSION_BIND_HOLD_STATUS_COMMITTED - || status == InitialAdmissionBindHoldStatus.INITIAL_ADMISSION_BIND_HOLD_STATUS_ABORTED; - } - - private static boolean isRetryableHoldStatus(InitialAdmissionBindHoldStatus status) { - return status == InitialAdmissionBindHoldStatus.INITIAL_ADMISSION_BIND_HOLD_STATUS_PENDING - || status - == InitialAdmissionBindHoldStatus - .INITIAL_ADMISSION_BIND_HOLD_STATUS_RECONCILIATION_REQUIRED; - } - - private static String requestDigest( - RunOwnedInitialAdmissionFixtureCapability capability, - InitialAdmissionBindCatalog catalog, - long gameInstanceId, - long versionId, - long activeLifecycleEpoch) { - StringBuilder canonical = new StringBuilder(); - appendDigestField(canonical, "domain", DIGEST_DOMAIN); - appendDigestField(canonical, "operationId", capability.operationId()); - appendDigestField(canonical, "tenantId", Long.toString(capability.tenantId())); - appendDigestField(canonical, "gameTemplateId", Long.toString(capability.gameTemplateId())); - appendDigestField(canonical, "ownerAccountId", Long.toString(capability.ownerAccountId())); - appendDigestField(canonical, "worldSlug", capability.worldSlug()); - appendDigestField(canonical, "worldDisplayName", capability.worldDisplayName()); - appendDigestField(canonical, "realmSlug", capability.realmSlug()); - appendDigestField(canonical, "realmDisplayName", capability.realmDisplayName()); - appendDigestField( - canonical, - "requiresCharacterSelection", - Boolean.toString(capability.requiresCharacterSelection())); - appendDigestField(canonical, "realmId", catalog.realmId().toString()); - appendDigestField( - canonical, "playableStateNamespaceId", catalog.playableStateNamespaceId().toString()); - appendDigestField( - canonical, "playableStateScope", RunOwnedInitialAdmissionFixtureCapability.STATE_SCOPE); - appendDigestField(canonical, "expectedNoPriorPointer", "true"); - appendDigestField(canonical, "gameInstanceId", Long.toString(gameInstanceId)); - appendDigestField(canonical, "versionId", Long.toString(versionId)); - appendDigestField(canonical, "activeLifecycleEpoch", Long.toString(activeLifecycleEpoch)); - appendDigestField(canonical, "catalogRevision", Long.toString(catalog.catalogRevision())); - try { - return HexFormat.of() - .formatHex( - MessageDigest.getInstance("SHA-256") - .digest(canonical.toString().getBytes(StandardCharsets.UTF_8))); - } catch (NoSuchAlgorithmException exception) { - throw new IllegalStateException("SHA-256 is unavailable", exception); - } - } - - private static void appendDigestField(StringBuilder canonical, String name, String value) { - int nameBytes = name.getBytes(StandardCharsets.UTF_8).length; - int valueBytes = value.getBytes(StandardCharsets.UTF_8).length; - canonical - .append(nameBytes) - .append(':') - .append(name) - .append(valueBytes) - .append(':') - .append(value); - } - - private static String asCanonicalUuid(UUID value) { - return value == null ? null : value.toString(); - } - - private static boolean isCanonicalUuid(String value) { - if (value == null) { - return false; - } - try { - return UUID.fromString(value).toString().equals(value); - } catch (IllegalArgumentException exception) { - return false; - } - } - - private static boolean isCanonicalPositiveLong(String value) { - if (value == null) { - return false; - } - try { - long parsed = Long.parseLong(value); - return parsed > 0L && Long.toString(parsed).equals(value); - } catch (NumberFormatException exception) { - return false; - } - } - - private static RuntimeException unresolved() { - return new IllegalStateException("Run-owned initial-admission fixture remains unresolved"); - } - - private static SafeDiagnostic safeDiagnostic(RuntimeException exception) { - if (exception instanceof IllegalArgumentException) { - return new SafeDiagnostic( - exception.getClass().getSimpleName(), - "FIXTURE_INPUT_REJECTED", - "Fixture input or owner response was rejected."); - } - if (exception instanceof IllegalStateException) { - return new SafeDiagnostic( - exception.getClass().getSimpleName(), - "FIXTURE_STATE_UNRESOLVED", - "Fixture state remains unresolved."); - } - return new SafeDiagnostic( - exception.getClass().getSimpleName(), - "FIXTURE_ATTEMPT_FAILED", - "Fixture dependency attempt failed."); - } - - private record SafeDiagnostic(String exceptionType, String errorCode, String message) {} - - enum BootstrapResult { - COMMITTED, - ABORTED - } -} diff --git a/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/dto/CanonicalGameInstanceLaunchAssociation.java b/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/dto/CanonicalGameInstanceLaunchAssociation.java index d58cdedeba..11360ab30f 100644 --- a/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/dto/CanonicalGameInstanceLaunchAssociation.java +++ b/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/dto/CanonicalGameInstanceLaunchAssociation.java @@ -2,6 +2,7 @@ import java.util.Objects; import java.util.UUID; +import net.firedevops.firemud.common.gamedesign.AuthoredWorldLaunchDescriptorEvidence; import net.firedevops.firemud.common.gamedesign.CompleteLaunchBindingEvidence; import net.firedevops.firemud.common.publication.RealmEntryPolicy; import net.firedevops.firemud.common.tenant.AuthoredWorldSourceDigest; @@ -22,7 +23,10 @@ public record CanonicalGameInstanceLaunchAssociation( long capturedStartingRowVersion, CompleteLaunchBindingEvidence launchBindingEvidence, CurrentGameInstanceStatus currentGameInstanceStatus, - long currentRowVersion) { + long currentRowVersion, + AuthoredWorldLaunchDescriptorEvidence fixtureDescriptor, + String fixtureProvenanceDigest, + UUID fixtureCanonicalVersionId) { private static final UUID NIL_UUID = new UUID(0L, 0L); public enum CurrentGameInstanceStatus { @@ -51,16 +55,28 @@ public enum CurrentGameInstanceStatus { if (capturedStartingRowVersion < 0) { throw new IllegalArgumentException("capturedStartingRowVersion must not be negative"); } - Objects.requireNonNull(launchBindingEvidence, "launchBindingEvidence"); + if ((launchBindingEvidence == null) == (fixtureDescriptor == null) + || (fixtureDescriptor == null) != (fixtureProvenanceDigest == null) + || (fixtureDescriptor == null) != (fixtureCanonicalVersionId == null)) { + throw new IllegalArgumentException( + "Launch association requires exactly one Human binding or run-owned fixture descriptor"); + } + if (fixtureProvenanceDigest != null + && !fixtureProvenanceDigest.matches("sha256:[0-9a-f]{64}")) { + throw new IllegalArgumentException("fixtureProvenanceDigest must be a prefixed SHA-256"); + } Objects.requireNonNull(currentGameInstanceStatus, "currentGameInstanceStatus"); if (currentRowVersion < capturedStartingRowVersion) { throw new IllegalArgumentException( "currentRowVersion must not precede the captured STARTING row version"); } - var descriptor = launchBindingEvidence.descriptor(); + var descriptor = + launchBindingEvidence != null ? launchBindingEvidence.descriptor() : fixtureDescriptor; descriptor.requireValid(); - launchBindingEvidence.releaseAttestation().requireValid(descriptor); + if (launchBindingEvidence != null) { + launchBindingEvidence.releaseAttestation().requireValid(descriptor); + } if (!targetNamespace.equals(descriptor.targetNamespace()) || !canonicalTenantId.equals(descriptor.canonicalTenantId()) || !worldSlug.equals(descriptor.worldSlug()) @@ -71,6 +87,70 @@ public enum CurrentGameInstanceStatus { } } + /** Existing Human launch association constructor retained at its call sites. */ + public CanonicalGameInstanceLaunchAssociation( + String targetNamespace, + long gameSessionTenantId, + UUID tenantAssociationOperationId, + UUID canonicalTenantId, + UUID gameInstanceUuid, + String worldSlug, + UUID playableStateNamespaceId, + RealmEntryPolicy.StateScope playableStateScope, + boolean publicProduction, + String controlPlaneRequestId, + String launchDescriptorId, + long capturedStartingRowVersion, + CompleteLaunchBindingEvidence launchBindingEvidence, + CurrentGameInstanceStatus currentGameInstanceStatus, + long currentRowVersion) { + this( + targetNamespace, + gameSessionTenantId, + tenantAssociationOperationId, + canonicalTenantId, + gameInstanceUuid, + worldSlug, + playableStateNamespaceId, + playableStateScope, + publicProduction, + controlPlaneRequestId, + launchDescriptorId, + capturedStartingRowVersion, + Objects.requireNonNull(launchBindingEvidence, "launchBindingEvidence"), + currentGameInstanceStatus, + currentRowVersion, + null, + null, + null); + } + + /** Canonical content version from retained publication or fixture policy evidence. */ + public UUID canonicalVersionId() { + return launchBindingEvidence != null + ? launchBindingEvidence.releaseAttestation().canonicalVersionId() + : fixtureCanonicalVersionId; + } + + public boolean isRunOwnedFixture() { + return fixtureDescriptor != null; + } + + /** The authored launch descriptor of either variant. */ + public AuthoredWorldLaunchDescriptorEvidence descriptor() { + return launchBindingEvidence != null ? launchBindingEvidence.descriptor() : fixtureDescriptor; + } + + /** + * The Human release-attestation digest, or for the run-owned fixture its policy-seal evidence + * digest, which takes the attestation's place in lifecycle and intent bindings. + */ + public String attestationDigest() { + return launchBindingEvidence != null + ? launchBindingEvidence.releaseAttestation().evidenceDigest() + : fixtureProvenanceDigest; + } + private static void requireNonNil(UUID value, String name) { if (value == null || NIL_UUID.equals(value)) { throw new IllegalArgumentException(name + " must be a non-nil UUID"); diff --git a/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/dto/CanonicalInitialAdmissionLaunchTarget.java b/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/dto/CanonicalInitialAdmissionLaunchTarget.java index 4a6a5502dc..e9fb34f6b8 100644 --- a/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/dto/CanonicalInitialAdmissionLaunchTarget.java +++ b/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/dto/CanonicalInitialAdmissionLaunchTarget.java @@ -15,7 +15,7 @@ public record CanonicalInitialAdmissionLaunchTarget( if (gameInstanceId <= 0L || runtimeVersionId <= 0L) { throw new IllegalArgumentException("Canonical launch target identifiers must be positive"); } - if (association.launchBindingEvidence().descriptor().versionId() != runtimeVersionId) { + if (association.descriptor().versionId() != runtimeVersionId) { throw new IllegalArgumentException( "Current runtime version does not match the canonical launch descriptor"); } @@ -23,6 +23,6 @@ public record CanonicalInitialAdmissionLaunchTarget( /** Canonical content version from retained publication evidence, never from the numeric row. */ public UUID canonicalVersionId() { - return association.launchBindingEvidence().releaseAttestation().canonicalVersionId(); + return association.canonicalVersionId(); } } diff --git a/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/repository/CanonicalGameInstanceLaunchAssociationRepository.java b/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/repository/CanonicalGameInstanceLaunchAssociationRepository.java index 004306f200..9ac6037c18 100644 --- a/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/repository/CanonicalGameInstanceLaunchAssociationRepository.java +++ b/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/repository/CanonicalGameInstanceLaunchAssociationRepository.java @@ -1251,7 +1251,8 @@ public CanonicalInitialAdmissionLaunchTarget lockStartingForHumanRuntimeCompleti lockForInitialAdmission( targetNamespace, canonicalTenantId, realmId, canonicalGameInstanceId, false); CanonicalGameInstanceLaunchAssociation association = target.association(); - if (association.currentGameInstanceStatus() != CurrentGameInstanceStatus.STARTING + if (association.isRunOwnedFixture() + || association.currentGameInstanceStatus() != CurrentGameInstanceStatus.STARTING || association.currentRowVersion() != association.capturedStartingRowVersion()) { throw new IllegalStateException( "Human runtime completion requires the exact captured STARTING owner row"); @@ -1259,6 +1260,25 @@ public CanonicalInitialAdmissionLaunchTarget lockStartingForHumanRuntimeCompleti return target; } + /** + * Purpose-specific run-owned fixture lock for its exact captured STARTING row. Human launches are + * refused; ordinary admission readers remain RUNNING-only. + */ + public CanonicalInitialAdmissionLaunchTarget lockStartingForFixtureRuntimeCompletion( + String targetNamespace, UUID canonicalTenantId, UUID realmId, UUID canonicalGameInstanceId) { + CanonicalInitialAdmissionLaunchTarget target = + lockForInitialAdmission( + targetNamespace, canonicalTenantId, realmId, canonicalGameInstanceId, false); + CanonicalGameInstanceLaunchAssociation association = target.association(); + if (!association.isRunOwnedFixture() + || association.currentGameInstanceStatus() != CurrentGameInstanceStatus.STARTING + || association.currentRowVersion() != association.capturedStartingRowVersion()) { + throw new IllegalStateException( + "Run-owned fixture completion requires the exact captured fixture STARTING owner row"); + } + return target; + } + /** Reads the exact launch association and current runtime row after owner commit. */ public Optional readForInitialAdmission( String targetNamespace, UUID canonicalTenantId, UUID realmId, UUID canonicalGameInstanceId) { @@ -1524,11 +1544,42 @@ private Optional findByRequest(String controlPlaneRequestId, boolean for private CanonicalGameInstanceLaunchAssociation toAssociation(Record row) { try { - CompleteLaunchBindingEvidence evidence = - JSON.readValue( - row.get("complete_launch_binding_evidence", JSONB.class).data(), - CompleteLaunchBindingEvidence.class); - ValidatedBinding binding = validateBinding(evidence); + boolean fixture = row.get("fixture_policy_request_bytes", byte[].class) != null; + CompleteLaunchBindingEvidence evidence = null; + net.firedevops.firemud.common.gamedesign.AuthoredWorldLaunchDescriptorEvidence + fixtureDescriptor = null; + String fixtureProvenanceDigest = null; + UUID fixtureCanonicalVersionId = null; + if (fixture) { + // The run-owned fixture retains its verified descriptor and policy seal; its seal evidence + // digest takes the release attestation's place. + var tree = JSON.readTree(row.get("complete_launch_binding_evidence", JSONB.class).data()); + fixtureDescriptor = + JSON.treeToValue( + tree.get("descriptor"), + net.firedevops.firemud.common.gamedesign.AuthoredWorldLaunchDescriptorEvidence + .class); + fixtureDescriptor.requireValid(); + requireRequestId(fixtureDescriptor.controlPlaneRequestId()); + fixtureProvenanceDigest = row.get("fixture_policy_seal_evidence_digest", String.class); + fixtureCanonicalVersionId = + UUID.fromString( + net.firedevops.firemud.common.smoke.RunOwnedInitialAdmissionFixtureWireCodec + .parseFixturePolicyRequestBytes( + row.get("fixture_policy_request_bytes", byte[].class)) + .launchReadEvidence() + .publishedReleaseBundle() + .getCanonicalVersionId()); + } else { + evidence = + JSON.readValue( + row.get("complete_launch_binding_evidence", JSONB.class).data(), + CompleteLaunchBindingEvidence.class); + } + DescriptorBinding binding = + fixture + ? new DescriptorBinding(fixtureDescriptor) + : new DescriptorBinding(validateBinding(evidence).descriptor()); UUID canonicalTenantId = row.get("canonical_tenant_id", UUID.class); UUID associationOperationId = row.get("tenant_association_operation_id", UUID.class); UUID gameInstanceUuid = row.get("game_instance_uuid", UUID.class); @@ -1575,7 +1626,7 @@ private CanonicalGameInstanceLaunchAssociation toAssociation(Record row) { row.get("current_version_state_epoch", Long.class), row.get("current_run_owned_start_request_id", String.class), row.get("current_run_owned_start_published_release_bundle_ref", String.class)); - requireRuntimeBinding(current, evidence); + requireRuntimeBinding(current, binding.descriptor()); if (!gameInstanceUuid.equals(current.gameInstanceUuid()) || current.rowVersion() < row.get("captured_starting_row_version", Long.class) || !RealmEntryPolicy.StateScope.SHARED @@ -1599,7 +1650,10 @@ private CanonicalGameInstanceLaunchAssociation toAssociation(Record row) { row.get("captured_starting_row_version", Long.class), evidence, CurrentGameInstanceStatus.valueOf(current.status()), - current.rowVersion()); + current.rowVersion(), + fixtureDescriptor, + fixtureProvenanceDigest, + fixtureCanonicalVersionId); } catch (RuntimeException exception) { if (exception instanceof IllegalStateException illegalState) { throw illegalState; @@ -1669,7 +1723,12 @@ private static void requireStartingRuntime( private static void requireRuntimeBinding( GameInstanceRow runtime, CompleteLaunchBindingEvidence evidence) { - var descriptor = evidence.descriptor(); + requireRuntimeBinding(runtime, evidence.descriptor()); + } + + private static void requireRuntimeBinding( + GameInstanceRow runtime, + net.firedevops.firemud.common.gamedesign.AuthoredWorldLaunchDescriptorEvidence descriptor) { if (runtime.id() <= 0 || runtime.tenantId() <= 0 || runtime.gameInstanceUuid() == null @@ -1830,6 +1889,9 @@ private record ValidatedBinding(CompleteLaunchBindingEvidence evidence) { } } + private record DescriptorBinding( + net.firedevops.firemud.common.gamedesign.AuthoredWorldLaunchDescriptorEvidence descriptor) {} + private record FreshTenantOwnerMapping(UUID operationId) {} private record RealmOwnerProjection( diff --git a/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/repository/CanonicalGameplayAdmissionAbortManualFactory.java b/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/repository/CanonicalGameplayAdmissionAbortManualFactory.java index 7313057d32..61b2e150da 100644 --- a/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/repository/CanonicalGameplayAdmissionAbortManualFactory.java +++ b/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/repository/CanonicalGameplayAdmissionAbortManualFactory.java @@ -54,6 +54,27 @@ public static CanonicalGameplayAdmissionAbortOwner createUnregisteredOwner( Objects.requireNonNull(accountClient, "Account gameplay lease client required")); } + /** Complete discovery and JOIN-resolution receiver for Spring registration. */ + public static CanonicalGameplayAdmissionDecisionReadGrpcService createDecisionReadReceiver( + DSLContext dsl, + String workloadNamespace, + net.firedevops.firemud.gamesession.service.CanonicalPlayerRouteReadService routeReader, + net.firedevops.firemud.gamesession.service.CanonicalPublishedPlayerRouteReadService + publishedReader, + CanonicalGameInstanceLaunchAssociationRepository launchReader, + net.firedevops.firemud.common.world.WorldCanonicalInstanceLifecycleClient world) { + return new CanonicalGameplayAdmissionDecisionReadGrpcService( + new CanonicalGameplayBindingInventoryRepository( + Objects.requireNonNull(dsl, "Game Session SQL context required")), + new CanonicalGameplayAdmissionDecisionReadWorkloadGuard(workloadNamespace), + workloadNamespace, + null, + Objects.requireNonNull(routeReader, "Canonical route reader required"), + Objects.requireNonNull(publishedReader, "Published route reader required"), + Objects.requireNonNull(launchReader, "Launch association reader required"), + Objects.requireNonNull(world, "World lifecycle client required")); + } + public static CanonicalGameplayAdmissionDecisionReadGrpcService createUnregisteredDecisionReadReceiver(DSLContext dsl, String workloadNamespace) { var repository = diff --git a/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/repository/CanonicalInitialAdmissionIntentRepository.java b/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/repository/CanonicalInitialAdmissionIntentRepository.java index cf9894c9fb..bda94f7e79 100644 --- a/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/repository/CanonicalInitialAdmissionIntentRepository.java +++ b/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/repository/CanonicalInitialAdmissionIntentRepository.java @@ -44,19 +44,29 @@ public CanonicalInitialAdmissionIntentRepository( /** Locks both Game Session owner sources and commits exact World request bytes before acquire. */ public CanonicalInitialAdmissionIntentSnapshot reserve( Request holdRequest, WorldCanonicalInstanceLifecycleEvidence.Request lifecycleRequest) { - return reserve(holdRequest, lifecycleRequest, false); + return reserve(holdRequest, lifecycleRequest, LaunchMode.RUNNING); } /** Retains the exact Human pre-hold intent while its launch is still STARTING. */ public CanonicalInitialAdmissionIntentSnapshot reserveHumanStarting( Request holdRequest, WorldCanonicalInstanceLifecycleEvidence.Request lifecycleRequest) { - return reserve(holdRequest, lifecycleRequest, true); + return reserve(holdRequest, lifecycleRequest, LaunchMode.HUMAN_STARTING); + } + + /** + * Retains the exact run-owned fixture pre-hold intent while its launch is still STARTING. The + * fixture has no original StartSession tuple; its policy-seal evidence digest stands in for the + * release attestation. + */ + public CanonicalInitialAdmissionIntentSnapshot reserveFixtureStarting( + Request holdRequest, WorldCanonicalInstanceLifecycleEvidence.Request lifecycleRequest) { + return reserve(holdRequest, lifecycleRequest, LaunchMode.FIXTURE_STARTING); } private CanonicalInitialAdmissionIntentSnapshot reserve( Request holdRequest, WorldCanonicalInstanceLifecycleEvidence.Request lifecycleRequest, - boolean requireStarting) { + LaunchMode mode) { Objects.requireNonNull(holdRequest, "holdRequest"); Objects.requireNonNull(lifecycleRequest, "lifecycleRequest"); requireIntentRequestId(holdRequest.initialAdmissionRequestId()); @@ -65,7 +75,7 @@ private CanonicalInitialAdmissionIntentSnapshot reserve( boundedRequestBytes(lifecycleRequest.canonicalBytes(), "lifecycle request"); requireWritableReadCommittedOwnerTransaction(); - LockedSources sources = lockSources(holdRequest, requireStarting); + LockedSources sources = lockSources(holdRequest, mode); CanonicalInitialAdmissionIntentSnapshot.requireExactBinding( holdRequest, lifecycleRequest, sources.binding()); @@ -103,17 +113,23 @@ private CanonicalInitialAdmissionIntentSnapshot reserve( /** Attaches only World-issued acquisition identity to an already committed exact intent. */ public CanonicalInitialAdmissionIntentSnapshot attach( Request exactHoldRequest, HoldIdentity holdIdentity) { - return attach(exactHoldRequest, holdIdentity, false); + return attach(exactHoldRequest, holdIdentity, LaunchMode.RUNNING); } /** Attaches the exact World identity to a retained Human STARTING intent. */ public CanonicalInitialAdmissionIntentSnapshot attachHumanStarting( Request exactHoldRequest, HoldIdentity holdIdentity) { - return attach(exactHoldRequest, holdIdentity, true); + return attach(exactHoldRequest, holdIdentity, LaunchMode.HUMAN_STARTING); + } + + /** Attaches the exact World identity to a retained run-owned fixture STARTING intent. */ + public CanonicalInitialAdmissionIntentSnapshot attachFixtureStarting( + Request exactHoldRequest, HoldIdentity holdIdentity) { + return attach(exactHoldRequest, holdIdentity, LaunchMode.FIXTURE_STARTING); } private CanonicalInitialAdmissionIntentSnapshot attach( - Request exactHoldRequest, HoldIdentity holdIdentity, boolean requireStarting) { + Request exactHoldRequest, HoldIdentity holdIdentity, LaunchMode mode) { Objects.requireNonNull(exactHoldRequest, "exactHoldRequest"); Objects.requireNonNull(holdIdentity, "holdIdentity"); requireIntentRequestId(exactHoldRequest.initialAdmissionRequestId()); @@ -129,7 +145,7 @@ private CanonicalInitialAdmissionIntentSnapshot attach( } requireWritableReadCommittedOwnerTransaction(); - LockedSources sources = lockSources(exactHoldRequest, requireStarting); + LockedSources sources = lockSources(exactHoldRequest, mode); Record existing = findIntent( exactHoldRequest.targetNamespace(), exactHoldRequest.initialAdmissionRequestId(), true); @@ -196,7 +212,7 @@ public Optional read( return row == null ? Optional.empty() : Optional.of(decodeSnapshot(row)); } - private LockedSources lockSources(Request request, boolean requireStarting) { + private LockedSources lockSources(Request request, LaunchMode mode) { CanonicalRealmCatalogSnapshot catalog = catalogRepository.lockInitialAdmissionTarget( request.targetNamespace(), @@ -204,21 +220,38 @@ private LockedSources lockSources(Request request, boolean requireStarting) { request.realmId(), request.expectedCatalogRevision()); CanonicalInitialAdmissionLaunchTarget launch = - requireStarting - ? launchRepository.lockStartingForHumanRuntimeCompletion( - request.targetNamespace(), - request.canonicalTenantId(), - request.realmId(), - request.canonicalGameInstanceId()) - : launchRepository.lockForInitialAdmission( - request.targetNamespace(), - request.canonicalTenantId(), - request.realmId(), - request.canonicalGameInstanceId()); + switch (mode) { + case HUMAN_STARTING -> + launchRepository.lockStartingForHumanRuntimeCompletion( + request.targetNamespace(), + request.canonicalTenantId(), + request.realmId(), + request.canonicalGameInstanceId()); + case FIXTURE_STARTING -> + launchRepository.lockStartingForFixtureRuntimeCompletion( + request.targetNamespace(), + request.canonicalTenantId(), + request.realmId(), + request.canonicalGameInstanceId()); + case RUNNING -> + launchRepository.lockForInitialAdmission( + request.targetNamespace(), + request.canonicalTenantId(), + request.realmId(), + request.canonicalGameInstanceId()); + }; + boolean fixture = mode == LaunchMode.FIXTURE_STARTING; + if (launch.association().isRunOwnedFixture() != fixture) { + throw conflict( + fixture + ? "Run-owned fixture intent requires the exact fixture launch" + : "Human initial-admission intent cannot use a run-owned fixture launch"); + } SourceBinding source = sourceBinding(catalog, launch); Record retainedLaunch = dsl.fetchOne( - "SELECT original_start_session_tuple, catalog_source_intake_operation_id, " + "SELECT original_start_session_tuple, fixture_policy_request_bytes, " + + "fixture_policy_seal_evidence_digest, catalog_source_intake_operation_id, " + "catalog_source_intake_request_id FROM game_session_canonical_instance_launch " + "WHERE target_namespace = ? AND control_plane_request_id = ? " + "AND canonical_tenant_id = ? AND canonical_realm_id = ? " @@ -234,9 +267,25 @@ private LockedSources lockSources(Request request, boolean requireStarting) { if (retainedLaunch == null) { throw conflict("Exact captured original launch evidence is unavailable for intent storage"); } - byte[] originalTuple = required(retainedLaunch, "original_start_session_tuple", byte[].class); UUID intakeOperation = catalog.sourceIntakeReceipt().operationId(); UUID intakeRequest = catalog.sourceIntakeReceipt().intakeRequestId(); + if (fixture) { + // The fixture retains no original StartSession tuple; its exact policy seal is the source. + if (retainedLaunch.get("original_start_session_tuple", byte[].class) != null + || retainedLaunch.get("fixture_policy_request_bytes", byte[].class) == null + || !launch + .association() + .attestationDigest() + .equals(retainedLaunch.get("fixture_policy_seal_evidence_digest", String.class)) + || !intakeOperation.equals( + required(retainedLaunch, "catalog_source_intake_operation_id", UUID.class)) + || !intakeRequest.equals( + required(retainedLaunch, "catalog_source_intake_request_id", UUID.class))) { + throw conflict("Captured fixture launch differs from the locked catalog source identity"); + } + return new LockedSources(source, null, intakeOperation, intakeRequest); + } + byte[] originalTuple = required(retainedLaunch, "original_start_session_tuple", byte[].class); if (originalTuple.length == 0 || originalTuple.length > 262_144 || !intakeOperation.equals( @@ -245,7 +294,7 @@ private LockedSources lockSources(Request request, boolean requireStarting) { required(retainedLaunch, "catalog_source_intake_request_id", UUID.class))) { throw conflict("Captured original launch differs from the locked catalog source identity"); } - if (requireStarting) { + if (mode == LaunchMode.HUMAN_STARTING) { final StartSessionPostAuthorizationExecutionTuple decodedOriginal; try { decodedOriginal = StartSessionPostAuthorizationExecutionTuple.decode(originalTuple); @@ -261,8 +310,7 @@ private LockedSources lockSources(Request request, boolean requireStarting) { private static SourceBinding sourceBinding( CanonicalRealmCatalogSnapshot catalog, CanonicalInitialAdmissionLaunchTarget launch) { CanonicalGameInstanceLaunchAssociation association = launch.association(); - var descriptor = association.launchBindingEvidence().descriptor(); - var release = association.launchBindingEvidence().releaseAttestation(); + var descriptor = association.descriptor(); return new SourceBinding( catalog.targetNamespace(), catalog.tenantId(), @@ -288,7 +336,7 @@ private static SourceBinding sourceBinding( association.currentRowVersion(), descriptor.requestDigest(), descriptor.resultDigest(), - release.evidenceDigest()); + association.attestationDigest()); } private void insertIntent( @@ -339,7 +387,7 @@ private void insertIntent( source.releaseAttestationDigest(), sources.catalogSourceIntakeOperationId(), sources.catalogSourceIntakeRequestId(), - sources.originalStartSessionTuple(), + org.jooq.impl.DSL.val(sources.originalStartSessionTuple(), org.jooq.impl.SQLDataType.BLOB), holdBytes, lifecycleBytes, IntentState.PENDING_HOLD.name()); @@ -571,18 +619,26 @@ private static T required(Record row, String column, Class type) { message); } + private enum LaunchMode { + RUNNING, + HUMAN_STARTING, + FIXTURE_STARTING + } + + /** Human launches retain their original tuple; the run-owned fixture retains none (null). */ private record LockedSources( SourceBinding binding, byte[] originalStartSessionTuple, UUID catalogSourceIntakeOperationId, UUID catalogSourceIntakeRequestId) { private LockedSources { - originalStartSessionTuple = originalStartSessionTuple.clone(); + originalStartSessionTuple = + originalStartSessionTuple == null ? null : originalStartSessionTuple.clone(); } @Override public byte[] originalStartSessionTuple() { - return originalStartSessionTuple.clone(); + return originalStartSessionTuple == null ? null : originalStartSessionTuple.clone(); } } } diff --git a/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/repository/CanonicalInitialAdmissionRepository.java b/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/repository/CanonicalInitialAdmissionRepository.java index c3d77d9443..05378ced63 100644 --- a/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/repository/CanonicalInitialAdmissionRepository.java +++ b/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/repository/CanonicalInitialAdmissionRepository.java @@ -155,6 +155,9 @@ private void reserveProtected( lockTarget(request); Attempt existing = findAttempt(request.targetNamespace(), request.initialAdmissionRequestId(), true); + if (existing != null) { + requireHumanAttempt(existing); + } if (existing != null && !PENDING.equals(existing.status())) { requireSameRequestIdentity(existing, request); requireTerminalProtectionReplay(existing, accountProtection); @@ -262,6 +265,7 @@ public void commitProtected( requireWritableReadCommittedOwnerTransaction(); lockTarget(request); Attempt attempt = requireAttemptForUpdate(request); + requireHumanAttempt(attempt); if (!PENDING.equals(attempt.status())) { if (!COMMITTED.equals(attempt.status())) { throw new CanonicalInitialAdmissionConflictException( @@ -281,7 +285,15 @@ public void commitProtected( protectionRepository() .requireExactPendingReservation( request.targetNamespace(), request.initialAdmissionRequestId(), accountProtection); + writeCommit(request, attempt, catalog, launchTarget); + } + /** Writes the pointer, audit, attempt terminal and intent terminal for one locked attempt. */ + private void writeCommit( + CanonicalInitialAdmissionRequest request, + Attempt attempt, + CanonicalRealmCatalogSnapshot catalog, + CanonicalInitialAdmissionLaunchTarget launchTarget) { ExpectedClosedEvidence closedOrigin = lockExpectedClosedOrigin(request); if (closedOrigin == null) { requireNoPriorPointer(request, catalog, launchTarget); @@ -323,11 +335,147 @@ public void commitProtected( request.initialAdmissionRequestId()); if (updated != 1) { throw new CanonicalInitialAdmissionConflictException( - "Protected initial-admission attempt changed before pointer commit"); + "Initial-admission attempt changed before pointer commit"); } terminalizeIntent(request, terminalAt); } + /** + * Reserves the run-owned fixture attempt before its STARTING runtime completes. The fixture has + * no Account protection; the attempt retains the launch's fixture provenance digest instead. + * Returns true when this call inserted the reservation and false for an exact replay. + */ + @Transactional(isolation = Isolation.READ_COMMITTED) + public boolean reserveFixtureStarting(CanonicalInitialAdmissionRequest request) { + Objects.requireNonNull(request, "request"); + requireWritableReadCommittedOwnerTransaction(); + lockTarget(request); + Attempt existing = + findAttempt(request.targetNamespace(), request.initialAdmissionRequestId(), true); + if (existing != null) { + requireFixtureAttempt(existing); + requireSameRequestIdentity(existing, request); + if (!PENDING.equals(existing.status())) { + return false; + } + } + CanonicalRealmCatalogSnapshot catalog = lockCatalog(request); + if (request.originKind() == CanonicalInitialAdmissionRequest.OriginKind.NO_PRIOR_POINTER) { + lockAllAdmissionRepresentationsForNoPrior(); + } + // A pending replay may follow fixture runtime completion; a fresh reservation needs STARTING. + CanonicalInitialAdmissionLaunchTarget launchTarget = + existing != null ? lockLaunchTarget(request, false) : lockFixtureStartingLaunch(request); + requireRequestMatchesCatalogAndLaunch(request, catalog, launchTarget); + String provenance = requireFixtureLaunch(launchTarget); + if (existing != null) { + requireSameRequest(existing, request, launchTarget); + if (!provenance.equals(existing.fixtureProvenanceDigest())) { + throw new CanonicalInitialAdmissionConflictException( + "Fixture initial-admission replay changed its fixture provenance"); + } + return false; + } + requireAttachedFixtureIntent(request, provenance); + if (findPendingForRealm(request, true) != null) { + throw new CanonicalInitialAdmissionConflictException( + "Another initial-admission request already owns the pending realm attempt"); + } + requireOriginStillCurrent(request, catalog, launchTarget); + + Instant now = databaseTimestamp(); + int inserted = + dsl.execute( + "INSERT INTO " + + OPERATION_TABLE + + " (target_namespace, initial_admission_request_id, request_digest, " + + "canonical_tenant_id, world_slug, realm_id, playable_state_namespace_id, " + + "playable_state_scope, canonical_game_instance_id, game_session_tenant_id, " + + "game_instance_id, canonical_version_id, runtime_version_id, " + + "expected_catalog_revision, origin_kind, expected_prior_pointer_version, " + + "active_lifecycle_epoch, hold_id, hold_fence, hold_binding_digest, status, " + + "fixture_provenance_digest, created_at, updated_at) VALUES (?, ?, ?, ?, " + + "?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, 'PENDING', ?, " + + "CAST(? AS TIMESTAMPTZ), CAST(? AS TIMESTAMPTZ)) ON CONFLICT DO NOTHING", + request.targetNamespace(), + request.initialAdmissionRequestId(), + request.requestDigest(), + request.canonicalTenantId(), + request.worldSlug(), + request.realmId(), + request.playableStateNamespaceId(), + request.playableStateScope(), + request.canonicalGameInstanceId(), + launchTarget.association().gameSessionTenantId(), + launchTarget.gameInstanceId(), + request.canonicalVersionId(), + launchTarget.runtimeVersionId(), + request.expectedCatalogRevision(), + request.originKind().name(), + request.expectedPriorPointerVersion(), + request.activeLifecycleEpoch(), + request.holdId(), + request.holdFence(), + request.holdBindingDigest(), + provenance, + utc(now), + utc(now)); + Attempt reserved = + findAttempt(request.targetNamespace(), request.initialAdmissionRequestId(), true); + if (inserted != 1 || reserved == null) { + throw new CanonicalInitialAdmissionConflictException( + "Fixture initial-admission reservation conflicted with durable owner state"); + } + requireFixtureAttempt(reserved); + requireSameRequest(reserved, request, launchTarget); + if (!PENDING.equals(reserved.status()) + || !provenance.equals(reserved.fixtureProvenanceDigest())) { + throw new CanonicalInitialAdmissionReconciliationRequiredException( + "Fixture initial-admission reservation readback differs from its insert"); + } + return true; + } + + /** + * Atomically writes the fixture pointer, append-only audit, fixture-provenance terminal and + * intent terminal after the exact World ACTIVE/hold proof and the retained fixture RUNNING + * completion. Returns true when this call committed and false for an exact COMMITTED replay. + */ + @Transactional(isolation = Isolation.READ_COMMITTED) + public boolean commitFixture( + CanonicalInitialAdmissionRequest request, CanonicalInitialAdmissionWorldProof worldProof) { + Objects.requireNonNull(request, "request"); + Objects.requireNonNull(worldProof, "worldProof"); + worldProof.requireMatches(request); + requireWritableReadCommittedOwnerTransaction(); + lockTarget(request); + Attempt attempt = requireAttemptForUpdate(request); + requireFixtureAttempt(attempt); + if (!PENDING.equals(attempt.status())) { + if (!COMMITTED.equals(attempt.status())) { + throw new CanonicalInitialAdmissionConflictException( + "A definitively ABORTED initial admission cannot later commit"); + } + return false; + } + CanonicalRealmCatalogSnapshot catalog = lockCatalog(request); + if (request.originKind() == CanonicalInitialAdmissionRequest.OriginKind.NO_PRIOR_POINTER) { + lockAllAdmissionRepresentationsForNoPrior(); + } + CanonicalInitialAdmissionLaunchTarget launchTarget = lockLaunchTarget(request, true); + requireRequestMatchesCatalogAndLaunch(request, catalog, launchTarget); + requireSameRequest(attempt, request, launchTarget); + String provenance = requireFixtureLaunch(launchTarget); + if (!provenance.equals(attempt.fixtureProvenanceDigest())) { + throw new CanonicalInitialAdmissionConflictException( + "Fixture initial-admission commit changed its fixture provenance"); + } + requireAttachedFixtureIntent(request, provenance); + requireFixtureRuntimeCompletion(request, provenance, launchTarget); + writeCommit(request, attempt, catalog, launchTarget); + return true; + } + /** Records one immutable protection-bound abort without creating pointer or audit evidence. */ @Transactional(isolation = Isolation.READ_COMMITTED) public void abortProtected( @@ -340,6 +488,7 @@ public void abortProtected( requireWritableReadCommittedOwnerTransaction(); lockTarget(request); Attempt attempt = requireAttemptForUpdate(request); + requireHumanAttempt(attempt); if (!PENDING.equals(attempt.status())) { if (!ABORTED.equals(attempt.status()) || !reason.equals(attempt.abortReason())) { throw new CanonicalInitialAdmissionConflictException( @@ -697,6 +846,123 @@ private CanonicalInitialAdmissionLaunchTarget lockStartingLaunchTarget( return launch; } + private CanonicalInitialAdmissionLaunchTarget lockFixtureStartingLaunch( + CanonicalInitialAdmissionRequest request) { + CanonicalInitialAdmissionLaunchTarget launch = + new CanonicalGameInstanceLaunchAssociationRepository(dsl, request.targetNamespace()) + .lockStartingForFixtureRuntimeCompletion( + request.targetNamespace(), + request.canonicalTenantId(), + request.realmId(), + request.canonicalGameInstanceId()); + requireLaunchMatchesRequest( + request, + launch, + "Canonical fixture STARTING launch does not match the exact initial-admission request"); + return launch; + } + + private static String requireFixtureLaunch(CanonicalInitialAdmissionLaunchTarget launch) { + if (!launch.association().isRunOwnedFixture()) { + throw new CanonicalInitialAdmissionConflictException( + "Run-owned fixture admission cannot use a Human launch"); + } + return launch.association().attestationDigest(); + } + + private static void requireFixtureAttempt(Attempt attempt) { + if (!attempt.isRunOwnedFixture()) { + throw new CanonicalInitialAdmissionConflictException( + "Run-owned fixture admission cannot settle a Human attempt"); + } + } + + private static void requireHumanAttempt(Attempt attempt) { + if (attempt.isRunOwnedFixture()) { + throw new CanonicalInitialAdmissionConflictException( + "Protected Human admission cannot settle a run-owned fixture attempt"); + } + } + + /** The exact attached intent whose attestation slot holds this fixture's provenance digest. */ + private void requireAttachedFixtureIntent( + CanonicalInitialAdmissionRequest request, String provenance) { + Record intent = + dsl.fetchOne( + "SELECT state, hold_identity_bytes, release_attestation_digest, " + + "original_start_session_tuple FROM game_session_canonical_initial_admission_intent " + + "WHERE target_namespace = ? AND initial_admission_request_id = ? " + + "AND request_digest = ? FOR UPDATE", + request.targetNamespace(), + request.initialAdmissionRequestId(), + request.requestDigest()); + if (intent == null + || !"HOLD_ATTACHED".equals(intent.get("state", String.class)) + || intent.get("original_start_session_tuple", byte[].class) != null + || !provenance.equals(intent.get("release_attestation_digest", String.class))) { + throw new CanonicalInitialAdmissionConflictException( + "Fixture initial admission requires its exact attached fixture intent"); + } + final net.firedevops.firemud.common.world.WorldCanonicalInitialAdmissionHold.HoldIdentity + identity; + try { + identity = + net.firedevops.firemud.common.world.WorldCanonicalInitialAdmissionHold.HoldIdentity + .fromStored(intent.get("hold_identity_bytes", byte[].class)); + } catch (RuntimeException malformed) { + throw new CanonicalInitialAdmissionReconciliationRequiredException( + "Fixture intent retains a malformed World hold identity", malformed); + } + if (!identity.holdId().equals(request.holdId()) + || !identity.holdFence().equals(request.holdFence()) + || !identity.holdBindingDigest().equals(request.holdBindingDigest())) { + throw new CanonicalInitialAdmissionConflictException( + "Fixture initial admission differs from its attached World hold identity"); + } + } + + private void requireFixtureRuntimeCompletion( + CanonicalInitialAdmissionRequest request, + String provenance, + CanonicalInitialAdmissionLaunchTarget launch) { + Record completion = + dsl.fetchOne( + "SELECT 1 FROM game_session_run_owned_fixture_runtime_completion " + + "WHERE target_namespace = ? AND initial_admission_request_id = ? " + + "AND request_digest = ? AND hold_id = ? AND hold_fence = ? " + + "AND canonical_game_instance_id = ? AND canonical_version_id = ? " + + "AND game_session_tenant_id = ? AND game_instance_id = ? " + + "AND completed_running_row_version <= ? AND fixture_provenance_digest = ?", + request.targetNamespace(), + request.initialAdmissionRequestId(), + request.requestDigest(), + request.holdId(), + request.holdFence(), + request.canonicalGameInstanceId(), + request.canonicalVersionId(), + launch.association().gameSessionTenantId(), + launch.gameInstanceId(), + launch.association().currentRowVersion(), + provenance); + if (completion == null) { + throw new CanonicalInitialAdmissionConflictException( + "Fixture first OPEN requires its retained exact RUNNING completion"); + } + } + + /** V1006 terminal framing with the fixture provenance digest in the protection slot. */ + private static String fixtureTerminalProofDigest(Attempt attempt) { + return AccountInitialAdmissionProtectionBindingRepository.terminalDigest( + attempt.fixtureProvenanceDigest().getBytes(StandardCharsets.UTF_8), + attempt.requestDigest(), + attempt.status(), + attempt.pointerId(), + attempt.pointerVersion(), + attempt.auditEventId(), + attempt.terminalAt(), + attempt.abortReason()); + } + private CanonicalRealmCatalogSnapshot lockCatalog(CanonicalInitialAdmissionRequest request) { CanonicalRealmCatalogSnapshot catalog = catalogRepository.lockInitialAdmissionTarget( @@ -1297,6 +1563,9 @@ private void verifyAbortReadback(Attempt attempt) { } private Optional protectedTerminalProofDigest(Attempt attempt) { + if (attempt.isRunOwnedFixture()) { + return Optional.of(fixtureTerminalProofDigest(attempt)); + } try { return new AccountInitialAdmissionProtectionBindingRepository(dsl) .read(attempt.targetNamespace(), attempt.initialAdmissionRequestId()) @@ -1439,7 +1708,10 @@ private static Attempt toAttempt(Record row) { row.get("updated_at", OffsetDateTime.class).toInstant(), row.get("terminal_at", OffsetDateTime.class) == null ? null - : row.get("terminal_at", OffsetDateTime.class).toInstant()); + : row.get("terminal_at", OffsetDateTime.class).toInstant(), + row.field("fixture_provenance_digest") == null + ? null + : row.get("fixture_provenance_digest", String.class)); } private static CanonicalInitialAdmissionOwnerProof toProof( @@ -1781,7 +2053,12 @@ private record Attempt( String abortReason, Instant createdAt, Instant updatedAt, - Instant terminalAt) { + Instant terminalAt, + String fixtureProvenanceDigest) { + private boolean isRunOwnedFixture() { + return fixtureProvenanceDigest != null; + } + private CanonicalInitialAdmissionRequest asRequest() { return new CanonicalInitialAdmissionRequest( targetNamespace, diff --git a/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/repository/RunOwnedFixtureRuntimeCompletionRepository.java b/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/repository/RunOwnedFixtureRuntimeCompletionRepository.java new file mode 100644 index 0000000000..7c76f8a521 --- /dev/null +++ b/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/repository/RunOwnedFixtureRuntimeCompletionRepository.java @@ -0,0 +1,271 @@ +package net.firedevops.firemud.gamesession.repository; + +import java.sql.Connection; +import java.time.Instant; +import java.time.OffsetDateTime; +import java.util.Objects; +import java.util.Optional; +import java.util.UUID; +import net.firedevops.firemud.common.grpc.GrpcPeerIdentity; +import net.firedevops.firemud.gamesession.dto.CanonicalGameInstanceLaunchAssociation; +import net.firedevops.firemud.gamesession.dto.CanonicalInitialAdmissionLaunchTarget; +import net.firedevops.firemud.gamesession.dto.CanonicalInitialAdmissionRequest; +import net.firedevops.firemud.gamesession.dto.CanonicalInitialAdmissionWorldProof; +import org.jooq.DSLContext; +import org.jooq.Record; +import org.springframework.transaction.support.TransactionSynchronizationManager; + +/** + * Owner-local STARTING to RUNNING completion of the run-owned fixture launch. The fixture has no + * Account protection; the retained row binds the exact pending fixture attempt, attached World hold + * and fixture provenance digest, and the storage guard requires it for the RUNNING update. + */ +public final class RunOwnedFixtureRuntimeCompletionRepository { + private static final String TABLE = "game_session_run_owned_fixture_runtime_completion"; + private final DSLContext dsl; + private final CanonicalGameInstanceLaunchAssociationRepository launchRepository; + + /** The launch repository is the workload-namespace owner; its locks refuse other namespaces. */ + public RunOwnedFixtureRuntimeCompletionRepository( + DSLContext dsl, CanonicalGameInstanceLaunchAssociationRepository launchRepository) { + this.dsl = Objects.requireNonNull(dsl, "dsl"); + this.launchRepository = Objects.requireNonNull(launchRepository, "launchRepository"); + } + + /** + * Completes only the exact fixture STARTING row while its fixture attempt is PENDING. An exact + * replay returns the retained completion. It creates no pointer, terminal or hold release. + */ + public Completion complete( + CanonicalInitialAdmissionRequest request, CanonicalInitialAdmissionWorldProof worldProof) { + Objects.requireNonNull(request, "request"); + Objects.requireNonNull(worldProof, "worldProof"); + worldProof.requireMatches(request); + requireWritableReadCommittedTransaction(); + lockTarget(request); + + Record retained = find(request.targetNamespace(), request.initialAdmissionRequestId(), true); + if (retained != null) { + return requireExactReplay(retained, request); + } + + Record attempt = + dsl.fetchOne( + "SELECT status, fixture_provenance_digest " + + "FROM game_session_canonical_initial_admission_attempt " + + "WHERE target_namespace=? AND initial_admission_request_id=? " + + "AND request_digest=? AND hold_id=? AND hold_fence=? FOR UPDATE", + request.targetNamespace(), + request.initialAdmissionRequestId(), + request.requestDigest(), + request.holdId(), + request.holdFence()); + if (attempt == null + || !"PENDING".equals(attempt.get("status", String.class)) + || attempt.get("fixture_provenance_digest", String.class) == null) { + throw conflict("Fixture runtime completion requires the exact pending fixture reservation"); + } + + CanonicalInitialAdmissionLaunchTarget launch = + launchRepository.lockStartingForFixtureRuntimeCompletion( + request.targetNamespace(), + request.canonicalTenantId(), + request.realmId(), + request.canonicalGameInstanceId()); + requireExactLaunch(request, launch); + CanonicalGameInstanceLaunchAssociation association = launch.association(); + String provenance = association.attestationDigest(); + if (!provenance.equals(attempt.get("fixture_provenance_digest", String.class))) { + throw conflict("Fixture reservation provenance differs from its launch"); + } + + long startingVersion = association.currentRowVersion(); + long runningVersion = Math.addExact(startingVersion, 1L); + int updated = + dsl.execute( + "UPDATE game_instances SET status='RUNNING', row_version=? " + + "WHERE tenant_id=? AND id=? AND game_instance_uuid=? " + + "AND status='STARTING' AND row_version=?", + runningVersion, + association.gameSessionTenantId(), + launch.gameInstanceId(), + request.canonicalGameInstanceId(), + startingVersion); + if (updated != 1) { + throw conflict("Fixture runtime STARTING owner changed before completion"); + } + + Record inserted = + dsl.fetchOne( + "INSERT INTO " + + TABLE + + " (target_namespace, initial_admission_request_id, request_digest, " + + "canonical_tenant_id, world_slug, realm_id, playable_state_namespace_id, " + + "playable_state_scope, canonical_game_instance_id, canonical_version_id, " + + "active_lifecycle_epoch, expected_catalog_revision, origin_kind, " + + "expected_prior_pointer_version, hold_id, hold_fence, hold_binding_digest, " + + "game_session_tenant_id, game_instance_id, control_plane_request_id, " + + "captured_starting_row_version, completed_running_row_version, " + + "fixture_provenance_digest, completed_at) " + + "VALUES (?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?, clock_timestamp()) " + + "RETURNING *", + request.targetNamespace(), + request.initialAdmissionRequestId(), + request.requestDigest(), + request.canonicalTenantId(), + request.worldSlug(), + request.realmId(), + request.playableStateNamespaceId(), + request.playableStateScope(), + request.canonicalGameInstanceId(), + request.canonicalVersionId(), + request.activeLifecycleEpoch(), + request.expectedCatalogRevision(), + request.originKind().name(), + request.expectedPriorPointerVersion(), + request.holdId(), + request.holdFence(), + request.holdBindingDigest(), + association.gameSessionTenantId(), + launch.gameInstanceId(), + association.controlPlaneRequestId(), + association.capturedStartingRowVersion(), + runningVersion, + provenance); + if (inserted == null) { + throw conflict("Fixture runtime completion evidence was not retained"); + } + return requireExactReplay(inserted, request); + } + + /** Historical readback only; this value grants no current runtime or admission authority. */ + public Optional read(String namespace, String initialAdmissionRequestId) { + if (!GrpcPeerIdentity.isValidNamespace(namespace)) { + throw new IllegalArgumentException("Fixture completion namespace is invalid"); + } + Record row = find(namespace, initialAdmissionRequestId, false); + return row == null ? Optional.empty() : Optional.of(decode(row)); + } + + private Record find(String namespace, String requestId, boolean forUpdate) { + return dsl.fetchOne( + "SELECT * FROM " + + TABLE + + " WHERE target_namespace=? AND initial_admission_request_id=?" + + (forUpdate ? " FOR UPDATE" : ""), + namespace, + requestId); + } + + private static Completion requireExactReplay( + Record row, CanonicalInitialAdmissionRequest request) { + Completion completion = decode(row); + if (!completion.request().equals(request)) { + throw conflict("Fixture runtime completion retry changed its exact request"); + } + return completion; + } + + private static Completion decode(Record row) { + CanonicalInitialAdmissionRequest request = + new CanonicalInitialAdmissionRequest( + required(row, "target_namespace", String.class), + required(row, "canonical_tenant_id", UUID.class), + required(row, "world_slug", String.class), + required(row, "realm_id", UUID.class), + required(row, "playable_state_namespace_id", UUID.class), + required(row, "playable_state_scope", String.class), + required(row, "canonical_game_instance_id", UUID.class), + required(row, "canonical_version_id", UUID.class), + required(row, "active_lifecycle_epoch", Long.class), + required(row, "expected_catalog_revision", Long.class), + CanonicalInitialAdmissionRequest.OriginKind.valueOf( + required(row, "origin_kind", String.class)), + row.get("expected_prior_pointer_version", Long.class), + required(row, "initial_admission_request_id", String.class), + required(row, "request_digest", String.class), + required(row, "hold_id", UUID.class), + required(row, "hold_fence", UUID.class), + required(row, "hold_binding_digest", String.class)); + return new Completion( + request, + required(row, "game_session_tenant_id", Long.class), + required(row, "game_instance_id", Long.class), + required(row, "captured_starting_row_version", Long.class), + required(row, "completed_running_row_version", Long.class), + required(row, "fixture_provenance_digest", String.class), + required(row, "completed_at", OffsetDateTime.class).toInstant()); + } + + private static void requireExactLaunch( + CanonicalInitialAdmissionRequest request, CanonicalInitialAdmissionLaunchTarget launch) { + CanonicalGameInstanceLaunchAssociation association = launch.association(); + if (!association.isRunOwnedFixture() + || !request.targetNamespace().equals(association.targetNamespace()) + || !request.canonicalTenantId().equals(association.canonicalTenantId()) + || !request.worldSlug().equals(association.worldSlug()) + || !request.realmId().equals(launch.realmId()) + || !request.playableStateNamespaceId().equals(association.playableStateNamespaceId()) + || !request.playableStateScope().equals(association.playableStateScope().name()) + || !request.canonicalGameInstanceId().equals(association.gameInstanceUuid()) + || !request.canonicalVersionId().equals(launch.canonicalVersionId())) { + throw conflict("Fixture runtime completion launch differs from the exact request"); + } + } + + private void lockTarget(CanonicalInitialAdmissionRequest request) { + dsl.fetchOne( + "SELECT pg_advisory_xact_lock(hashtextextended(? || ':' || ? || ':' || ?, 0))", + request.targetNamespace(), + request.canonicalTenantId().toString(), + request.realmId().toString()); + } + + private void requireWritableReadCommittedTransaction() { + if (!TransactionSynchronizationManager.isActualTransactionActive() + || TransactionSynchronizationManager.isCurrentTransactionReadOnly() + || dsl.connectionResult( + connection -> { + try { + return connection.getAutoCommit() + || connection.isReadOnly() + || connection.getTransactionIsolation() + != Connection.TRANSACTION_READ_COMMITTED; + } catch (java.sql.SQLException exception) { + throw new IllegalStateException( + "Unable to inspect completion transaction", exception); + } + })) { + throw new IllegalStateException( + "Fixture runtime completion requires a writable READ COMMITTED transaction"); + } + } + + private static T required(Record row, String field, Class type) { + T value = row.get(field, type); + if (value == null) { + throw new IllegalStateException("Fixture runtime completion is missing " + field); + } + return value; + } + + private static IllegalStateException conflict(String message) { + return new IllegalStateException(message); + } + + /** Immutable historical fixture completion receipt; it never authorizes another write. */ + public record Completion( + CanonicalInitialAdmissionRequest request, + long gameSessionTenantId, + long gameInstanceId, + long capturedStartingRowVersion, + long completedRunningRowVersion, + String fixtureProvenanceDigest, + Instant completedAt) { + public Completion { + Objects.requireNonNull(request, "request"); + Objects.requireNonNull(fixtureProvenanceDigest, "fixtureProvenanceDigest"); + Objects.requireNonNull(completedAt, "completedAt"); + } + } +} diff --git a/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/service/impl/AuthenticatedCanonicalInitialAdmissionWorldVerifier.java b/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/service/impl/AuthenticatedCanonicalInitialAdmissionWorldVerifier.java index cf3c95e5b3..7f268e56b5 100644 --- a/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/service/impl/AuthenticatedCanonicalInitialAdmissionWorldVerifier.java +++ b/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/service/impl/AuthenticatedCanonicalInitialAdmissionWorldVerifier.java @@ -178,14 +178,13 @@ private static void requireCurrentPendingActiveState( throw new IllegalStateException( "Authenticated World hold-state response changed the exact immutable identity"); } - if (!requestedLifecycle.equals(observed.lifecycleEvidence().request())) { + if (!requestedLifecycle.equals(observed.lifecycleRequest())) { throw new IllegalStateException( "Authenticated World hold-state response changed the fresh lifecycle read request"); } if (observed.holdStatus() != HoldStatus.PENDING - || !"ACTIVE".equals(observed.lifecycleEvidence().lifecycleStatus()) - || observed.lifecycleEvidence().lifecycleEpoch() - != requestedIdentity.request().activeLifecycleEpoch()) { + || !"ACTIVE".equals(observed.lifecycleStatus()) + || observed.lifecycleEpoch() != requestedIdentity.request().activeLifecycleEpoch()) { throw new IllegalStateException( "Authenticated World hold is not pending at its exact ACTIVE lifecycle epoch"); } @@ -205,8 +204,8 @@ private static CanonicalInitialAdmissionWorldProof proofFromWorldState( worldRequest.playableStateScope(), worldRequest.canonicalGameInstanceId(), worldRequest.canonicalVersionId(), - worldState.lifecycleEvidence().lifecycleStatus(), - worldState.lifecycleEvidence().lifecycleEpoch(), + worldState.lifecycleStatus(), + worldState.lifecycleEpoch(), CanonicalInitialAdmissionRequest.OriginKind.valueOf( worldRequest.initialAdmissionOrigin().name()), worldRequest.expectedCatalogRevision(), diff --git a/services/game-session-service/src/main/resources/application.yml b/services/game-session-service/src/main/resources/application.yml index bd9cd448c0..6ff7363775 100644 --- a/services/game-session-service/src/main/resources/application.yml +++ b/services/game-session-service/src/main/resources/application.yml @@ -140,6 +140,11 @@ firemud: - game_session.v1.CanonicalGameplayRosterOwnerReadService/GetCanonicalGameplayRosterOwnerRead - game_session.v1.CanonicalGameplayRosterOwnerReadService/GetPreseededActorAssignmentOwnerRead - game_session.v1.GameSessionService/AuthorizeStartSession + - game_session.v1.CanonicalGameplayAdmissionDecisionReadService/ListVisiblePublicProductionAdmissionTargets + - game_session.v1.CanonicalGameplayAdmissionDecisionReadService/ResolvePublishedRealmAdmissionTarget + - game_session.v1.CanonicalGameplayAdmissionDecisionReadService/GetOriginalNewNeverAdmittedDecision + - game_session.v1.CanonicalGameplayAdmissionDecisionReadService/GetCanonicalGameplayAdmissionDecision + - game_session.v1.CanonicalGameplayAdmissionDecisionReadService/GetPublishedRealmAdmissionOwnerRead grpc: cert-chain: ${FIREMUD_GRPC_CERT_CHAIN_PATH:certs/client.crt} private-key: ${FIREMUD_GRPC_PRIVATE_KEY_PATH:certs/client.key} diff --git a/services/game-session-service/src/main/resources/db/migration/V1070__game_session_run_owned_fixture_initial_admission.sql b/services/game-session-service/src/main/resources/db/migration/V1070__game_session_run_owned_fixture_initial_admission.sql new file mode 100644 index 0000000000..5676a89838 --- /dev/null +++ b/services/game-session-service/src/main/resources/db/migration/V1070__game_session_run_owned_fixture_initial_admission.sql @@ -0,0 +1,603 @@ +-- Admit the run-owned fixture's first OPEN through the existing intent, attempt and pointer owners. +-- The fixture has no Account protection or original StartSession tuple: its launch's policy-seal +-- evidence digest (the fixture provenance digest) takes the release-attestation and protection +-- slots. Every Human check below is retained unchanged; fixture rows are admitted only with their +-- exact fixture launch, attached hold and retained fixture runtime completion. +-- [jooq ignore start] +LOCK TABLE game_session_canonical_initial_admission_intent, + game_session_canonical_initial_admission_attempt IN ACCESS EXCLUSIVE MODE; + +ALTER TABLE game_session_canonical_initial_admission_attempt + ADD COLUMN fixture_provenance_digest VARCHAR(71), + ADD CONSTRAINT chk_gs_initial_admission_fixture_provenance CHECK ( + fixture_provenance_digest IS NULL + OR (fixture_provenance_digest ~ '^sha256:[0-9a-f]{64}$' + AND account_protection_evidence_version IS NULL + AND account_protection_id IS NULL + AND account_protection_fence IS NULL + AND original_owner_attempt_id IS NULL + AND original_owner_mutation_id IS NULL + AND original_owner_fence IS NULL + AND account_protection_evidence_bytes IS NULL)); + +-- Retained historical rows stay unvalidated exactly as V1011 left them; new terminals require +-- Account protection or, for the run-owned fixture only, its fixture provenance. +ALTER TABLE game_session_canonical_initial_admission_attempt + DROP CONSTRAINT chk_gs_initial_admission_terminal_requires_protection, + ADD CONSTRAINT chk_gs_initial_admission_terminal_requires_protection + CHECK (status = 'PENDING' + OR (account_protection_evidence_version IS NOT NULL + AND account_protection_evidence_version = 1) + OR (account_protection_evidence_version IS NULL + AND fixture_provenance_digest IS NOT NULL)) NOT VALID; + +-- A fixture intent retains the exact catalog source identity but no original StartSession tuple. +ALTER TABLE game_session_canonical_initial_admission_intent + DROP CONSTRAINT chk_gs_initial_admission_intent_v44_launch_evidence, + ADD CONSTRAINT chk_gs_initial_admission_intent_v44_launch_evidence + CHECK ((catalog_source_intake_operation_id IS NULL + AND catalog_source_intake_request_id IS NULL + AND original_start_session_tuple IS NULL) + OR (catalog_source_intake_operation_id IS NOT NULL + AND catalog_source_intake_operation_id <> '00000000-0000-0000-0000-000000000000'::UUID + AND catalog_source_intake_request_id IS NOT NULL + AND catalog_source_intake_request_id <> '00000000-0000-0000-0000-000000000000'::UUID + AND (original_start_session_tuple IS NULL + OR octet_length(original_start_session_tuple) BETWEEN 1 AND 262144))); + +CREATE TABLE game_session_run_owned_fixture_runtime_completion ( + target_namespace VARCHAR(63) NOT NULL, + initial_admission_request_id VARCHAR(128) NOT NULL, + request_digest VARCHAR(64) NOT NULL, + canonical_tenant_id UUID NOT NULL, + world_slug VARCHAR(120) NOT NULL, + realm_id UUID NOT NULL, + playable_state_namespace_id UUID NOT NULL, + playable_state_scope VARCHAR(16) NOT NULL, + canonical_game_instance_id UUID NOT NULL, + canonical_version_id UUID NOT NULL, + active_lifecycle_epoch BIGINT NOT NULL, + expected_catalog_revision BIGINT NOT NULL, + origin_kind VARCHAR(32) NOT NULL, + expected_prior_pointer_version BIGINT, + hold_id UUID NOT NULL, + hold_fence UUID NOT NULL, + hold_binding_digest VARCHAR(71) NOT NULL, + game_session_tenant_id BIGINT NOT NULL, + game_instance_id BIGINT NOT NULL, + control_plane_request_id VARCHAR(128) NOT NULL, + captured_starting_row_version BIGINT NOT NULL, + completed_running_row_version BIGINT NOT NULL, + fixture_provenance_digest VARCHAR(71) NOT NULL, + completed_at TIMESTAMPTZ NOT NULL, + CONSTRAINT pk_gs_run_owned_fixture_runtime_completion + PRIMARY KEY (target_namespace, initial_admission_request_id), + CONSTRAINT uq_gs_run_owned_fixture_runtime_completion_launch + UNIQUE (target_namespace, canonical_game_instance_id), + CONSTRAINT uq_gs_run_owned_fixture_runtime_completion_runtime + UNIQUE (game_session_tenant_id, game_instance_id), + CONSTRAINT fk_gs_run_owned_fixture_runtime_completion_intent + FOREIGN KEY (target_namespace, initial_admission_request_id) + REFERENCES game_session_canonical_initial_admission_intent + (target_namespace, initial_admission_request_id), + CONSTRAINT fk_gs_run_owned_fixture_runtime_completion_attempt + FOREIGN KEY (target_namespace, initial_admission_request_id) + REFERENCES game_session_canonical_initial_admission_attempt + (target_namespace, initial_admission_request_id), + CONSTRAINT fk_gs_run_owned_fixture_runtime_completion_launch + FOREIGN KEY (target_namespace, canonical_game_instance_id) + REFERENCES game_session_canonical_instance_launch (target_namespace, game_instance_uuid), + CONSTRAINT chk_gs_run_owned_fixture_runtime_completion_shape CHECK ( + request_digest ~ '^[0-9a-f]{64}$' + AND playable_state_scope = 'SHARED' + AND active_lifecycle_epoch > 0 + AND expected_catalog_revision > 0 + AND origin_kind IN ('NO_PRIOR_POINTER', 'EXPECT_CLOSED') + AND ((origin_kind = 'NO_PRIOR_POINTER' AND expected_prior_pointer_version IS NULL) + OR (origin_kind = 'EXPECT_CLOSED' AND expected_prior_pointer_version > 0)) + AND hold_binding_digest ~ '^sha256:[0-9a-f]{64}$' + AND fixture_provenance_digest ~ '^sha256:[0-9a-f]{64}$' + AND game_session_tenant_id > 0 + AND game_instance_id > 0 + AND captured_starting_row_version >= 0 + AND completed_running_row_version = captured_starting_row_version + 1) +); + +CREATE FUNCTION require_gs_run_owned_fixture_runtime_completion() +RETURNS trigger +LANGUAGE plpgsql +AS $$ +DECLARE + runtime game_instances%ROWTYPE; + launch game_session_canonical_instance_launch%ROWTYPE; + intent game_session_canonical_initial_admission_intent%ROWTYPE; + attempt game_session_canonical_initial_admission_attempt%ROWTYPE; +BEGIN + SELECT * INTO launch FROM game_session_canonical_instance_launch + WHERE target_namespace=NEW.target_namespace + AND game_instance_uuid=NEW.canonical_game_instance_id; + SELECT * INTO runtime FROM game_instances + WHERE tenant_id=NEW.game_session_tenant_id AND id=NEW.game_instance_id; + SELECT * INTO intent FROM game_session_canonical_initial_admission_intent + WHERE target_namespace=NEW.target_namespace + AND initial_admission_request_id=NEW.initial_admission_request_id; + SELECT * INTO attempt FROM game_session_canonical_initial_admission_attempt + WHERE target_namespace=NEW.target_namespace + AND initial_admission_request_id=NEW.initial_admission_request_id; + + IF launch.target_namespace IS NULL OR runtime.id IS NULL OR intent.target_namespace IS NULL + OR attempt.target_namespace IS NULL + OR launch.fixture_policy_request_bytes IS NULL + OR launch.original_start_session_tuple IS NOT NULL + OR launch.fixture_policy_seal_evidence_digest IS DISTINCT FROM NEW.fixture_provenance_digest + OR runtime.status IS DISTINCT FROM 'RUNNING' + OR runtime.row_version IS DISTINCT FROM NEW.completed_running_row_version + OR runtime.game_instance_uuid IS DISTINCT FROM NEW.canonical_game_instance_id + OR runtime.run_owned_start_request_id IS DISTINCT FROM launch.control_plane_request_id + OR launch.captured_starting_row_version IS DISTINCT FROM NEW.captured_starting_row_version + OR launch.game_session_tenant_id IS DISTINCT FROM NEW.game_session_tenant_id + OR launch.game_instance_id IS DISTINCT FROM NEW.game_instance_id + OR launch.control_plane_request_id IS DISTINCT FROM NEW.control_plane_request_id + OR launch.canonical_tenant_id IS DISTINCT FROM NEW.canonical_tenant_id + OR launch.canonical_realm_id IS DISTINCT FROM NEW.realm_id + OR launch.world_slug IS DISTINCT FROM NEW.world_slug + OR launch.playable_state_namespace_id IS DISTINCT FROM NEW.playable_state_namespace_id + OR launch.playable_state_scope IS DISTINCT FROM NEW.playable_state_scope + OR intent.state IS DISTINCT FROM 'HOLD_ATTACHED' + OR intent.hold_identity_bytes IS NULL + OR intent.request_digest IS DISTINCT FROM NEW.request_digest + OR intent.control_plane_request_id IS DISTINCT FROM NEW.control_plane_request_id + OR intent.canonical_version_id IS DISTINCT FROM NEW.canonical_version_id + OR intent.release_attestation_digest IS DISTINCT FROM NEW.fixture_provenance_digest + OR intent.original_start_session_tuple IS NOT NULL + OR attempt.status IS DISTINCT FROM 'PENDING' + OR attempt.fixture_provenance_digest IS DISTINCT FROM NEW.fixture_provenance_digest + OR attempt.request_digest IS DISTINCT FROM NEW.request_digest + OR attempt.canonical_tenant_id IS DISTINCT FROM NEW.canonical_tenant_id + OR attempt.world_slug IS DISTINCT FROM NEW.world_slug + OR attempt.realm_id IS DISTINCT FROM NEW.realm_id + OR attempt.playable_state_namespace_id IS DISTINCT FROM NEW.playable_state_namespace_id + OR attempt.playable_state_scope IS DISTINCT FROM NEW.playable_state_scope + OR attempt.canonical_game_instance_id IS DISTINCT FROM NEW.canonical_game_instance_id + OR attempt.canonical_version_id IS DISTINCT FROM NEW.canonical_version_id + OR attempt.game_session_tenant_id IS DISTINCT FROM NEW.game_session_tenant_id + OR attempt.game_instance_id IS DISTINCT FROM NEW.game_instance_id + OR attempt.active_lifecycle_epoch IS DISTINCT FROM NEW.active_lifecycle_epoch + OR attempt.expected_catalog_revision IS DISTINCT FROM NEW.expected_catalog_revision + OR attempt.origin_kind IS DISTINCT FROM NEW.origin_kind + OR attempt.expected_prior_pointer_version IS DISTINCT FROM NEW.expected_prior_pointer_version + OR attempt.hold_id IS DISTINCT FROM NEW.hold_id + OR attempt.hold_fence IS DISTINCT FROM NEW.hold_fence + OR attempt.hold_binding_digest IS DISTINCT FROM NEW.hold_binding_digest + OR EXISTS (SELECT 1 FROM gameplay_admission_pointer p + WHERE p.target_namespace=NEW.target_namespace + AND p.initial_admission_request_id=NEW.initial_admission_request_id) + OR EXISTS (SELECT 1 FROM gameplay_admission_pointer_event e + WHERE e.target_namespace=NEW.target_namespace + AND e.initial_admission_request_id=NEW.initial_admission_request_id) + THEN + RAISE EXCEPTION 'Fixture runtime completion requires the exact pending fixture attempt, attached hold, fixture launch and RUNNING CAS' + USING ERRCODE='23514'; + END IF; + RETURN NEW; +END; +$$; + +CREATE TRIGGER gs_run_owned_fixture_runtime_completion_guard +BEFORE INSERT ON game_session_run_owned_fixture_runtime_completion +FOR EACH ROW EXECUTE FUNCTION require_gs_run_owned_fixture_runtime_completion(); + +CREATE FUNCTION reject_gs_run_owned_fixture_runtime_completion_mutation() +RETURNS trigger LANGUAGE plpgsql AS $$ +BEGIN + RAISE EXCEPTION 'Run-owned fixture runtime completion evidence is immutable' + USING ERRCODE='23514'; +END; +$$; + +CREATE TRIGGER gs_run_owned_fixture_runtime_completion_immutable +BEFORE UPDATE OR DELETE ON game_session_run_owned_fixture_runtime_completion +FOR EACH ROW EXECUTE FUNCTION reject_gs_run_owned_fixture_runtime_completion_mutation(); +CREATE TRIGGER gs_run_owned_fixture_runtime_completion_no_truncate +BEFORE TRUNCATE ON game_session_run_owned_fixture_runtime_completion +FOR EACH STATEMENT EXECUTE FUNCTION reject_gs_run_owned_fixture_runtime_completion_mutation(); + +-- A run-owned fixture runtime reaches RUNNING only with its exact retained completion row. +CREATE FUNCTION require_gs_run_owned_fixture_running_completion() +RETURNS trigger +LANGUAGE plpgsql +AS $$ +BEGIN + IF NOT EXISTS ( + SELECT 1 FROM game_session_canonical_instance_launch launch + WHERE launch.game_session_tenant_id = NEW.tenant_id + AND launch.game_instance_id = NEW.id + AND launch.fixture_policy_request_bytes IS NOT NULL) THEN + RETURN NULL; + END IF; + IF NOT EXISTS ( + SELECT 1 + FROM game_session_run_owned_fixture_runtime_completion completion + JOIN game_session_canonical_instance_launch launch + ON launch.target_namespace = completion.target_namespace + AND launch.game_instance_uuid = completion.canonical_game_instance_id + AND launch.game_session_tenant_id = completion.game_session_tenant_id + AND launch.game_instance_id = completion.game_instance_id + AND launch.fixture_policy_seal_evidence_digest = completion.fixture_provenance_digest + WHERE completion.game_session_tenant_id = NEW.tenant_id + AND completion.game_instance_id = NEW.id + AND completion.canonical_game_instance_id = NEW.game_instance_uuid + AND completion.captured_starting_row_version = OLD.row_version + AND completion.completed_running_row_version = NEW.row_version) THEN + RAISE EXCEPTION 'Run-owned fixture STARTING to RUNNING requires its exact retained runtime completion' + USING ERRCODE = '23514', + CONSTRAINT = 'chk_gs_run_owned_fixture_running_completion_required'; + END IF; + RETURN NULL; +END; +$$; + +CREATE CONSTRAINT TRIGGER game_instances_run_owned_fixture_running_completion + AFTER UPDATE ON game_instances + DEFERRABLE INITIALLY DEFERRED + FOR EACH ROW + WHEN (OLD.status = 'STARTING' AND NEW.status = 'RUNNING') + EXECUTE FUNCTION require_gs_run_owned_fixture_running_completion(); + +-- The fixture attempt guard mirrors the protected terminal guard with no Account protection; the +-- fixture provenance digest's UTF-8 bytes take the V1006 terminal preimage's protection slot. +CREATE FUNCTION require_gs_run_owned_fixture_initial_admission_attempt( + p_op TEXT, + p_old game_session_canonical_initial_admission_attempt, + p_new game_session_canonical_initial_admission_attempt) +RETURNS game_session_canonical_initial_admission_attempt +LANGUAGE plpgsql +AS $$ +DECLARE + selected_intent game_session_canonical_initial_admission_intent%ROWTYPE; + selected_launch game_session_canonical_instance_launch%ROWTYPE; + selected_catalog game_session_canonical_realm_catalog%ROWTYPE; + hold_json JSONB; + expected_request_digest TEXT; + digest_bytes BYTEA; + field_bytes BYTEA; +BEGIN + IF p_new.status NOT IN ('PENDING', 'COMMITTED') + OR p_new.fixture_provenance_digest IS NULL + OR p_new.fixture_provenance_digest !~ '^sha256:[0-9a-f]{64}$' + OR p_new.account_protection_evidence_version IS NOT NULL + OR p_new.account_protection_id IS NOT NULL + OR p_new.account_protection_fence IS NOT NULL + OR p_new.original_owner_attempt_id IS NOT NULL + OR p_new.original_owner_mutation_id IS NOT NULL + OR p_new.original_owner_fence IS NOT NULL + OR p_new.account_protection_evidence_bytes IS NOT NULL + OR (p_op = 'INSERT' AND p_new.status <> 'PENDING') + OR (p_op = 'UPDATE' + AND (p_old.status <> 'PENDING' + OR p_old.fixture_provenance_digest IS DISTINCT FROM p_new.fixture_provenance_digest)) + THEN + RAISE EXCEPTION 'Run-owned fixture initial admission requires one immutable fixture provenance and no Account protection' + USING ERRCODE = '23514', + CONSTRAINT = 'chk_gs_initial_admission_fixture_provenance'; + END IF; + + SELECT * INTO selected_intent + FROM game_session_canonical_initial_admission_intent + WHERE target_namespace = p_new.target_namespace + AND initial_admission_request_id = p_new.initial_admission_request_id; + SELECT * INTO selected_launch + FROM game_session_canonical_instance_launch + WHERE target_namespace = p_new.target_namespace + AND control_plane_request_id = selected_intent.control_plane_request_id; + SELECT * INTO selected_catalog + FROM game_session_canonical_realm_catalog + WHERE target_namespace = p_new.target_namespace + AND canonical_tenant_id = p_new.canonical_tenant_id + AND realm_id = p_new.realm_id; + + IF selected_intent.target_namespace IS NULL + OR selected_intent.state <> 'HOLD_ATTACHED' + OR selected_intent.terminal_at IS NOT NULL + OR selected_intent.hold_identity_bytes IS NULL + OR selected_launch.target_namespace IS NULL + OR selected_catalog.target_namespace IS NULL + OR selected_launch.fixture_policy_request_bytes IS NULL + OR selected_launch.original_start_session_tuple IS NOT NULL + OR selected_intent.original_start_session_tuple IS NOT NULL + OR selected_launch.fixture_policy_seal_evidence_digest IS DISTINCT FROM p_new.fixture_provenance_digest + OR selected_intent.release_attestation_digest IS DISTINCT FROM p_new.fixture_provenance_digest + OR selected_launch.game_instance_uuid IS DISTINCT FROM p_new.canonical_game_instance_id + OR selected_launch.game_session_tenant_id IS DISTINCT FROM p_new.game_session_tenant_id + OR selected_launch.game_instance_id IS DISTINCT FROM p_new.game_instance_id + OR selected_launch.version_id IS DISTINCT FROM p_new.runtime_version_id + OR selected_intent.request_digest <> p_new.request_digest + OR selected_intent.canonical_tenant_id <> p_new.canonical_tenant_id + OR selected_intent.world_slug <> p_new.world_slug + OR selected_intent.realm_id <> p_new.realm_id + OR selected_intent.playable_state_namespace_id <> p_new.playable_state_namespace_id + OR selected_intent.playable_state_scope <> p_new.playable_state_scope + OR selected_intent.canonical_game_instance_id <> p_new.canonical_game_instance_id + OR selected_intent.canonical_version_id <> p_new.canonical_version_id + OR selected_intent.game_session_tenant_id <> p_new.game_session_tenant_id + OR selected_intent.game_instance_id <> p_new.game_instance_id + OR selected_intent.runtime_version_id <> p_new.runtime_version_id + OR selected_intent.catalog_revision <> p_new.expected_catalog_revision + OR selected_intent.launch_descriptor_id <> selected_launch.launch_descriptor_id + OR selected_intent.captured_starting_row_version <> selected_launch.captured_starting_row_version + OR selected_launch.complete_launch_binding_evidence -> 'descriptor' ->> 'requestDigest' + IS DISTINCT FROM selected_intent.descriptor_request_digest + OR selected_launch.complete_launch_binding_evidence -> 'descriptor' ->> 'resultDigest' + IS DISTINCT FROM selected_intent.descriptor_result_digest + OR selected_intent.tenant_association_operation_id <> selected_launch.tenant_association_operation_id + OR selected_intent.catalog_source_intake_operation_id <> selected_launch.catalog_source_intake_operation_id + OR selected_intent.catalog_source_intake_request_id <> selected_launch.catalog_source_intake_request_id + OR selected_catalog.creation_request_id <> selected_intent.catalog_creation_request_id + OR selected_catalog.catalog_revision <> selected_intent.catalog_revision + OR selected_catalog.source_intake_operation_id <> selected_intent.catalog_source_intake_operation_id + OR selected_catalog.source_intake_request_id <> selected_intent.catalog_source_intake_request_id + OR selected_catalog.request_digest <> selected_intent.catalog_request_digest + OR selected_catalog.receipt_digest <> selected_intent.catalog_receipt_digest + OR selected_catalog.fixture_policy_seal_evidence_digest IS DISTINCT FROM p_new.fixture_provenance_digest + OR selected_launch.catalog_creation_request_id <> selected_catalog.creation_request_id + OR selected_launch.catalog_revision <> selected_catalog.catalog_revision + OR selected_launch.playable_state_scope <> selected_catalog.state_scope + OR selected_launch.public_production IS NOT TRUE + OR selected_catalog.visible IS NOT TRUE + OR selected_catalog.public_production IS NOT TRUE + OR selected_catalog.state_scope <> 'SHARED' + THEN + RAISE EXCEPTION 'Run-owned fixture admission is not linked to its exact intent, fixture launch and catalog' + USING ERRCODE = '23514'; + END IF; + + BEGIN + hold_json := convert_from(selected_intent.hold_identity_bytes, 'UTF8')::JSONB; + EXCEPTION WHEN OTHERS THEN + RAISE EXCEPTION 'Fixture admission hold identity is not structurally readable' + USING ERRCODE = '23514'; + END; + IF hold_json ->> 'schema' IS DISTINCT FROM 'world-canonical-initial-admission-hold-identity/v1' + OR hold_json ->> 'holdId' IS DISTINCT FROM p_new.hold_id::TEXT + OR hold_json ->> 'holdFence' IS DISTINCT FROM p_new.hold_fence::TEXT + OR hold_json ->> 'holdBindingDigest' IS DISTINCT FROM p_new.hold_binding_digest + OR decode(hold_json ->> 'requestBytesBase64', 'base64') + IS DISTINCT FROM selected_intent.canonical_hold_request_bytes + THEN + RAISE EXCEPTION 'Fixture admission differs from its attached World hold identity' + USING ERRCODE = '23514'; + END IF; + + digest_bytes := ''::BYTEA; + FOREACH field_bytes IN ARRAY ARRAY[ + convert_to('game-session-canonical-initial-admission/v1', 'UTF8'), + convert_to(p_new.target_namespace, 'UTF8'), + convert_to(p_new.canonical_tenant_id::TEXT, 'UTF8'), + convert_to(p_new.world_slug, 'UTF8'), + convert_to(p_new.realm_id::TEXT, 'UTF8'), + convert_to(p_new.playable_state_namespace_id::TEXT, 'UTF8'), + convert_to(p_new.playable_state_scope, 'UTF8'), + convert_to(p_new.canonical_game_instance_id::TEXT, 'UTF8'), + convert_to(p_new.canonical_version_id::TEXT, 'UTF8'), + convert_to(p_new.active_lifecycle_epoch::TEXT, 'UTF8'), + convert_to(p_new.expected_catalog_revision::TEXT, 'UTF8'), + convert_to(p_new.origin_kind, 'UTF8'), + convert_to(COALESCE(p_new.expected_prior_pointer_version::TEXT, ''), 'UTF8'), + convert_to(p_new.initial_admission_request_id, 'UTF8')] + LOOP + digest_bytes := digest_bytes || int4send(octet_length(field_bytes)) || field_bytes; + END LOOP; + expected_request_digest := encode(sha256(digest_bytes), 'hex'); + IF p_new.request_digest <> expected_request_digest THEN + RAISE EXCEPTION 'Canonical initial-admission request digest does not bind the exact V28 fields' + USING ERRCODE = '23514'; + END IF; + + IF p_new.status = 'PENDING' THEN + RETURN p_new; + END IF; + + IF p_new.pointer_id IS NULL OR p_new.pointer_version IS NULL OR p_new.audit_event_id IS NULL + OR p_new.abort_reason IS NOT NULL OR p_new.abort_proof_digest IS NOT NULL + OR NOT EXISTS ( + SELECT 1 FROM game_session_run_owned_fixture_runtime_completion completion + WHERE completion.target_namespace = p_new.target_namespace + AND completion.initial_admission_request_id = p_new.initial_admission_request_id + AND completion.request_digest = p_new.request_digest + AND completion.canonical_game_instance_id = p_new.canonical_game_instance_id + AND completion.canonical_version_id = p_new.canonical_version_id + AND completion.game_session_tenant_id = p_new.game_session_tenant_id + AND completion.game_instance_id = p_new.game_instance_id + AND completion.hold_id = p_new.hold_id + AND completion.hold_fence = p_new.hold_fence + AND completion.hold_binding_digest = p_new.hold_binding_digest + AND completion.fixture_provenance_digest = p_new.fixture_provenance_digest) + THEN + RAISE EXCEPTION 'COMMITTED fixture admission requires complete terminal fields and its retained runtime completion' + USING ERRCODE = '23514'; + END IF; + + digest_bytes := ''::BYTEA; + FOREACH field_bytes IN ARRAY ARRAY[ + convert_to('game-session-canonical-initial-admission-terminal/v1', 'UTF8'), + convert_to(p_new.fixture_provenance_digest, 'UTF8'), + convert_to(p_new.request_digest, 'UTF8'), + convert_to(p_new.status, 'UTF8'), + convert_to(COALESCE(p_new.pointer_id::TEXT, ''), 'UTF8'), + convert_to(COALESCE(p_new.pointer_version::TEXT, ''), 'UTF8'), + convert_to(COALESCE(p_new.audit_event_id::TEXT, ''), 'UTF8'), + convert_to(to_char(p_new.terminal_at AT TIME ZONE 'UTC', 'YYYY-MM-DD"T"HH24:MI:SS.US"Z"'), 'UTF8'), + convert_to(COALESCE(p_new.abort_reason, ''), 'UTF8')] + LOOP + digest_bytes := digest_bytes || int4send(octet_length(field_bytes)) || field_bytes; + END LOOP; + p_new.commit_proof_digest := 'sha256:' || encode(sha256(digest_bytes), 'hex'); + RETURN p_new; +END; +$$; + +DO $migration$ +DECLARE definition TEXT; original TEXT; replacement TEXT; +BEGIN + -- Intent and attempt terminal guard: branch the fixture provenance, leave Human checks intact. + SELECT pg_get_functiondef((quote_ident(current_schema()) + ||'.require_game_session_canonical_initial_admission_account_terminal_evidence()')::regprocedure) + INTO STRICT definition; + + original := $needle$ IF NEW.original_start_session_tuple IS NULL + OR octet_length(NEW.original_start_session_tuple) NOT BETWEEN 1 AND 262144 + OR selected_launch.target_namespace IS NULL$needle$; + replacement := $replacement$ IF (CASE WHEN selected_launch.fixture_policy_request_bytes IS NOT NULL + THEN NEW.original_start_session_tuple IS NOT NULL + ELSE NEW.original_start_session_tuple IS NULL + OR octet_length(NEW.original_start_session_tuple) NOT BETWEEN 1 AND 262144 + END) + OR selected_launch.target_namespace IS NULL$replacement$; + IF (length(definition)-length(replace(definition,original,'')))/length(original)<>1 THEN + RAISE EXCEPTION 'Expected exact intent original tuple clause'; END IF; + definition := replace(definition,original,replacement); + + original := $needle$ OR selected_launch.complete_launch_binding_evidence -> 'releaseAttestation' ->> 'evidenceDigest' + IS DISTINCT FROM NEW.release_attestation_digest$needle$; + replacement := $replacement$ OR COALESCE(selected_launch.fixture_policy_seal_evidence_digest, + selected_launch.complete_launch_binding_evidence -> 'releaseAttestation' ->> 'evidenceDigest') + IS DISTINCT FROM NEW.release_attestation_digest$replacement$; + IF (length(definition)-length(replace(definition,original,'')))/length(original)<>1 THEN + RAISE EXCEPTION 'Expected exact intent release attestation clause'; END IF; + definition := replace(definition,original,replacement); + + original := $needle$ AND attempt.account_protection_evidence_version = 1 + AND attempt.account_protection_evidence_bytes IS NOT NULL$needle$; + replacement := $replacement$ AND ((attempt.account_protection_evidence_version = 1 + AND attempt.account_protection_evidence_bytes IS NOT NULL) + OR (attempt.status = 'COMMITTED' + AND attempt.account_protection_evidence_version IS NULL + AND attempt.fixture_provenance_digest IS NOT NULL + AND attempt.fixture_provenance_digest = NEW.release_attestation_digest + AND NEW.original_start_session_tuple IS NULL))$replacement$; + IF (length(definition)-length(replace(definition,original,'')))/length(original)<>1 THEN + RAISE EXCEPTION 'Expected exact intent terminal protection clause'; END IF; + definition := replace(definition,original,replacement); + + original := $needle$ IF NEW.status NOT IN ('PENDING', 'COMMITTED', 'ABORTED') + OR NEW.account_protection_evidence_version IS DISTINCT FROM 1$needle$; + replacement := $replacement$ IF NEW.fixture_provenance_digest IS NOT NULL + OR (TG_OP = 'UPDATE' AND OLD.fixture_provenance_digest IS NOT NULL) THEN + NEW := require_gs_run_owned_fixture_initial_admission_attempt(TG_OP, OLD, NEW); + RETURN NEW; + END IF; + +$replacement$ || original; + IF (length(definition)-length(replace(definition,original,'')))/length(original)<>1 THEN + RAISE EXCEPTION 'Expected exact attempt protection clause'; END IF; + definition := replace(definition,original,replacement); + EXECUTE definition; + + -- Atomic pointer/audit evidence: the fixture binds its canonical version through its completion. + SELECT pg_get_functiondef((quote_ident(current_schema()) + ||'.require_game_session_canonical_initial_admission_atomic_evidence()')::regprocedure) + INTO STRICT definition; + original := $needle$ AND launch.complete_launch_binding_evidence -> 'releaseAttestation' ->> 'canonicalVersionId' + = attempt.canonical_version_id::text$needle$; + replacement := $replacement$ AND (launch.complete_launch_binding_evidence -> 'releaseAttestation' ->> 'canonicalVersionId' + = attempt.canonical_version_id::text + OR (launch.fixture_policy_request_bytes IS NOT NULL + AND attempt.fixture_provenance_digest = launch.fixture_policy_seal_evidence_digest + AND EXISTS ( + SELECT 1 FROM game_session_run_owned_fixture_runtime_completion completion + WHERE completion.target_namespace = attempt.target_namespace + AND completion.initial_admission_request_id = attempt.initial_admission_request_id + AND completion.canonical_game_instance_id = attempt.canonical_game_instance_id + AND completion.canonical_version_id = attempt.canonical_version_id + AND completion.fixture_provenance_digest = attempt.fixture_provenance_digest)))$replacement$; + IF (length(definition)-length(replace(definition,original,'')))/length(original)<>1 THEN + RAISE EXCEPTION 'Expected exact atomic launch canonical version clause'; END IF; + EXECUTE replace(definition,original,replacement); + + -- OPEN pointer owner guard: same fixture canonical-version binding. + SELECT pg_get_functiondef((quote_ident(current_schema()) + ||'.require_game_session_canonical_initial_admission_catalog()')::regprocedure) + INTO STRICT definition; + original := $needle$ AND launch.complete_launch_binding_evidence -> 'releaseAttestation' ->> 'canonicalVersionId' + = NEW.canonical_version_id::text$needle$; + replacement := $replacement$ AND (launch.complete_launch_binding_evidence -> 'releaseAttestation' ->> 'canonicalVersionId' + = NEW.canonical_version_id::text + OR (launch.fixture_policy_request_bytes IS NOT NULL + AND EXISTS ( + SELECT 1 FROM game_session_run_owned_fixture_runtime_completion completion + WHERE completion.target_namespace = NEW.target_namespace + AND completion.initial_admission_request_id = NEW.initial_admission_request_id + AND completion.request_digest = NEW.initial_admission_request_digest + AND completion.canonical_game_instance_id = NEW.canonical_game_instance_id + AND completion.canonical_version_id = NEW.canonical_version_id + AND completion.fixture_provenance_digest = launch.fixture_policy_seal_evidence_digest)))$replacement$; + IF (length(definition)-length(replace(definition,original,'')))/length(original)<>1 THEN + RAISE EXCEPTION 'Expected exact pointer launch canonical version clause'; END IF; + EXECUTE replace(definition,original,replacement); + + -- Fresh source-bound tenant scope for OPEN pointer/audit rows: same fixture binding. + SELECT pg_get_functiondef((quote_ident(current_schema()) + ||'.reserve_game_session_tenant_scope()')::regprocedure) + INTO STRICT definition; + original := $needle$ AND launch.complete_launch_binding_evidence -> 'releaseAttestation' ->> 'canonicalVersionId' + = attempt.canonical_version_id::text$needle$; + replacement := $replacement$ AND (launch.complete_launch_binding_evidence -> 'releaseAttestation' ->> 'canonicalVersionId' + = attempt.canonical_version_id::text + OR (launch.fixture_policy_request_bytes IS NOT NULL + AND attempt.fixture_provenance_digest = launch.fixture_policy_seal_evidence_digest + AND EXISTS ( + SELECT 1 FROM game_session_run_owned_fixture_runtime_completion completion + WHERE completion.target_namespace = attempt.target_namespace + AND completion.initial_admission_request_id = attempt.initial_admission_request_id + AND completion.canonical_game_instance_id = attempt.canonical_game_instance_id + AND completion.canonical_version_id = attempt.canonical_version_id + AND completion.fixture_provenance_digest = attempt.fixture_provenance_digest)))$replacement$; + IF (length(definition)-length(replace(definition,original,'')))/length(original)<>1 THEN + RAISE EXCEPTION 'Expected exact tenant scope launch canonical version clause'; END IF; + EXECUTE replace(definition,original,replacement); +END; +$migration$; + +INSERT INTO game_session_runtime_family_classification + (family_id,relation_name,family_role,state_class,fresh_disposition,retention_disposition,owner_consequence) +VALUES ('game_session_run_owned_fixture_runtime_completion','game_session_run_owned_fixture_runtime_completion', + 'PROVENANCE','NOT_PAYLOAD','PROVENANCE_ONLY','OWNER_POLICY_RETAINED', + 'Original run-owned fixture STARTING-to-RUNNING row versions and fixture provenance remain immutable provenance, not first OPEN, Account protection or private runtime creation.'); + +DO $migration$ +DECLARE definition TEXT; original TEXT; replacement TEXT; +BEGIN + SELECT pg_get_functiondef((quote_ident(current_schema())||'.gs_runtime_family_catalog_installed()')::regprocedure) INTO STRICT definition; + original := $needle$WHERE version='1066.1' + ) AND ($needle$; + replacement := $replacement$WHERE version='1066.1' + ) AND ( + SELECT count(*)=1 AND coalesce(bool_and(type='SQL' + AND script='V1070__game_session_run_owned_fixture_initial_admission.sql' AND success),false) + FROM "${flyway:table}" WHERE version='1070' + ) AND ($replacement$; + IF (length(definition)-length(replace(definition,original,'')))/length(original)<>1 THEN + RAISE EXCEPTION 'Expected exact predecessor catalog installation clause'; END IF; + EXECUTE replace(definition,original,replacement); + + SELECT pg_get_functiondef((quote_ident(current_schema())||'.gs_runtime_family_catalog_bytes(bigint)')::regprocedure) INTO STRICT definition; + original := $needle$AND version IS DISTINCT FROM '1066.1'$needle$; + replacement := original||E'\n AND version IS DISTINCT FROM ''1070'''; + IF (length(definition)-length(replace(definition,original,'')))/length(original)<>1 THEN + RAISE EXCEPTION 'Expected exact predecessor history exclusion'; END IF; + definition := replace(definition,original,replacement); + original := $needle$SELECT 'MIGRATION','catalog-installation:1066.1','V1066.1__transferred_capacity_origin_recovery.sql'$needle$; + replacement := original||E'\n UNION ALL\n SELECT ''MIGRATION'',''catalog-installation:1070'',''V1070__game_session_run_owned_fixture_initial_admission.sql'''; + IF (length(definition)-length(replace(definition,original,'')))/length(original)<>1 THEN + RAISE EXCEPTION 'Expected exact predecessor catalog marker'; END IF; + EXECUTE replace(definition,original,replacement); +END; +$migration$; + +INSERT INTO game_session_runtime_family_catalog_epoch(catalog_epoch,catalog_bytes,catalog_digest) +SELECT epoch,bytes,'sha256:'||encode(sha256(bytes),'hex') FROM ( + SELECT epoch,gs_runtime_family_catalog_bytes(epoch) AS bytes FROM ( + SELECT coalesce(max(catalog_epoch),0)+1 AS epoch FROM game_session_runtime_family_catalog_epoch + ) next_epoch +) seal; +-- [jooq ignore stop] diff --git a/services/game-session-service/src/main/resources/db/migration/V1071__run_owned_fixture_preseeded_only_catalog.sql b/services/game-session-service/src/main/resources/db/migration/V1071__run_owned_fixture_preseeded_only_catalog.sql new file mode 100644 index 0000000000..34d934dbc1 --- /dev/null +++ b/services/game-session-service/src/main/resources/db/migration/V1071__run_owned_fixture_preseeded_only_catalog.sql @@ -0,0 +1,58 @@ +-- The run-owned fixture realm admits only preseeded characters, matching the canonical PLAY chain +-- (Account discovery, entitlement and Game Session admission accept PRESEEDED_ONLY). Pre-v1 +-- fixture rows are throwaway, so retained rows are not revalidated. +-- [jooq ignore start] +ALTER TABLE game_session_canonical_realm_catalog + DROP CONSTRAINT chk_gs_catalog_fixture_provenance; +ALTER TABLE game_session_canonical_realm_catalog + ADD CONSTRAINT chk_gs_catalog_fixture_provenance CHECK ( + (fixture_policy_request_bytes IS NULL AND fixture_policy_seal_operation_id IS NULL + AND fixture_policy_seal_request_digest IS NULL AND fixture_policy_seal_evidence_digest IS NULL) + OR (complete_policy_set_evidence IS NULL AND fixture_policy_request_bytes IS NOT NULL + AND octet_length(fixture_policy_request_bytes) > 0 + AND fixture_policy_seal_operation_id IS NOT NULL + AND fixture_policy_seal_operation_id <> '00000000-0000-0000-0000-000000000000'::UUID + AND fixture_policy_seal_request_digest IS NOT NULL + AND fixture_policy_seal_request_digest ~ '^sha256:[0-9a-f]{64}$' + AND fixture_policy_seal_evidence_digest IS NOT NULL + AND fixture_policy_seal_evidence_digest ~ '^sha256:[0-9a-f]{64}$' + AND visible AND public_production AND state_scope = 'SHARED' + AND character_creation_policy = 'PRESEEDED_ONLY')) NOT VALID; + +DO $migration$ +DECLARE definition TEXT; original TEXT; replacement TEXT; +BEGIN + SELECT pg_get_functiondef((quote_ident(current_schema())||'.gs_runtime_family_catalog_installed()')::regprocedure) INTO STRICT definition; + original := $needle$WHERE version='1070' + ) AND ($needle$; + replacement := $replacement$WHERE version='1070' + ) AND ( + SELECT count(*)=1 AND coalesce(bool_and(type='SQL' + AND script='V1071__run_owned_fixture_preseeded_only_catalog.sql' AND success),false) + FROM "${flyway:table}" WHERE version='1071' + ) AND ($replacement$; + IF (length(definition)-length(replace(definition,original,'')))/length(original)<>1 THEN + RAISE EXCEPTION 'Expected exact predecessor catalog installation clause'; END IF; + EXECUTE replace(definition,original,replacement); + + SELECT pg_get_functiondef((quote_ident(current_schema())||'.gs_runtime_family_catalog_bytes(bigint)')::regprocedure) INTO STRICT definition; + original := $needle$AND version IS DISTINCT FROM '1070'$needle$; + replacement := original||E'\n AND version IS DISTINCT FROM ''1071'''; + IF (length(definition)-length(replace(definition,original,'')))/length(original)<>1 THEN + RAISE EXCEPTION 'Expected exact predecessor history exclusion'; END IF; + definition := replace(definition,original,replacement); + original := $needle$SELECT 'MIGRATION','catalog-installation:1070','V1070__game_session_run_owned_fixture_initial_admission.sql'$needle$; + replacement := original||E'\n UNION ALL\n SELECT ''MIGRATION'',''catalog-installation:1071'',''V1071__run_owned_fixture_preseeded_only_catalog.sql'''; + IF (length(definition)-length(replace(definition,original,'')))/length(original)<>1 THEN + RAISE EXCEPTION 'Expected exact predecessor catalog marker'; END IF; + EXECUTE replace(definition,original,replacement); +END; +$migration$; + +INSERT INTO game_session_runtime_family_catalog_epoch(catalog_epoch,catalog_bytes,catalog_digest) +SELECT epoch,bytes,'sha256:'||encode(sha256(bytes),'hex') FROM ( + SELECT epoch,gs_runtime_family_catalog_bytes(epoch) AS bytes FROM ( + SELECT coalesce(max(catalog_epoch),0)+1 AS epoch FROM game_session_runtime_family_catalog_epoch + ) next_epoch +) seal; +-- [jooq ignore stop] diff --git a/services/game-session-service/src/test/java/integration/net/firedevops/firemud/gamesession/repository/CanonicalGameplayRegionTransferMixedInventoryIntegrationTest.java b/services/game-session-service/src/test/java/integration/net/firedevops/firemud/gamesession/repository/CanonicalGameplayRegionTransferMixedInventoryIntegrationTest.java index 4a979fccf1..ec2c20674d 100644 --- a/services/game-session-service/src/test/java/integration/net/firedevops/firemud/gamesession/repository/CanonicalGameplayRegionTransferMixedInventoryIntegrationTest.java +++ b/services/game-session-service/src/test/java/integration/net/firedevops/firemud/gamesession/repository/CanonicalGameplayRegionTransferMixedInventoryIntegrationTest.java @@ -306,6 +306,11 @@ private void calibrateMixedRetainedExecutionHandoff(boolean loseLastMarker, int } assertThat(proof.executionState(proof.execution)).isEqualTo("COMMITTED"); String originalReceipts = proof.originalImage(); + if (cohortSize > CanonicalGameplayRegionOwnerTransferRepository.PAGE_SIZE) { + // Give each one-shot dispatch its own budget before measuring paged verification. + // The small-cohort case still dispatches through advance within one deadline. + for (var item : captured) proof.fence(item); + } var observationLatency = Duration.ofMillis(5); var attestor = @@ -342,8 +347,8 @@ private void calibrateMixedRetainedExecutionHandoff(boolean loseLastMarker, int int pages = (cohortSize + CanonicalGameplayRegionOwnerTransferRepository.PAGE_SIZE - 1) / CanonicalGameplayRegionOwnerTransferRepository.PAGE_SIZE; - // Bounded calls can stop while fencing or verifying a page. Retry the same transfer - // and prove the predecessor and exact terminal receipts stay intact until it qualifies. + // Bounded verification calls may stop between pages. Keep the predecessor and original + // receipts intact until the retained fences qualify. UUID verified = null; for (int attempt = 0; attempt < 4 * pages && verified == null; attempt++) { try { @@ -356,10 +361,7 @@ private void calibrateMixedRetainedExecutionHandoff(boolean loseLastMarker, int if (cohortSize == 3 || !List.of( "Normal region handoff requires complete current transfer evidence", - "Normal region owner transfer is held", - // A 5 s budget that ends inside the Redis fence surfaces untyped; FENCE is - // idempotent, so the same transfer resumes on the next attempt. - "Original NEW final admission Redis readback is unavailable") + "Normal region owner transfer is held") .contains(held.getMessage())) throw held; } assertThat(proof.currentOwner()).isEqualTo(proof.prior); diff --git a/services/game-session-service/src/test/java/integration/net/firedevops/firemud/gamesession/repository/CanonicalInitialAdmissionProtectedWriterPostgresIntegrationTest.java b/services/game-session-service/src/test/java/integration/net/firedevops/firemud/gamesession/repository/CanonicalInitialAdmissionProtectedWriterPostgresIntegrationTest.java index af2ee3e76a..42bcce69fa 100644 --- a/services/game-session-service/src/test/java/integration/net/firedevops/firemud/gamesession/repository/CanonicalInitialAdmissionProtectedWriterPostgresIntegrationTest.java +++ b/services/game-session-service/src/test/java/integration/net/firedevops/firemud/gamesession/repository/CanonicalInitialAdmissionProtectedWriterPostgresIntegrationTest.java @@ -1772,9 +1772,25 @@ private static CanonicalInitialAdmissionWorldProof worldProof( request.holdBindingDigest()); } + /** + * The exact Human attempt row. The run-owned fixture's {@code fixture_provenance_digest} column + * (V1070) is omitted while it is null, so pre- and post-upgrade Human rows compare exactly. + */ private static Record terminal( CanonicalInitialAdmissionIntentRepositoryIntegrationTest.Harness harness, CanonicalInitialAdmissionRequest request) { + Record row = terminalWithAllColumns(harness, request); + org.jooq.Field fixture = row.field("fixture_provenance_digest"); + if (fixture == null || row.get(fixture) != null) return row; + return row.into( + java.util.Arrays.stream(row.fields()) + .filter(field -> !field.getName().equals("fixture_provenance_digest")) + .toArray(org.jooq.Field[]::new)); + } + + private static Record terminalWithAllColumns( + CanonicalInitialAdmissionIntentRepositoryIntegrationTest.Harness harness, + CanonicalInitialAdmissionRequest request) { return harness .dsl() .fetchSingle( diff --git a/services/game-session-service/src/test/java/integration/net/firedevops/firemud/gamesession/repository/CanonicalInitialAdmissionRepositoryIntegrationTest.java b/services/game-session-service/src/test/java/integration/net/firedevops/firemud/gamesession/repository/CanonicalInitialAdmissionRepositoryIntegrationTest.java index 3f733165f8..17cb35a730 100644 --- a/services/game-session-service/src/test/java/integration/net/firedevops/firemud/gamesession/repository/CanonicalInitialAdmissionRepositoryIntegrationTest.java +++ b/services/game-session-service/src/test/java/integration/net/firedevops/firemud/gamesession/repository/CanonicalInitialAdmissionRepositoryIntegrationTest.java @@ -1489,7 +1489,7 @@ private static String allAttemptProjection(Fixture fixture) { return fixture .dsl .fetchSingle( - "SELECT jsonb_agg(jsonb_build_array(xmin::TEXT, to_jsonb(attempt)) " + "SELECT jsonb_agg(jsonb_build_array(xmin::TEXT, to_jsonb(attempt) - 'fixture_provenance_digest') " + "ORDER BY initial_admission_request_id)::TEXT FROM game_session_canonical_initial_admission_attempt attempt") .get(0, String.class); } @@ -2114,7 +2114,7 @@ private static String predecessorAttemptProjection( "SELECT jsonb_build_array(xmin::TEXT, to_jsonb(attempt) - ARRAY[" + "'account_protection_evidence_version', 'account_protection_id', " + "'account_protection_fence', 'original_owner_attempt_id', 'original_owner_mutation_id', " - + "'original_owner_fence', 'account_protection_evidence_bytes'])::TEXT AS projection " + + "'original_owner_fence', 'account_protection_evidence_bytes', 'fixture_provenance_digest'])::TEXT AS projection " + "FROM game_session_canonical_initial_admission_attempt attempt " + "WHERE target_namespace = ? AND initial_admission_request_id = ?", NAMESPACE, @@ -2155,7 +2155,8 @@ private static String attemptProjection( return fixture .dsl .fetchSingle( - "SELECT xmin::text || '/' || to_jsonb(attempt)::text AS projection " + "SELECT xmin::text || '/' || " + + "(to_jsonb(attempt) - 'fixture_provenance_digest')::text AS projection " + "FROM game_session_canonical_initial_admission_attempt attempt WHERE target_namespace = ? " + "AND initial_admission_request_id = ?", request.targetNamespace(), @@ -2581,7 +2582,18 @@ private static String otherGuardProjection(Fixture fixture) { + "'fk_gs_canonical_human_runtime_completion_attempt', " + "'fk_gs_canonical_human_runtime_completion_launch') " + "AND completion_child.relname = 'game_session_canonical_human_runtime_completion' " - + "AND completion_namespace.nspname = current_schema())) guard") + + "AND completion_namespace.nspname = current_schema()) " + + "AND NOT EXISTS (SELECT 1 FROM pg_constraint fixture_fk " + + "JOIN pg_class fixture_child ON fixture_child.oid = fixture_fk.conrelid " + + "JOIN pg_namespace fixture_namespace " + + "ON fixture_namespace.oid = fixture_child.relnamespace " + + "WHERE fixture_fk.oid = trigger.tgconstraint " + + "AND fixture_fk.conname IN (" + + "'fk_gs_run_owned_fixture_runtime_completion_intent', " + + "'fk_gs_run_owned_fixture_runtime_completion_attempt', " + + "'fk_gs_run_owned_fixture_runtime_completion_launch') " + + "AND fixture_child.relname = 'game_session_run_owned_fixture_runtime_completion' " + + "AND fixture_namespace.nspname = current_schema())) guard") .get(0, String.class); } diff --git a/services/game-session-service/src/test/java/integration/net/firedevops/firemud/gamesession/repository/GameSessionRunOwnedFixtureFirstOpenPostgresIntegrationTest.java b/services/game-session-service/src/test/java/integration/net/firedevops/firemud/gamesession/repository/GameSessionRunOwnedFixtureFirstOpenPostgresIntegrationTest.java new file mode 100644 index 0000000000..d065947caa --- /dev/null +++ b/services/game-session-service/src/test/java/integration/net/firedevops/firemud/gamesession/repository/GameSessionRunOwnedFixtureFirstOpenPostgresIntegrationTest.java @@ -0,0 +1,445 @@ +package integration.net.firedevops.firemud.gamesession.repository; + +import static org.assertj.core.api.Assertions.assertThat; +import static org.assertj.core.api.Assertions.assertThatThrownBy; + +import java.nio.charset.StandardCharsets; +import java.nio.file.Path; +import java.util.Objects; +import java.util.UUID; +import net.firedevops.firemud.common.smoke.RunOwnedInitialAdmissionFixtureWireCodec; +import net.firedevops.firemud.common.tenant.AuthoredWorldSourceDigest; +import net.firedevops.firemud.common.tenant.AuthoredWorldSourceEvidence; +import net.firedevops.firemud.common.world.WorldCanonicalInitialAdmissionHold; +import net.firedevops.firemud.common.world.WorldCanonicalInstanceLifecycleEvidence; +import net.firedevops.firemud.gamesession.data.RunOwnedInitialAdmissionLaunchEvidence; +import net.firedevops.firemud.gamesession.data.RunOwnedInitialAdmissionLaunchEvidenceTestFixture; +import net.firedevops.firemud.gamesession.dto.CanonicalInitialAdmissionOwnerProof; +import net.firedevops.firemud.gamesession.dto.CanonicalInitialAdmissionRequest; +import net.firedevops.firemud.gamesession.dto.CanonicalInitialAdmissionWorldProof; +import net.firedevops.firemud.gamesession.dto.StartSessionRequest; +import net.firedevops.firemud.gamesession.repository.CanonicalGameInstanceLaunchAssociationRepository; +import net.firedevops.firemud.gamesession.repository.CanonicalGameplayIssuerTestFixtures; +import net.firedevops.firemud.gamesession.repository.CanonicalInitialAdmissionIntentRepository; +import net.firedevops.firemud.gamesession.repository.CanonicalInitialAdmissionRepository; +import net.firedevops.firemud.gamesession.repository.GameSessionAuthoredWorldSourceRepository; +import net.firedevops.firemud.gamesession.repository.GameSessionAuthoredWorldSourceRepository.IntakeReceipt; +import net.firedevops.firemud.gamesession.repository.GameSessionCanonicalAdmissionPointerRepository; +import net.firedevops.firemud.gamesession.repository.GameSessionCanonicalInstanceLaunchRepository; +import net.firedevops.firemud.gamesession.repository.GameSessionCanonicalInstanceLaunchRepository.FixtureCanonicalInstanceLaunch; +import net.firedevops.firemud.gamesession.repository.GameSessionCanonicalRealmCatalogRepository; +import net.firedevops.firemud.gamesession.repository.GameSessionFreshTenantAssociationRepository; +import net.firedevops.firemud.gamesession.repository.GameplayAdmissionPointerEventRepository; +import net.firedevops.firemud.gamesession.repository.RunOwnedFixtureRuntimeCompletionRepository; +import net.firedevops.firemud.gamesession.service.CanonicalPlayerRouteReadService; +import net.firedevops.firemud.test.PostgresBackedServiceTestSupport; +import net.firedevops.firemud.test.TestContainerImages; +import org.jooq.DSLContext; +import org.jooq.Record; +import org.jooq.SQLDialect; +import org.jooq.impl.DSL; +import org.junit.jupiter.api.BeforeAll; +import org.junit.jupiter.api.Test; +import org.springframework.jdbc.datasource.DataSourceTransactionManager; +import org.springframework.jdbc.datasource.DriverManagerDataSource; +import org.springframework.jdbc.datasource.TransactionAwareDataSourceProxy; +import org.springframework.transaction.TransactionDefinition; +import org.springframework.transaction.support.TransactionTemplate; +import org.testcontainers.containers.PostgreSQLContainer; +import org.testcontainers.junit.jupiter.Container; +import org.testcontainers.junit.jupiter.Testcontainers; + +/** + * PostgreSQL proof for the run-owned fixture first OPEN through the Game Session intent, attempt, + * fixture runtime completion and pointer owners. The World hold identity and ACTIVE proof are + * controlled test inputs; this does not claim a genuine World or Account producer. + */ +@Testcontainers(disabledWithoutDocker = true) +@SuppressWarnings("resource") +class GameSessionRunOwnedFixtureFirstOpenPostgresIntegrationTest { + private static final String NAMESPACE = + RunOwnedInitialAdmissionFixtureWireCodec.SOURCE_TARGET_NAMESPACE; + private static final long SOURCE_GAME_ROW_ID = 919L; + private static final String SOURCE_GAME_TENANT_KEY = "919"; + private static final long GAME_TEMPLATE_ID = 301L; + private static final long OWNER_ACCOUNT_ID = 401L; + private static final long ACTIVE_EPOCH = 2L; + private static final String MIGRATION_LOCATION = + "filesystem:" + Path.of("src/main/resources/db/migration").toAbsolutePath().normalize(); + + @Container + static PostgreSQLContainer postgres = + new PostgreSQLContainer<>(TestContainerImages.postgres()); + + @BeforeAll + static void awaitPostgresJdbcReady() { + PostgresBackedServiceTestSupport.awaitPostgresJdbcReady(postgres); + } + + @Test + void commitsFixtureFirstOpenThroughExactOwnersWithoutAccountProtection() { + Fixture f = fixture(); + AuthoredWorldSourceEvidence source = source(); + RunOwnedInitialAdmissionLaunchEvidence evidence = launchEvidence(source); + UUID fixtureOperationId = UUID.fromString(evidence.fixtureCapability().operationId()); + IntakeReceipt receipt = + Objects.requireNonNull( + f.transactions.execute(status -> f.sources.register(fixtureOperationId, source))); + f.transactions.executeWithoutResult( + status -> + f.tenantAssociations.associateFresh( + associationOperationId(source), NAMESPACE, receipt, evidence.creationEvidence())); + FixtureCanonicalInstanceLaunch launch = + f.instanceLaunches.createVerifiedFixtureStartingLaunch(evidence); + var catalog = launch.catalog().snapshot(); + var association = + f.launches + .readForInitialAdmission( + NAMESPACE, catalog.tenantId(), catalog.realmId(), launch.gameInstanceUuid()) + .orElseThrow() + .association(); + assertThat(association.isRunOwnedFixture()).isTrue(); + String provenance = evidence.fixturePolicySeal().evidenceDigest(); + assertThat(association.attestationDigest()).isEqualTo(provenance); + + String requestId = "run-owned-fixture-" + fixtureOperationId; + UUID canonicalVersionId = association.canonicalVersionId(); + String requestDigest = + CanonicalInitialAdmissionRequest.computeRequestDigest( + NAMESPACE, + catalog.tenantId(), + catalog.worldSlug(), + catalog.realmId(), + catalog.playableStateNamespaceId(), + catalog.stateScope(), + launch.gameInstanceUuid(), + canonicalVersionId, + ACTIVE_EPOCH, + catalog.catalogRevision(), + CanonicalInitialAdmissionRequest.OriginKind.NO_PRIOR_POINTER, + null, + requestId); + var holdRequest = + new WorldCanonicalInitialAdmissionHold.Request( + NAMESPACE, + catalog.tenantId(), + catalog.worldSlug(), + catalog.realmId(), + catalog.playableStateNamespaceId(), + catalog.stateScope(), + launch.gameInstanceUuid(), + canonicalVersionId, + ACTIVE_EPOCH, + requestId, + requestDigest, + WorldCanonicalInitialAdmissionHold.InitialAdmissionOrigin.NO_PRIOR_POINTER, + catalog.catalogRevision(), + null); + var lifecycleRequest = + new WorldCanonicalInstanceLifecycleEvidence.Request( + WorldCanonicalInstanceLifecycleEvidence.Request.SCHEMA_VERSION, + uuid(1201), + NAMESPACE, + catalog.tenantId(), + catalog.worldSlug(), + launch.gameInstanceUuid(), + catalog.playableStateNamespaceId(), + catalog.stateScope(), + true, + association.controlPlaneRequestId(), + canonicalVersionId, + association.descriptor().requestDigest(), + association.descriptor().resultDigest(), + association.attestationDigest()); + + var intent = + f.transactions.execute( + status -> f.intents.reserveFixtureStarting(holdRequest, lifecycleRequest)); + assertThat(intent.sourceBinding().releaseAttestationDigest()).isEqualTo(provenance); + var intentReplay = + f.transactions.execute( + status -> f.intents.reserveFixtureStarting(holdRequest, lifecycleRequest)); + assertThat(intentReplay.holdRequest().canonicalRequestBytes()) + .isEqualTo(intent.holdRequest().canonicalRequestBytes()); + assertThat(intentReplay.sourceBinding()).isEqualTo(intent.sourceBinding()); + assertThatThrownBy( + () -> + f.transactions.execute( + status -> f.intents.reserveHumanStarting(holdRequest, lifecycleRequest))) + .isInstanceOf(IllegalStateException.class); + + var hold = + new WorldCanonicalInitialAdmissionHold.HoldIdentity(holdRequest, uuid(1301), uuid(1302)); + var attached = + f.transactions.execute(status -> f.intents.attachFixtureStarting(holdRequest, hold)); + var attachReplay = + f.transactions.execute(status -> f.intents.attachFixtureStarting(holdRequest, hold)); + assertThat(attachReplay.holdIdentity().canonicalBytes()) + .isEqualTo(attached.holdIdentity().canonicalBytes()); + + CanonicalInitialAdmissionRequest request = request(hold); + CanonicalInitialAdmissionWorldProof worldProof = worldProof(request); + assertThat(flag(f, () -> f.admissions.reserveFixtureStarting(request))).isTrue(); + assertThat(flag(f, () -> f.admissions.reserveFixtureStarting(request))).isFalse(); + assertThat( + f.dsl + .fetchSingle( + "SELECT account_protection_id, fixture_provenance_digest, status " + + "FROM game_session_canonical_initial_admission_attempt " + + "WHERE target_namespace = ? AND initial_admission_request_id = ?", + NAMESPACE, + requestId) + .intoMap()) + .containsEntry("account_protection_id", null) + .containsEntry("fixture_provenance_digest", provenance) + .containsEntry("status", "PENDING"); + + // A raw STARTING -> RUNNING update without the retained fixture completion is refused. + assertThatThrownBy( + () -> + f.transactions.executeWithoutResult( + status -> + f.dsl.execute( + "UPDATE game_instances SET status = 'RUNNING', " + + "row_version = row_version + 1 WHERE tenant_id = ? AND id = ?", + association.gameSessionTenantId(), + launch.gameInstanceId()))) + .hasStackTraceContaining("requires its exact retained runtime completion"); + assertThat(runtimeStatus(f, association.gameSessionTenantId(), launch.gameInstanceId())) + .isEqualTo("STARTING"); + + var completion = f.transactions.execute(status -> f.completions.complete(request, worldProof)); + assertThat(completion.capturedStartingRowVersion()).isZero(); + assertThat(completion.completedRunningRowVersion()).isEqualTo(1L); + assertThat(completion.fixtureProvenanceDigest()).isEqualTo(provenance); + assertThat(replayCompletion(f, request, worldProof)).isEqualTo(completion); + assertThat(runtimeStatus(f, association.gameSessionTenantId(), launch.gameInstanceId())) + .isEqualTo("RUNNING"); + + assertThat(flag(f, () -> f.admissions.commitFixture(request, worldProof))).isTrue(); + assertThat(flag(f, () -> f.admissions.commitFixture(request, worldProof))).isFalse(); + assertThat(flag(f, () -> f.admissions.reserveFixtureStarting(request))).isFalse(); + assertThat(replayCompletion(f, request, worldProof)).isEqualTo(completion); + + CanonicalInitialAdmissionOwnerProof proof = + f.admissions.read(NAMESPACE, requestId).orElseThrow(); + assertThat(proof.outcome()).isEqualTo(CanonicalInitialAdmissionOwnerProof.Outcome.COMMITTED); + Record attempt = + f.dsl.fetchSingle( + "SELECT * FROM game_session_canonical_initial_admission_attempt " + + "WHERE target_namespace = ? AND initial_admission_request_id = ?", + NAMESPACE, + requestId); + assertThat(attempt.get("status", String.class)).isEqualTo("COMMITTED"); + assertThat(attempt.get("fixture_provenance_digest", String.class)).isEqualTo(provenance); + assertThat(attempt.get("account_protection_evidence_bytes", byte[].class)).isNull(); + assertThat( + f.dsl + .fetchSingle( + "SELECT state FROM game_session_canonical_initial_admission_intent " + + "WHERE target_namespace = ? AND initial_admission_request_id = ?", + NAMESPACE, + requestId) + .get(0, String.class)) + .isEqualTo("TERMINAL"); + assertThat( + f.dsl.fetchCount( + DSL.table(DSL.name("gameplay_admission_pointer")), + DSL.field(DSL.name("admission_state")).eq("OPEN"))) + .isEqualTo(1); + + var snapshot = + f.admissions.readCurrentOpenSnapshotForRealm( + NAMESPACE, catalog.tenantId(), catalog.realmId()); + assertThat(snapshot.ownerProof()).isEqualTo(proof); + var targets = + new CanonicalPlayerRouteReadService(NAMESPACE, f.catalogs, f.admissions, f.launches) + .readVisiblePublicProductionTargets(); + assertThat(targets).hasSize(1); + assertThat(targets.get(0).realmId()).isEqualTo(catalog.realmId()); + assertThat(targets.get(0).initialAdmissionRequestId()).isEqualTo(requestId); + assertThat(targets.get(0).activeWorldEpoch()).isEqualTo(ACTIVE_EPOCH); + } + + private static boolean flag(Fixture f, java.util.function.Supplier owner) { + Boolean result = f.transactions.execute(status -> owner.get()); + return Boolean.TRUE.equals(result); + } + + private static RunOwnedFixtureRuntimeCompletionRepository.Completion replayCompletion( + Fixture f, + CanonicalInitialAdmissionRequest request, + CanonicalInitialAdmissionWorldProof worldProof) { + return f.transactions.execute(status -> f.completions.complete(request, worldProof)); + } + + private static String runtimeStatus(Fixture f, long tenantId, long gameInstanceId) { + return f.dsl + .fetchSingle( + "SELECT status FROM game_instances WHERE tenant_id = ? AND id = ?", + tenantId, + gameInstanceId) + .get(0, String.class); + } + + private static CanonicalInitialAdmissionRequest request( + WorldCanonicalInitialAdmissionHold.HoldIdentity hold) { + var world = hold.request(); + return new CanonicalInitialAdmissionRequest( + world.targetNamespace(), + world.canonicalTenantId(), + world.worldSlug(), + world.realmId(), + world.playableStateNamespaceId(), + world.playableStateScope(), + world.canonicalGameInstanceId(), + world.canonicalVersionId(), + world.activeLifecycleEpoch(), + world.expectedCatalogRevision(), + CanonicalInitialAdmissionRequest.OriginKind.valueOf(world.initialAdmissionOrigin().name()), + world.expectedPriorPointerVersion(), + world.initialAdmissionRequestId(), + world.initialAdmissionRequestDigest(), + hold.holdId(), + hold.holdFence(), + hold.holdBindingDigest()); + } + + /** Controlled World verifier output; no genuine World service is claimed by this test. */ + private static CanonicalInitialAdmissionWorldProof worldProof( + CanonicalInitialAdmissionRequest request) { + return new CanonicalInitialAdmissionWorldProof( + request.initialAdmissionRequestId(), + request.requestDigest(), + request.targetNamespace(), + request.canonicalTenantId(), + request.worldSlug(), + request.realmId(), + request.playableStateNamespaceId(), + request.playableStateScope(), + request.canonicalGameInstanceId(), + request.canonicalVersionId(), + "ACTIVE", + request.activeLifecycleEpoch(), + request.originKind(), + request.expectedCatalogRevision(), + request.expectedPriorPointerVersion(), + request.holdId(), + request.holdFence(), + request.holdBindingDigest()); + } + + private static AuthoredWorldSourceEvidence source() { + UUID canonicalTenantId = uuid(1001); + UUID registrationRequestId = + UUID.fromString(RunOwnedInitialAdmissionLaunchEvidenceTestFixture.operationId()); + UUID sourceOperationId = uuid(1002); + String tenantSlug = "run-owned-fixture-tenant"; + String worldSlug = RunOwnedInitialAdmissionFixtureWireCodec.WORLD_SLUG; + String displayName = RunOwnedInitialAdmissionFixtureWireCodec.WORLD_DISPLAY_NAME; + String requestDigest = + AuthoredWorldSourceDigest.requestDigest( + NAMESPACE, + registrationRequestId, + canonicalTenantId, + tenantSlug, + worldSlug, + displayName); + String evidenceDigest = + AuthoredWorldSourceDigest.evidenceDigest( + NAMESPACE, + registrationRequestId, + sourceOperationId, + requestDigest, + canonicalTenantId, + tenantSlug, + worldSlug, + displayName, + SOURCE_GAME_ROW_ID, + SOURCE_GAME_TENANT_KEY, + "NEW_GAME_ROW"); + return new AuthoredWorldSourceEvidence( + 1, + NAMESPACE, + registrationRequestId, + sourceOperationId, + requestDigest, + canonicalTenantId, + tenantSlug, + worldSlug, + displayName, + SOURCE_GAME_ROW_ID, + SOURCE_GAME_TENANT_KEY, + "NEW_GAME_ROW", + evidenceDigest); + } + + private static RunOwnedInitialAdmissionLaunchEvidence launchEvidence( + AuthoredWorldSourceEvidence source) { + StartSessionRequest controlledCapabilityInput = + new StartSessionRequest( + Long.parseLong(source.sourceGameTenantKey()), + GAME_TEMPLATE_ID, + RunOwnedInitialAdmissionLaunchEvidenceTestFixture.operationId(), + OWNER_ACCOUNT_ID); + return RunOwnedInitialAdmissionLaunchEvidenceTestFixture.create( + controlledCapabilityInput, source); + } + + private static UUID associationOperationId(AuthoredWorldSourceEvidence source) { + return UUID.nameUUIDFromBytes( + ("test-only-gs-fresh-association:" + source.canonicalTenantId()) + .getBytes(StandardCharsets.UTF_8)); + } + + private static UUID uuid(int value) { + return UUID.fromString(String.format("%08d-1111-4111-8111-111111111111", value)); + } + + private static Fixture fixture() { + String schema = "gs_fixture_first_open_" + UUID.randomUUID().toString().replace("-", ""); + DriverManagerDataSource dataSource = new DriverManagerDataSource(); + dataSource.setDriverClassName("org.postgresql.Driver"); + dataSource.setUrl(postgres.getJdbcUrl()); + dataSource.setUsername(postgres.getUsername()); + dataSource.setPassword(postgres.getPassword()); + dataSource.setSchema(schema); + CanonicalGameplayIssuerTestFixtures.migrateSchema(dataSource, schema, MIGRATION_LOCATION, null); + + DataSourceTransactionManager transactionManager = new DataSourceTransactionManager(dataSource); + TransactionTemplate transactions = new TransactionTemplate(transactionManager); + transactions.setIsolationLevel(TransactionDefinition.ISOLATION_READ_COMMITTED); + DSLContext dsl = + DSL.using(new TransactionAwareDataSourceProxy(dataSource), SQLDialect.POSTGRES); + var catalogs = + new GameSessionCanonicalRealmCatalogRepository(dsl, transactionManager, NAMESPACE); + var launches = new CanonicalGameInstanceLaunchAssociationRepository(dsl, NAMESPACE); + var pointers = + new GameSessionCanonicalAdmissionPointerRepository( + dsl, catalogs, new GameplayAdmissionPointerEventRepository(dsl)); + return new Fixture( + dsl, + transactions, + new GameSessionAuthoredWorldSourceRepository(dsl), + new GameSessionFreshTenantAssociationRepository(dsl), + catalogs, + new GameSessionCanonicalInstanceLaunchRepository( + dsl, transactionManager, NAMESPACE, catalogs), + launches, + new CanonicalInitialAdmissionIntentRepository(dsl, catalogs, launches), + new CanonicalInitialAdmissionRepository(dsl, catalogs, pointers), + new RunOwnedFixtureRuntimeCompletionRepository(dsl, launches)); + } + + private record Fixture( + DSLContext dsl, + TransactionTemplate transactions, + GameSessionAuthoredWorldSourceRepository sources, + GameSessionFreshTenantAssociationRepository tenantAssociations, + GameSessionCanonicalRealmCatalogRepository catalogs, + GameSessionCanonicalInstanceLaunchRepository instanceLaunches, + CanonicalGameInstanceLaunchAssociationRepository launches, + CanonicalInitialAdmissionIntentRepository intents, + CanonicalInitialAdmissionRepository admissions, + RunOwnedFixtureRuntimeCompletionRepository completions) {} +} diff --git a/services/game-session-service/src/test/java/integration/net/firedevops/firemud/gamesession/repository/GameSessionRuntimeFamilyCatalogPostgresIntegrationTest.java b/services/game-session-service/src/test/java/integration/net/firedevops/firemud/gamesession/repository/GameSessionRuntimeFamilyCatalogPostgresIntegrationTest.java index c16a5b38cd..ec9b3b29a0 100644 --- a/services/game-session-service/src/test/java/integration/net/firedevops/firemud/gamesession/repository/GameSessionRuntimeFamilyCatalogPostgresIntegrationTest.java +++ b/services/game-session-service/src/test/java/integration/net/firedevops/firemud/gamesession/repository/GameSessionRuntimeFamilyCatalogPostgresIntegrationTest.java @@ -97,7 +97,7 @@ void currentCombinedChainSealsEveryEmptyTableActualRenamesComponentsAndExplicitB Map before = f.rows(f.tables()); var evidence = f.owner().capture(request()); var catalog = evidence.catalog(); - assertThat(catalog.catalogEpoch()).isEqualTo(23); + assertThat(catalog.catalogEpoch()).isEqualTo(25); assertThat( catalog.schemaFacts().stream() .filter(fact -> fact.kind() == FactKind.TABLE) @@ -224,7 +224,9 @@ void currentCombinedChainSealsEveryEmptyTableActualRenamesComponentsAndExplicitB "catalog-installation:1065.1", "catalog-installation:1065.2", "catalog-installation:1066", - "catalog-installation:1066.1") + "catalog-installation:1066.1", + "catalog-installation:1070", + "catalog-installation:1071") .noneMatch( identity -> identity.contains(":1057:") @@ -249,7 +251,9 @@ void currentCombinedChainSealsEveryEmptyTableActualRenamesComponentsAndExplicitB || identity.contains(":1065.1:") || identity.contains(":1065.2:") || identity.contains(":1066:") - || identity.contains(":1066.1:")); + || identity.contains(":1066.1:") + || identity.contains(":1070:") + || identity.contains(":1071:")); assertThat( f.dsl .fetchSingle( @@ -792,7 +796,7 @@ void viewOptionsDriftRefusesReadsRetriesAndNewRequestsWithoutChangingRetainedRow "CREATE MATERIALIZED VIEW catalog_probe_materialized AS SELECT id,description FROM game_manifest WITH NO DATA"); migration(f.source, f.schema, f.history, null).migrate(); var original = f.owner().capture(request()); - assertThat(original.catalog().catalogEpoch()).isEqualTo(23); + assertThat(original.catalog().catalogEpoch()).isEqualTo(25); assertThat(original.catalog().schemaFacts()) .anyMatch( fact -> @@ -950,7 +954,9 @@ void priorAndLaterHistoryAndOwnSuccessfulScriptRemainSeparateInstallationChecks( "1065.1", "1065.2", "1066", - "1066.1")) { + "1066.1", + "1070", + "1071")) { for (String change : List.of("success=false", "script='wrong_installation.sql'", "type='JDBC'")) { try (Fixture f = fixture(null)) { @@ -973,7 +979,7 @@ void priorAndLaterHistoryAndOwnSuccessfulScriptRemainSeparateInstallationChecks( "INSERT INTO " + f.history + "(installed_rank,version,description,type,script,checksum,installed_by,execution_time,success)" - + " VALUES(10000,'1067','controlled later migration','SQL','V1067__probe.sql',1,current_user,0,true)"); + + " VALUES(10000,'1071','controlled later migration','SQL','V1071__probe.sql',1,current_user,0,true)"); assertThatThrownBy(() -> f.owner().readExact(original.request())) .isInstanceOf(GameSessionRuntimeFamilyCatalogRepository.CatalogConflictException.class); } @@ -1001,7 +1007,9 @@ void priorAndLaterHistoryAndOwnSuccessfulScriptRemainSeparateInstallationChecks( "1065.1", "1065.2", "1066", - "1066.1")) { + "1066.1", + "1070", + "1071")) { try (Fixture f = fixture(null)) { f.dsl.execute( "INSERT INTO " @@ -1858,6 +1866,48 @@ void transferredOriginRecoveryUpgradeRetainsPopulatedCatalogAndSealsIssuingFence } } + @Test + void runOwnedFixtureAdmissionUpgradeRetainsPopulatedCatalogAndClassifiesCompletion() { + try (Fixture f = fixture("1066.1")) { + f.populatePredecessor(); + var original = f.owner().capture(request()); + assertThat(original.catalog().catalogEpoch()).isEqualTo(23); + var before = f.rows(f.tables()); + before.remove(f.history); + before.remove(CLASSIFICATIONS); + before.remove(EPOCHS); + before.remove("game_session_canonical_initial_admission_attempt"); + var history = f.historyRows(false); + var classifications = f.classificationRows(); + String priorEpochs = + "SELECT to_jsonb(e)::text||':'||xmin::text FROM " + + EPOCHS + + " e WHERE catalog_epoch<=23 ORDER BY catalog_epoch"; + var epochs = f.dsl.fetch(priorEpochs).getValues(0, String.class); + + migration(f.source, f.schema, f.history, "1070").migrate(); + + assertThat(f.rows(before.keySet())).isEqualTo(before); + assertThat(f.historyRows(false)).hasSize(history.size() + 1); + assertThat(f.historyRows(false).subList(0, history.size())).isEqualTo(history); + assertThat(f.classificationRows()) + .containsAllEntriesOf(classifications) + .hasSize(classifications.size() + 1); + assertThat(f.dsl.fetch(priorEpochs).getValues(0, String.class)).isEqualTo(epochs); + assertThatThrownBy(() -> f.owner().readExact(original.request())) + .isInstanceOf(GameSessionRuntimeFamilyCatalogRepository.CatalogConflictException.class); + + var current = f.owner().capture(request()); + assertThat(current.catalog().catalogEpoch()).isEqualTo(24); + assertThat(current.catalog().families()) + .anyMatch( + item -> item.familyId().equals("game_session_run_owned_fixture_runtime_completion")); + assertThat(f.count("game_session_run_owned_fixture_runtime_completion")).isZero(); + assertThat(f.owner().readExact(current.request())).isEqualTo(current); + migration(f.source, f.schema, f.history, "1070").validate(); + } + } + @Test void historicalFinalObservationUpgradePreservesPopulatedV1065Point1AndSealsEpoch18() { try (Fixture f = fixture("1065.1")) { diff --git a/services/game-session-service/src/test/java/integration/net/firedevops/firemud/gamesession/repository/GameplayCommandRepositoryIntegrationTest.java b/services/game-session-service/src/test/java/integration/net/firedevops/firemud/gamesession/repository/GameplayCommandRepositoryIntegrationTest.java index ca1ca93f47..6d0586c940 100644 --- a/services/game-session-service/src/test/java/integration/net/firedevops/firemud/gamesession/repository/GameplayCommandRepositoryIntegrationTest.java +++ b/services/game-session-service/src/test/java/integration/net/firedevops/firemud/gamesession/repository/GameplayCommandRepositoryIntegrationTest.java @@ -51,6 +51,10 @@ class GameplayCommandRepositoryIntegrationTest { "game_session_canonical_human_runtime_completion"; private static final String HUMAN_RUNTIME_COMPLETION_TRUNCATE_GUARD = "game_session_canonical_human_runtime_completion_no_truncate"; + private static final String FIXTURE_RUNTIME_COMPLETION_TABLE = + "game_session_run_owned_fixture_runtime_completion"; + private static final String FIXTURE_RUNTIME_COMPLETION_TRUNCATE_GUARD = + "gs_run_owned_fixture_runtime_completion_no_truncate"; @Container static PostgreSQLContainer postgres = @@ -91,6 +95,10 @@ void setUpRepository() { void cleanTable() { String originalGuardState = humanRuntimeCompletionTruncateGuardState(); assertThat(originalGuardState).isIn("O", "A"); + String originalFixtureGuardState = + truncateGuardState( + FIXTURE_RUNTIME_COMPLETION_TABLE, FIXTURE_RUNTIME_COMPLETION_TRUNCATE_GUARD); + assertThat(originalFixtureGuardState).isIn("O", "A"); transactionTemplate.executeWithoutResult( status -> { @@ -100,15 +108,30 @@ void cleanTable() { + " DISABLE TRIGGER " + HUMAN_RUNTIME_COMPLETION_TRUNCATE_GUARD); assertThat(humanRuntimeCompletionTruncateGuardState()).isEqualTo("D"); + dsl.execute( + "ALTER TABLE " + + FIXTURE_RUNTIME_COMPLETION_TABLE + + " DISABLE TRIGGER " + + FIXTURE_RUNTIME_COMPLETION_TRUNCATE_GUARD); dsl.execute( "TRUNCATE TABLE gameplay_command, gameplay_admission_pointer, tick_batch, tick_effect, " + HUMAN_RUNTIME_COMPLETION_TABLE + + ", " + + FIXTURE_RUNTIME_COMPLETION_TABLE + " RESTART IDENTITY CASCADE"); restoreHumanRuntimeCompletionTruncateGuard(originalGuardState); + restoreTruncateGuard( + FIXTURE_RUNTIME_COMPLETION_TABLE, + FIXTURE_RUNTIME_COMPLETION_TRUNCATE_GUARD, + originalFixtureGuardState); assertThat(humanRuntimeCompletionTruncateGuardState()).isEqualTo(originalGuardState); }); assertThat(humanRuntimeCompletionTruncateGuardState()).isEqualTo(originalGuardState); + assertThat( + truncateGuardState( + FIXTURE_RUNTIME_COMPLETION_TABLE, FIXTURE_RUNTIME_COMPLETION_TRUNCATE_GUARD)) + .isEqualTo(originalFixtureGuardState); } @Test @@ -172,14 +195,19 @@ void cleanTableClearsFixedTickBatchAndEffectIdsForReuse() { } private String humanRuntimeCompletionTruncateGuardState() { + return truncateGuardState( + HUMAN_RUNTIME_COMPLETION_TABLE, HUMAN_RUNTIME_COMPLETION_TRUNCATE_GUARD); + } + + private String truncateGuardState(String table, String trigger) { List states = dsl .fetch( "SELECT tgenabled::text FROM pg_trigger " + "WHERE tgrelid = CAST(? AS regclass) AND tgname = CAST(? AS name) " + "AND NOT tgisinternal", - HUMAN_RUNTIME_COMPLETION_TABLE, - HUMAN_RUNTIME_COMPLETION_TRUNCATE_GUARD) + table, + trigger) .stream() .map(record -> record.get(0, String.class)) .toList(); @@ -188,19 +216,18 @@ private String humanRuntimeCompletionTruncateGuardState() { } private void restoreHumanRuntimeCompletionTruncateGuard(String state) { + restoreTruncateGuard( + HUMAN_RUNTIME_COMPLETION_TABLE, HUMAN_RUNTIME_COMPLETION_TRUNCATE_GUARD, state); + } + + private void restoreTruncateGuard(String table, String trigger, String state) { String enableMode = switch (state) { case "O" -> "ENABLE"; case "A" -> "ENABLE ALWAYS"; default -> throw new IllegalArgumentException("Unsupported enabled trigger state"); }; - dsl.execute( - "ALTER TABLE " - + HUMAN_RUNTIME_COMPLETION_TABLE - + " " - + enableMode - + " TRIGGER " - + HUMAN_RUNTIME_COMPLETION_TRUNCATE_GUARD); + dsl.execute("ALTER TABLE " + table + " " + enableMode + " TRIGGER " + trigger); } @Test diff --git a/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/data/RunOwnedCanonicalLaunchPreparationOwnerTest.java b/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/data/RunOwnedCanonicalLaunchPreparationOwnerTest.java index 7e4d15a63e..603fa7b695 100644 --- a/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/data/RunOwnedCanonicalLaunchPreparationOwnerTest.java +++ b/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/data/RunOwnedCanonicalLaunchPreparationOwnerTest.java @@ -386,7 +386,7 @@ private static RunOwnedInitialAdmissionFixtureCapability capability() { true, false, "SHARED", - "ALLOW_NEW", + "PRESEEDED_ONLY", "a".repeat(64), RunOwnedInitialAdmissionFixtureCapability.GAME_SESSION_URI_SAN, "b".repeat(64), diff --git a/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/data/RunOwnedInitialAdmissionFixtureCapabilityTest.java b/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/data/RunOwnedInitialAdmissionFixtureCapabilityTest.java index 9226864629..5b26a36770 100644 --- a/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/data/RunOwnedInitialAdmissionFixtureCapabilityTest.java +++ b/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/data/RunOwnedInitialAdmissionFixtureCapabilityTest.java @@ -78,7 +78,7 @@ void parsesExactCapabilityAndBindsRunProjectSelectorsAndTlsPins() { assertThat(capability.publicProductionRealm()).isTrue(); assertThat(capability.requiresCharacterSelection()).isFalse(); assertThat(capability.stateScope()).isEqualTo("SHARED"); - assertThat(capability.characterCreationPolicy()).isEqualTo("ALLOW_NEW"); + assertThat(capability.characterCreationPolicy()).isEqualTo("PRESEEDED_ONLY"); assertThat(capability.worldManagementUriSan()) .isEqualTo(RunOwnedInitialAdmissionFixtureCapability.WORLD_MANAGEMENT_URI_SAN); assertThat(capability.worldManagementLeafSha256()).isEqualTo(WORLD_LEAF_SHA); @@ -842,7 +842,7 @@ private static String validJson() { "publicProductionRealm": true,%n\ "requiresCharacterSelection": false,%n\ "stateScope": "SHARED",%n\ - "characterCreationPolicy": "ALLOW_NEW",%n\ + "characterCreationPolicy": "PRESEEDED_ONLY",%n\ "gameSessionLeafSha256": "%s",%n\ "gameSessionUriSan": "%s",%n\ "caCertificateSha256": "%s",%n\ diff --git a/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/data/RunOwnedInitialAdmissionFixtureCoordinatorTest.java b/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/data/RunOwnedInitialAdmissionFixtureCoordinatorTest.java deleted file mode 100644 index c7dcb6a6c0..0000000000 --- a/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/data/RunOwnedInitialAdmissionFixtureCoordinatorTest.java +++ /dev/null @@ -1,1170 +0,0 @@ -package net.firedevops.firemud.gamesession.data; - -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.anyLong; -import static org.mockito.ArgumentMatchers.anyString; -import static org.mockito.ArgumentMatchers.eq; -import static org.mockito.Mockito.doAnswer; -import static org.mockito.Mockito.doThrow; -import static org.mockito.Mockito.inOrder; -import static org.mockito.Mockito.mockStatic; -import static org.mockito.Mockito.never; -import static org.mockito.Mockito.same; -import static org.mockito.Mockito.times; -import static org.mockito.Mockito.verify; -import static org.mockito.Mockito.verifyNoInteractions; -import static org.mockito.Mockito.when; - -import java.nio.file.Path; -import java.time.Instant; -import java.util.UUID; -import java.util.concurrent.atomic.AtomicInteger; -import java.util.concurrent.atomic.AtomicReference; -import net.firedevops.firemud.common.gamedesign.AuthoredWorldLaunchDescriptorEvidence; -import net.firedevops.firemud.common.gamedesign.AuthoredWorldLaunchDescriptorGrpcCodec; -import net.firedevops.firemud.common.grpc.CommonGrpcClientProperties; -import net.firedevops.firemud.common.smoke.RunOwnedInitialAdmissionFixtureWireCodec; -import net.firedevops.firemud.common.tenant.AuthoredWorldSourceDigest; -import net.firedevops.firemud.common.tenant.AuthoredWorldSourceEvidence; -import net.firedevops.firemud.common.tenant.FreshTenantCreationEvidence; -import net.firedevops.firemud.common.tenant.GameTenantCreationDigest; -import net.firedevops.firemud.entitymanagement.v1.PlayableStateScope; -import net.firedevops.firemud.gamesession.client.WorldManagementClient; -import net.firedevops.firemud.gamesession.dto.GameInstanceDto; -import net.firedevops.firemud.gamesession.dto.StartSessionRequest; -import net.firedevops.firemud.gamesession.entity.InitialAdmissionBindAttempt; -import net.firedevops.firemud.gamesession.entity.InitialAdmissionBindAttempt.Status; -import net.firedevops.firemud.gamesession.entity.InitialAdmissionBindCatalog; -import net.firedevops.firemud.gamesession.service.GameInstanceService; -import net.firedevops.firemud.gamesession.service.InitialAdmissionBindCatalogDescriptor; -import net.firedevops.firemud.gamesession.service.InitialAdmissionBindHoldBinding; -import net.firedevops.firemud.gamesession.service.InitialAdmissionBindOwnerProof; -import net.firedevops.firemud.gamesession.service.InitialAdmissionBindOwnerProof.Outcome; -import net.firedevops.firemud.gamesession.service.InitialAdmissionBindOwnerService; -import net.firedevops.firemud.gamesession.service.InitialAdmissionBindRequest; -import net.firedevops.firemud.gamesession.service.RunOwnedInitialLaunchResult; -import net.firedevops.firemud.worldmanagement.v1.AcquireInitialAdmissionBindHoldResponse; -import net.firedevops.firemud.worldmanagement.v1.InitialAdmissionBindHold; -import net.firedevops.firemud.worldmanagement.v1.InitialAdmissionBindHoldStatus; -import org.junit.jupiter.api.Test; -import org.junit.jupiter.api.extension.ExtendWith; -import org.mockito.ArgumentCaptor; -import org.mockito.InOrder; -import org.mockito.MockedStatic; -import org.springframework.boot.test.system.CapturedOutput; -import org.springframework.boot.test.system.OutputCaptureExtension; - -@ExtendWith(OutputCaptureExtension.class) -class RunOwnedInitialAdmissionFixtureCoordinatorTest { - private static final String RUN_ID = "compose-smoke-2939"; - private static final String PROJECT_NAME = "firemud-smoke-compose-smoke-2939"; - private static final String CAPABILITY_PATH = "fixture/capability.json"; - private static final String SOURCE_RECEIPT_PATH = "fixture/source-receipt.json"; - private static final String CLAIM_DIGEST = "d".repeat(64); - private static final String GAME_SESSION_LEAF_SHA256 = "a".repeat(64); - private static final String CA_CERTIFICATE_SHA256 = "b".repeat(64); - private static final String WORLD_MANAGEMENT_LEAF_SHA256 = "c".repeat(64); - private static final String OPERATION_ID = - RunOwnedInitialAdmissionFixtureWireCodec.fixtureOperationId( - CLAIM_DIGEST, RUN_ID, PROJECT_NAME, GAME_SESSION_LEAF_SHA256, CA_CERTIFICATE_SHA256) - .toString(); - private static final UUID CREATION_REQUEST_ID = - UUID.fromString("57341fb9-55ee-42f4-842e-6e6305c22411"); - private static final UUID CREATION_OPERATION_ID = - UUID.fromString("d156e17a-d759-4db5-a456-c082b5d74419"); - private static final UUID SOURCE_OPERATION_ID = - UUID.fromString("3f773701-e812-44f5-8ae0-7268d543beed"); - private static final UUID REALM_ID = UUID.fromString("23d39978-9d44-4e1a-8659-998ff9239b01"); - private static final UUID NAMESPACE_ID = UUID.fromString("ed1b4d88-81f8-4404-af7c-9a5dc91d3043"); - private static final UUID HOLD_ID = UUID.fromString("5fdd38a3-09e3-46bb-b11a-e2ff2a096211"); - private static final UUID HOLD_FENCE = UUID.fromString("e385de73-4324-44a8-a815-d0c806b9a0f7"); - private static final UUID ATTEMPT_ID = UUID.fromString("6f39929c-44ee-45c7-9e96-8c6548b84e65"); - - @Test - void commitsOnlyAfterDurableIntentAndExactWorldHoldAndLeavesWorldFinalizationAsync() { - Fixture fixture = - fixture(InitialAdmissionBindHoldStatus.INITIAL_ADMISSION_BIND_HOLD_STATUS_PENDING); - - RunOwnedInitialAdmissionFixtureCoordinator.BootstrapResult result = - fixture.coordinator.coordinate(fixture.capability, fixture.sourceReceipt); - - assertThat(fixture.sourceReceipt.sourceEvidence().registrationRequestId()) - .isEqualTo(UUID.fromString(OPERATION_ID)); - assertThat(fixture.sourceReceipt.sourceEvidence().operationId()) - .isNotEqualTo(fixture.sourceReceipt.sourceEvidence().registrationRequestId()); - assertThat(result) - .isEqualTo(RunOwnedInitialAdmissionFixtureCoordinator.BootstrapResult.COMMITTED); - InOrder order = inOrder(fixture.gameInstanceService, fixture.ownerService, fixture.worldClient); - ArgumentCaptor launchEvidence = - ArgumentCaptor.forClass(RunOwnedInitialAdmissionLaunchEvidence.class); - order - .verify(fixture.gameInstanceService) - .startRunOwnedInitialLaunch(any(), launchEvidence.capture()); - assertThat(launchEvidence.getValue().sourceEvidence()) - .isEqualTo(fixture.sourceReceipt.sourceEvidence()); - assertThat(launchEvidence.getValue().creationEvidence()) - .isEqualTo(fixture.sourceReceipt.creationEvidence()); - assertThat(launchEvidence.getValue().fixturePolicySeal()) - .isEqualTo(fixture.sourceReceipt.fixturePolicySeal()); - assertThat(launchEvidence.getValue().publishedReleaseBundle()) - .isEqualTo(fixture.sourceReceipt.launchReadEvidence().publishedReleaseBundle()); - assertThat(launchEvidence.getValue().launchDescriptor()) - .isEqualTo(fixture.sourceReceipt.launchReadEvidence().launchDescriptor()); - order.verify(fixture.ownerService).registerPublicSharedFixtureCatalog(any()); - order.verify(fixture.ownerService).beginIntent(any()); - order - .verify(fixture.worldClient) - .acquireInitialAdmissionBindHold( - eq(7L), - eq(42L), - eq(11L), - eq(4L), - eq(OPERATION_ID), - anyString(), - eq(REALM_ID), - eq(NAMESPACE_ID), - eq(PlayableStateScope.PLAYABLE_STATE_SCOPE_SHARED), - eq(3L)); - order.verify(fixture.ownerService).attachHold(any()); - order.verify(fixture.ownerService).commit(any()); - verify(fixture.ownerService, never()).abort(any()); - verify(fixture.ownerService, never()).read(any()); - } - - @Test - void unresolvedOwnerProofDoesNotReleaseHoldOrCompensate() { - Fixture fixture = - fixture(InitialAdmissionBindHoldStatus.INITIAL_ADMISSION_BIND_HOLD_STATUS_PENDING); - doAnswer( - invocation -> { - InitialAdmissionBindHoldBinding binding = invocation.getArgument(0); - return proof(binding, Outcome.PENDING, ATTEMPT_ID, null, 0L, null, false); - }) - .when(fixture.ownerService) - .commit(any()); - - assertThatThrownBy( - () -> fixture.coordinator.coordinate(fixture.capability, fixture.sourceReceipt)) - .isInstanceOf(IllegalStateException.class); - - verify(fixture.ownerService, never()).abort(any()); - verify(fixture.ownerService).attachHold(any()); - verify(fixture.ownerService).commit(any()); - } - - @Test - void rejectsMismatchedWorldHoldBeforeAttachingOrCommitting() { - Fixture fixture = - fixture(InitialAdmissionBindHoldStatus.INITIAL_ADMISSION_BIND_HOLD_STATUS_PENDING); - doAnswer( - invocation -> - AcquireInitialAdmissionBindHoldResponse.newBuilder() - .setHold( - hold( - InitialAdmissionBindHoldStatus - .INITIAL_ADMISSION_BIND_HOLD_STATUS_PENDING, - UUID.fromString("49de9f26-f314-40e1-96a7-5655c5e5b16e"), - fixture.request.get().requestDigest())) - .build()) - .when(fixture.worldClient) - .acquireInitialAdmissionBindHold( - anyLong(), - anyLong(), - anyLong(), - anyLong(), - anyString(), - anyString(), - any(UUID.class), - any(UUID.class), - any(PlayableStateScope.class), - anyLong()); - - assertThatThrownBy( - () -> fixture.coordinator.coordinate(fixture.capability, fixture.sourceReceipt)) - .isInstanceOf(IllegalStateException.class); - - verify(fixture.ownerService, never()).attachHold(any()); - verify(fixture.ownerService, never()).commit(any()); - verify(fixture.ownerService, never()).abort(any()); - } - - @Test - void rejectsMalformedWorldHoldIdentityBeforeAttachingOrCommitting() { - Fixture fixture = - fixture(InitialAdmissionBindHoldStatus.INITIAL_ADMISSION_BIND_HOLD_STATUS_PENDING); - doAnswer( - invocation -> { - UUID namespaceId = invocation.getArgument(7); - String requestDigest = invocation.getArgument(5); - return AcquireInitialAdmissionBindHoldResponse.newBuilder() - .setHold( - hold( - InitialAdmissionBindHoldStatus - .INITIAL_ADMISSION_BIND_HOLD_STATUS_PENDING, - namespaceId, - requestDigest) - .toBuilder() - .setHoldFence("not-a-uuid") - .build()) - .build(); - }) - .when(fixture.worldClient) - .acquireInitialAdmissionBindHold( - anyLong(), - anyLong(), - anyLong(), - anyLong(), - anyString(), - anyString(), - any(UUID.class), - any(UUID.class), - any(PlayableStateScope.class), - anyLong()); - - assertThatThrownBy( - () -> fixture.coordinator.coordinate(fixture.capability, fixture.sourceReceipt)) - .isInstanceOf(IllegalStateException.class); - - verify(fixture.ownerService, never()).attachHold(any()); - verify(fixture.ownerService, never()).commit(any()); - verify(fixture.ownerService, never()).abort(any()); - } - - @Test - void rejectsMissingOrNoncanonicalCommittedAuditId() { - for (String auditId : new String[] {null, "031"}) { - Fixture fixture = - fixture(InitialAdmissionBindHoldStatus.INITIAL_ADMISSION_BIND_HOLD_STATUS_PENDING); - doAnswer( - invocation -> { - InitialAdmissionBindHoldBinding binding = invocation.getArgument(0); - return proof( - binding, - Outcome.COMMITTED, - ATTEMPT_ID, - auditId, - 1L, - binding.requestDigest(), - false); - }) - .when(fixture.ownerService) - .commit(any()); - - assertThatThrownBy( - () -> fixture.coordinator.coordinate(fixture.capability, fixture.sourceReceipt)) - .isInstanceOf(IllegalStateException.class); - } - } - - @Test - void terminalWorldAbortUsesExactReadbackWithoutTryingToCommit() { - Fixture fixture = - fixture(InitialAdmissionBindHoldStatus.INITIAL_ADMISSION_BIND_HOLD_STATUS_ABORTED); - when(fixture.ownerService.read(any())) - .thenAnswer( - invocation -> { - InitialAdmissionBindHoldBinding binding = invocation.getArgument(0); - return proof(binding, Outcome.ABORTED, ATTEMPT_ID, null, 0L, null, true); - }); - - assertThat(fixture.coordinator.coordinate(fixture.capability, fixture.sourceReceipt)) - .isEqualTo(RunOwnedInitialAdmissionFixtureCoordinator.BootstrapResult.ABORTED); - - verify(fixture.ownerService).read(any()); - verify(fixture.ownerService, never()).attachHold(any()); - verify(fixture.ownerService, never()).commit(any()); - verify(fixture.ownerService, never()).abort(any()); - } - - @Test - void disabledCoordinatorDoesNotLoadCapabilityOrCallOwners() { - GameInstanceService gameInstanceService = org.mockito.Mockito.mock(GameInstanceService.class); - InitialAdmissionBindOwnerService ownerService = - org.mockito.Mockito.mock(InitialAdmissionBindOwnerService.class); - WorldManagementClient worldClient = org.mockito.Mockito.mock(WorldManagementClient.class); - RunOwnedInitialAdmissionFixtureCoordinator coordinator = - new RunOwnedInitialAdmissionFixtureCoordinator( - false, - "", - "", - "", - "", - new CommonGrpcClientProperties(), - gameInstanceService, - ownerService, - worldClient); - - coordinator.retryRunOwnedFixtureBootstrap(); - - verifyNoInteractions(gameInstanceService, ownerService, worldClient); - } - - @Test - void missingSourceReceiptRejectsBeforeLaunchOrOwnerMutation() { - Fixture fixture = - fixture(InitialAdmissionBindHoldStatus.INITIAL_ADMISSION_BIND_HOLD_STATUS_PENDING); - try (MockedStatic capabilityLoader = - mockStatic(RunOwnedInitialAdmissionFixtureCapability.class)) { - capabilityLoader - .when( - () -> - RunOwnedInitialAdmissionFixtureCapability.load( - any(Path.class), eq(RUN_ID), eq(PROJECT_NAME), same(fixture.grpcProperties))) - .thenReturn(fixture.capability); - capabilityLoader - .when( - () -> - RunOwnedInitialAdmissionFixtureCapability.loadSourceReceipt( - any(Path.class), - eq(RUN_ID), - eq(PROJECT_NAME), - same(fixture.capability), - same(fixture.grpcProperties))) - .thenThrow(RunOwnedInitialAdmissionFixtureCapability.InvalidSourceReceiptException.class); - - fixture.coordinator.retryRunOwnedFixtureBootstrap(); - } - - verifyNoInteractions(fixture.gameInstanceService, fixture.ownerService, fixture.worldClient); - } - - @Test - void changedSourceReceiptAcrossRetriesIsRejectedBeforeSecondLaunch() { - Fixture fixture = - fixture(InitialAdmissionBindHoldStatus.INITIAL_ADMISSION_BIND_HOLD_STATUS_PENDING); - doThrow(new IllegalStateException("stop after initial launch")) - .when(fixture.ownerService) - .registerPublicSharedFixtureCatalog(any()); - var changedReceipt = - sourceReceipt( - fixture.capability, 29L, UUID.fromString("8f38bd13-8198-40f9-9daa-2373de047b1c")); - try (MockedStatic capabilityLoader = - mockStatic(RunOwnedInitialAdmissionFixtureCapability.class)) { - capabilityLoader - .when( - () -> - RunOwnedInitialAdmissionFixtureCapability.load( - any(Path.class), eq(RUN_ID), eq(PROJECT_NAME), same(fixture.grpcProperties))) - .thenReturn(fixture.capability); - capabilityLoader - .when( - () -> - RunOwnedInitialAdmissionFixtureCapability.loadSourceReceipt( - any(Path.class), - eq(RUN_ID), - eq(PROJECT_NAME), - same(fixture.capability), - same(fixture.grpcProperties))) - .thenReturn(fixture.sourceReceipt, changedReceipt); - - fixture.coordinator.retryRunOwnedFixtureBootstrap(); - fixture.coordinator.retryRunOwnedFixtureBootstrap(); - } - - verify(fixture.gameInstanceService, times(1)) - .startRunOwnedInitialLaunch(any(), any(RunOwnedInitialAdmissionLaunchEvidence.class)); - verify(fixture.ownerService, times(1)).registerPublicSharedFixtureCatalog(any()); - verify(fixture.ownerService, never()).beginIntent(any()); - verifyNoInteractions(fixture.worldClient); - } - - @Test - void changedOwnerReadEvidenceAcrossRetriesIsRejectedBeforeSecondLaunch() { - Fixture fixture = - fixture(InitialAdmissionBindHoldStatus.INITIAL_ADMISSION_BIND_HOLD_STATUS_PENDING); - doThrow(new IllegalStateException("stop after initial launch")) - .when(fixture.ownerService) - .registerPublicSharedFixtureCatalog(any()); - var changedReceipt = - withPublishedReleaseBundleRef( - fixture.capability, fixture.sourceReceipt, "owner-release-ref-changed"); - try (MockedStatic capabilityLoader = - mockStatic(RunOwnedInitialAdmissionFixtureCapability.class)) { - capabilityLoader - .when( - () -> - RunOwnedInitialAdmissionFixtureCapability.load( - any(Path.class), eq(RUN_ID), eq(PROJECT_NAME), same(fixture.grpcProperties))) - .thenReturn(fixture.capability); - capabilityLoader - .when( - () -> - RunOwnedInitialAdmissionFixtureCapability.loadSourceReceipt( - any(Path.class), - eq(RUN_ID), - eq(PROJECT_NAME), - same(fixture.capability), - same(fixture.grpcProperties))) - .thenReturn(fixture.sourceReceipt, changedReceipt); - - fixture.coordinator.retryRunOwnedFixtureBootstrap(); - fixture.coordinator.retryRunOwnedFixtureBootstrap(); - } - - verify(fixture.gameInstanceService, times(1)) - .startRunOwnedInitialLaunch(any(), any(RunOwnedInitialAdmissionLaunchEvidence.class)); - verify(fixture.ownerService, times(1)).registerPublicSharedFixtureCatalog(any()); - verify(fixture.ownerService, never()).beginIntent(any()); - verifyNoInteractions(fixture.worldClient); - } - - @Test - void retryLogUsesAllowlistedDiagnosticsAndDoesNotExposeHostileDependencyMessage( - CapturedOutput output) { - Fixture fixture = - fixture(InitialAdmissionBindHoldStatus.INITIAL_ADMISSION_BIND_HOLD_STATUS_PENDING); - String hostileMessage = - "capability-bytes=secret grpc-status-detail=tenant-token raw-pointer=private"; - doThrow(new IllegalStateException(hostileMessage)) - .when(fixture.gameInstanceService) - .startRunOwnedInitialLaunch(any(), any()); - - try (MockedStatic capabilityLoader = - mockStatic(RunOwnedInitialAdmissionFixtureCapability.class)) { - capabilityLoader - .when( - () -> - RunOwnedInitialAdmissionFixtureCapability.load( - any(Path.class), eq(RUN_ID), eq(PROJECT_NAME), same(fixture.grpcProperties))) - .thenReturn(fixture.capability); - capabilityLoader - .when( - () -> - RunOwnedInitialAdmissionFixtureCapability.loadSourceReceipt( - any(Path.class), - eq(RUN_ID), - eq(PROJECT_NAME), - same(fixture.capability), - same(fixture.grpcProperties))) - .thenReturn(fixture.sourceReceipt); - - fixture.coordinator.retryRunOwnedFixtureBootstrap(); - } - - assertThat(output) - .contains("exceptionType=IllegalStateException") - .contains("errorCode=FIXTURE_STATE_UNRESOLVED") - .contains("message=Fixture state remains unresolved.") - .doesNotContain(hostileMessage, "capability-bytes=secret", "tenant-token", "raw-pointer"); - } - - @Test - void exhaustedRetryLogUsesAllowlistedDiagnosticsAndDoesNotExposeHostileDependencyMessage( - CapturedOutput output) { - Fixture fixture = - fixture(InitialAdmissionBindHoldStatus.INITIAL_ADMISSION_BIND_HOLD_STATUS_PENDING); - String hostileMessage = "grpc sensitive details capability bytes that must not appear"; - doThrow(new IllegalStateException(hostileMessage)) - .when(fixture.gameInstanceService) - .startRunOwnedInitialLaunch(any(), any()); - - try (MockedStatic capabilityLoader = - mockStatic(RunOwnedInitialAdmissionFixtureCapability.class)) { - capabilityLoader - .when( - () -> - RunOwnedInitialAdmissionFixtureCapability.load( - any(Path.class), eq(RUN_ID), eq(PROJECT_NAME), same(fixture.grpcProperties))) - .thenReturn(fixture.capability); - capabilityLoader - .when( - () -> - RunOwnedInitialAdmissionFixtureCapability.loadSourceReceipt( - any(Path.class), - eq(RUN_ID), - eq(PROJECT_NAME), - same(fixture.capability), - same(fixture.grpcProperties))) - .thenReturn(fixture.sourceReceipt); - - for (int attempt = 0; attempt < 12; attempt++) { - fixture.coordinator.retryRunOwnedFixtureBootstrap(); - } - } - - assertThat(output) - .contains("did not reach a verified terminal result after the bounded retry budget") - .contains("exceptionType=IllegalStateException") - .contains("errorCode=FIXTURE_STATE_UNRESOLVED") - .contains("message=Fixture state remains unresolved.") - .doesNotContain(hostileMessage, "grpc sensitive details", "capability bytes"); - } - - @Test - void exhaustedRetryBudgetStopsMutationAndFreshCoordinatorReplaysSameClaim() { - Fixture fixture = - fixture(InitialAdmissionBindHoldStatus.INITIAL_ADMISSION_BIND_HOLD_STATUS_PENDING); - AtomicInteger worldAcquisitions = new AtomicInteger(); - doAnswer( - invocation -> { - int acquisition = worldAcquisitions.incrementAndGet(); - if (acquisition <= 12) { - throw new IllegalStateException("Simulated unresolved World response"); - } - String requestDigest = invocation.getArgument(5); - return AcquireInitialAdmissionBindHoldResponse.newBuilder() - .setHold( - hold( - InitialAdmissionBindHoldStatus.INITIAL_ADMISSION_BIND_HOLD_STATUS_PENDING, - NAMESPACE_ID, - requestDigest)) - .build(); - }) - .when(fixture.worldClient) - .acquireInitialAdmissionBindHold( - anyLong(), - anyLong(), - anyLong(), - anyLong(), - anyString(), - anyString(), - any(UUID.class), - any(UUID.class), - any(PlayableStateScope.class), - anyLong()); - - try (MockedStatic capabilityLoader = - mockStatic(RunOwnedInitialAdmissionFixtureCapability.class)) { - capabilityLoader - .when( - () -> - RunOwnedInitialAdmissionFixtureCapability.load( - any(Path.class), eq(RUN_ID), eq(PROJECT_NAME), same(fixture.grpcProperties))) - .thenReturn(fixture.capability); - capabilityLoader - .when( - () -> - RunOwnedInitialAdmissionFixtureCapability.loadSourceReceipt( - any(Path.class), - eq(RUN_ID), - eq(PROJECT_NAME), - same(fixture.capability), - same(fixture.grpcProperties))) - .thenReturn(fixture.sourceReceipt); - - // Orchestration unit proof only; capability TLS and durable cross-service behavior have - // separate proof boundaries. - for (int attempt = 0; attempt < 12; attempt++) { - fixture.coordinator.retryRunOwnedFixtureBootstrap(); - } - - verify(fixture.ownerService, times(12)).beginIntent(any()); - verify(fixture.worldClient, times(12)) - .acquireInitialAdmissionBindHold( - anyLong(), - anyLong(), - anyLong(), - anyLong(), - eq(OPERATION_ID), - anyString(), - eq(REALM_ID), - eq(NAMESPACE_ID), - eq(PlayableStateScope.PLAYABLE_STATE_SCOPE_SHARED), - eq(3L)); - verify(fixture.ownerService, never()).attachHold(any()); - verify(fixture.ownerService, never()).commit(any()); - capabilityLoader.verify( - () -> - RunOwnedInitialAdmissionFixtureCapability.load( - eq(Path.of(CAPABILITY_PATH)), - eq(RUN_ID), - eq(PROJECT_NAME), - same(fixture.grpcProperties)), - times(12)); - - fixture.coordinator.retryRunOwnedFixtureBootstrap(); - fixture.coordinator.retryRunOwnedFixtureBootstrap(); - verify(fixture.ownerService, times(12)).beginIntent(any()); - verify(fixture.worldClient, times(12)) - .acquireInitialAdmissionBindHold( - anyLong(), - anyLong(), - anyLong(), - anyLong(), - anyString(), - anyString(), - any(UUID.class), - any(UUID.class), - any(PlayableStateScope.class), - anyLong()); - capabilityLoader.verify( - () -> - RunOwnedInitialAdmissionFixtureCapability.load( - any(Path.class), anyString(), anyString(), any(CommonGrpcClientProperties.class)), - times(12)); - - RunOwnedInitialAdmissionFixtureCoordinator restarted = newCoordinator(fixture); - restarted.retryRunOwnedFixtureBootstrap(); - - ArgumentCaptor launchRequests = - ArgumentCaptor.forClass(StartSessionRequest.class); - verify(fixture.gameInstanceService, times(13)) - .startRunOwnedInitialLaunch( - launchRequests.capture(), any(RunOwnedInitialAdmissionLaunchEvidence.class)); - assertThat(launchRequests.getAllValues()) - .allSatisfy( - request -> { - assertThat(request.tenantId()).isEqualTo(fixture.capability.tenantId()); - assertThat(request.gameTemplateId()).isEqualTo(fixture.capability.gameTemplateId()); - assertThat(request.ownerAccountId()).isEqualTo(fixture.capability.ownerAccountId()); - assertThat(request.controlPlaneRequestId()).isEqualTo(OPERATION_ID); - }); - ArgumentCaptor ownerRequests = - ArgumentCaptor.forClass(InitialAdmissionBindRequest.class); - verify(fixture.worldClient, times(13)) - .acquireInitialAdmissionBindHold( - anyLong(), - anyLong(), - anyLong(), - anyLong(), - eq(OPERATION_ID), - anyString(), - eq(REALM_ID), - eq(NAMESPACE_ID), - eq(PlayableStateScope.PLAYABLE_STATE_SCOPE_SHARED), - eq(3L)); - verify(fixture.ownerService, times(13)).beginIntent(ownerRequests.capture()); - assertThat(ownerRequests.getAllValues()) - .extracting(InitialAdmissionBindRequest::initialAdmissionRequestId) - .containsOnly(OPERATION_ID); - assertThat(ownerRequests.getAllValues()) - .extracting(InitialAdmissionBindRequest::requestDigest) - .doesNotContainNull() - .containsOnly(ownerRequests.getValue().requestDigest()); - verify(fixture.ownerService).attachHold(any()); - verify(fixture.ownerService).commit(any()); - verify(fixture.ownerService, never()).abort(any()); - - capabilityLoader.verify( - () -> - RunOwnedInitialAdmissionFixtureCapability.load( - eq(Path.of(CAPABILITY_PATH)), - eq(RUN_ID), - eq(PROJECT_NAME), - same(fixture.grpcProperties)), - times(13)); - restarted.retryRunOwnedFixtureBootstrap(); - verify(fixture.ownerService, times(13)).beginIntent(any()); - verify(fixture.ownerService).commit(any()); - } - } - - private static Fixture fixture(InitialAdmissionBindHoldStatus holdStatus) { - GameInstanceService gameInstanceService = org.mockito.Mockito.mock(GameInstanceService.class); - InitialAdmissionBindOwnerService ownerService = - org.mockito.Mockito.mock(InitialAdmissionBindOwnerService.class); - WorldManagementClient worldClient = org.mockito.Mockito.mock(WorldManagementClient.class); - CommonGrpcClientProperties grpc = new CommonGrpcClientProperties(); - grpc.setPlaintext(true); - RunOwnedInitialAdmissionFixtureCapability capability = - new RunOwnedInitialAdmissionFixtureCapability( - RUN_ID, - PROJECT_NAME, - OPERATION_ID, - 7L, - 17L, - 27L, - "demo", - "Demo World", - "production", - "Live Realm", - true, - true, - false, - "SHARED", - "ALLOW_NEW", - GAME_SESSION_LEAF_SHA256, - RunOwnedInitialAdmissionFixtureCapability.GAME_SESSION_URI_SAN, - CA_CERTIFICATE_SHA256, - RunOwnedInitialAdmissionFixtureCapability.WORLD_MANAGEMENT_URI_SAN, - WORLD_MANAGEMENT_LEAF_SHA256, - CLAIM_DIGEST); - RunOwnedInitialAdmissionFixtureCapability.SourceReceipt sourceReceipt = - sourceReceipt(capability, 29L); - GameInstanceDto target = - new GameInstanceDto( - 42L, - 7L, - "v1", - null, - null, - null, - null, - 17L, - "launch-descriptor-1", - 11L, - 13L, - 3L, - "config-1", - null, - 27L, - "RUNNING"); - when(gameInstanceService.startRunOwnedInitialLaunch(any(), any())) - .thenReturn(new RunOwnedInitialLaunchResult(target, 4L)); - - InitialAdmissionBindCatalog catalog = - new InitialAdmissionBindCatalog( - REALM_ID, - 7L, - 17L, - "demo", - "Demo World", - "production", - "Live Realm", - 3L, - NAMESPACE_ID, - true, - true, - false, - "SHARED", - "ALLOW_NEW", - Instant.now()); - when(ownerService.registerPublicSharedFixtureCatalog( - any(InitialAdmissionBindCatalogDescriptor.class))) - .thenReturn(catalog); - - AtomicReference request = new AtomicReference<>(); - when(ownerService.beginIntent(any())) - .thenAnswer( - invocation -> { - InitialAdmissionBindRequest received = invocation.getArgument(0); - request.set(received); - return attempt(received, catalog, null, null, Status.PENDING); - }); - when(worldClient.acquireInitialAdmissionBindHold( - anyLong(), - anyLong(), - anyLong(), - anyLong(), - anyString(), - anyString(), - any(UUID.class), - any(UUID.class), - any(PlayableStateScope.class), - anyLong())) - .thenAnswer( - invocation -> { - InitialAdmissionBindHoldStatus selectedStatus = holdStatus; - UUID namespaceId = invocation.getArgument(7); - String requestDigest = invocation.getArgument(5); - return AcquireInitialAdmissionBindHoldResponse.newBuilder() - .setHold(hold(selectedStatus, namespaceId, requestDigest)) - .build(); - }); - when(ownerService.attachHold(any())) - .thenAnswer( - invocation -> { - InitialAdmissionBindHoldBinding binding = invocation.getArgument(0); - return attempt( - request.get(), - catalog, - UUID.fromString(binding.holdId()), - UUID.fromString(binding.holdFence()), - Status.PENDING); - }); - when(ownerService.commit(any())) - .thenAnswer( - invocation -> { - InitialAdmissionBindHoldBinding binding = invocation.getArgument(0); - return proof( - binding, Outcome.COMMITTED, ATTEMPT_ID, "31", 1L, binding.requestDigest(), false); - }); - RunOwnedInitialAdmissionFixtureCoordinator coordinator = - new RunOwnedInitialAdmissionFixtureCoordinator( - true, - CAPABILITY_PATH, - SOURCE_RECEIPT_PATH, - RUN_ID, - PROJECT_NAME, - grpc, - gameInstanceService, - ownerService, - worldClient); - return new Fixture( - coordinator, - capability, - sourceReceipt, - grpc, - gameInstanceService, - ownerService, - worldClient, - request); - } - - private static RunOwnedInitialAdmissionFixtureCoordinator newCoordinator(Fixture fixture) { - return new RunOwnedInitialAdmissionFixtureCoordinator( - true, - CAPABILITY_PATH, - SOURCE_RECEIPT_PATH, - RUN_ID, - PROJECT_NAME, - fixture.grpcProperties, - fixture.gameInstanceService, - fixture.ownerService, - fixture.worldClient); - } - - private static InitialAdmissionBindAttempt attempt( - InitialAdmissionBindRequest request, - InitialAdmissionBindCatalog catalog, - UUID holdId, - UUID holdFence, - Status status) { - Instant now = Instant.now(); - return new InitialAdmissionBindAttempt( - ATTEMPT_ID, - request.tenantId(), - request.initialAdmissionRequestId(), - request.requestDigest(), - catalog.realmId(), - catalog.playableStateNamespaceId(), - "SHARED", - true, - catalog.catalogRevision(), - request.gameInstanceId(), - request.versionId(), - request.activeLifecycleEpoch(), - holdId, - holdFence, - status, - status == Status.COMMITTED ? 1L : null, - status == Status.COMMITTED ? 31L : null, - now, - now, - status == Status.PENDING ? null : now); - } - - private static RunOwnedInitialAdmissionFixtureCapability.SourceReceipt sourceReceipt( - RunOwnedInitialAdmissionFixtureCapability capability, long sourceGameRowId) { - return sourceReceipt(capability, sourceGameRowId, SOURCE_OPERATION_ID); - } - - private static RunOwnedInitialAdmissionFixtureCapability.SourceReceipt sourceReceipt( - RunOwnedInitialAdmissionFixtureCapability capability, - long sourceGameRowId, - UUID operationId) { - UUID registrationRequestId = UUID.fromString(capability.operationId()); - UUID canonicalTenantId = UUID.fromString("9db3ab6f-cc09-49d2-8f93-84484397a120"); - String targetNamespace = RunOwnedInitialAdmissionFixtureCapability.SOURCE_TARGET_NAMESPACE; - String tenantSlug = "fixture-tenant"; - String worldSlug = capability.worldSlug(); - String worldDisplayName = capability.worldDisplayName(); - String sourceGameTenantKey = Long.toString(capability.tenantId()); - String provenanceKind = "NEW_GAME_ROW"; - String requestDigest = - AuthoredWorldSourceDigest.requestDigest( - targetNamespace, - registrationRequestId, - canonicalTenantId, - tenantSlug, - worldSlug, - worldDisplayName); - AuthoredWorldSourceEvidence evidence = - new AuthoredWorldSourceEvidence( - 1, - targetNamespace, - registrationRequestId, - operationId, - requestDigest, - canonicalTenantId, - tenantSlug, - worldSlug, - worldDisplayName, - sourceGameRowId, - sourceGameTenantKey, - provenanceKind, - AuthoredWorldSourceDigest.evidenceDigest( - targetNamespace, - registrationRequestId, - operationId, - requestDigest, - canonicalTenantId, - tenantSlug, - worldSlug, - worldDisplayName, - sourceGameRowId, - sourceGameTenantKey, - provenanceKind)); - var launchRead = launchReadEvidence(capability, evidence); - String creationRequestDigest = - GameTenantCreationDigest.requestDigest( - targetNamespace, CREATION_REQUEST_ID, sourceGameTenantKey, worldDisplayName, null); - FreshTenantCreationEvidence creationEvidence = - new FreshTenantCreationEvidence( - 1, - targetNamespace, - CREATION_REQUEST_ID, - CREATION_OPERATION_ID, - creationRequestDigest, - canonicalTenantId, - sourceGameRowId, - sourceGameTenantKey, - provenanceKind, - GameTenantCreationDigest.evidenceDigest( - targetNamespace, - CREATION_REQUEST_ID, - CREATION_OPERATION_ID, - creationRequestDigest, - canonicalTenantId, - sourceGameRowId, - sourceGameTenantKey, - provenanceKind)); - var policySeal = fixturePolicySeal(capability, creationEvidence, evidence, launchRead); - return new RunOwnedInitialAdmissionFixtureCapability.SourceReceipt( - RunOwnedInitialAdmissionFixtureCapability.SOURCE_RECEIPT_SCHEMA, - capability.runId(), - capability.composeProjectName(), - capability.operationId(), - RunOwnedInitialAdmissionFixtureCapability.SOURCE_RECEIPT_OWNER_SERVICE, - capability.gameSessionUriSan(), - capability.gameSessionLeafSha256(), - capability.caCertificateSha256(), - capability.worldManagementUriSan(), - capability.worldManagementLeafSha256(), - evidence, - launchRead, - creationEvidence, - policySeal); - } - - private static RunOwnedInitialAdmissionFixtureCapability.SourceReceipt - withPublishedReleaseBundleRef( - RunOwnedInitialAdmissionFixtureCapability capability, - RunOwnedInitialAdmissionFixtureCapability.SourceReceipt receipt, - String bundleRef) { - var original = receipt.launchReadEvidence(); - var changedBundle = - original.publishedReleaseBundle().toBuilder() - .setPublishedReleaseBundleRef(bundleRef) - .build(); - var changedReadEvidence = - new RunOwnedInitialAdmissionFixtureCapability.LaunchReadEvidence( - original.schema(), - original.gameTemplateId(), - changedBundle, - original.versionAssetArtifactState(), - original.versionState(), - launchDescriptor( - receipt.sourceEvidence(), - changedBundle, - original.versionState(), - original.gameTemplateId(), - receipt.fixtureOperationId())); - var changedPolicySeal = - fixturePolicySeal( - capability, receipt.creationEvidence(), receipt.sourceEvidence(), changedReadEvidence); - return new RunOwnedInitialAdmissionFixtureCapability.SourceReceipt( - receipt.schema(), - receipt.runId(), - receipt.composeProjectName(), - receipt.fixtureOperationId(), - receipt.ownerService(), - receipt.gameSessionUriSan(), - receipt.gameSessionLeafSha256(), - receipt.caCertificateSha256(), - receipt.worldManagementUriSan(), - receipt.worldManagementLeafSha256(), - receipt.sourceEvidence(), - changedReadEvidence, - receipt.creationEvidence(), - changedPolicySeal); - } - - private static RunOwnedInitialAdmissionFixtureWireCodec.FixturePolicySeal fixturePolicySeal( - RunOwnedInitialAdmissionFixtureCapability capability, - FreshTenantCreationEvidence creationEvidence, - AuthoredWorldSourceEvidence sourceEvidence, - RunOwnedInitialAdmissionFixtureCapability.LaunchReadEvidence launchReadEvidence) { - var wireLaunchRead = - new RunOwnedInitialAdmissionFixtureWireCodec.LaunchReadEvidence( - launchReadEvidence.schema(), - launchReadEvidence.gameTemplateId(), - launchReadEvidence.publishedReleaseBundle(), - launchReadEvidence.versionAssetArtifactState(), - launchReadEvidence.versionState(), - launchReadEvidence.launchDescriptor()); - String requestDigest = - RunOwnedInitialAdmissionFixtureWireCodec.fixturePolicyRequestDigest( - RunOwnedInitialAdmissionFixtureCapability.toWireCapability(capability), - creationEvidence, - sourceEvidence, - wireLaunchRead); - UUID fixtureOperationId = UUID.fromString(capability.operationId()); - return new RunOwnedInitialAdmissionFixtureWireCodec.FixturePolicySeal( - RunOwnedInitialAdmissionFixtureWireCodec.FIXTURE_POLICY_SEAL_SCHEMA, - RunOwnedInitialAdmissionFixtureCapability.SOURCE_RECEIPT_OWNER_SERVICE, - fixtureOperationId, - requestDigest, - RunOwnedInitialAdmissionFixtureWireCodec.fixturePolicyEvidenceDigest( - fixtureOperationId, requestDigest)); - } - - private static RunOwnedInitialAdmissionFixtureCapability.LaunchReadEvidence launchReadEvidence( - RunOwnedInitialAdmissionFixtureCapability capability, - AuthoredWorldSourceEvidence sourceEvidence) { - String manifestHash = "sha256:" + "a".repeat(64); - String artifactDigest = "sha256:" + "b".repeat(64); - var bundle = - net.firedevops.firemud.gamedesign.v1.PublishedReleaseBundle.newBuilder() - .setId(77L) - .setVersionId(11L) - .setVersionNumber(1) - .setAttestationSchemaVersion("v1") - .setPublishWorkflowId("publish-11") - .setManifestHash(manifestHash) - .addRequiredManifestAssetKeys("manifest.json") - .setGenerationConfigRevision("genrev-11") - .setPublishedAt("2026-04-15T10:00:00") - .setPublishedReleaseBundleRef("owner-release-ref-11") - .setCanonicalTenantId(sourceEvidence.canonicalTenantId().toString()) - .setCanonicalVersionId("10000000-0000-4000-8000-000000000011") - .setManifestSchemaVersion(1) - .addArtifactDigests( - net.firedevops.firemud.gamedesign.v1.PublishedArtifactDigest.newBuilder() - .setUsageKey("manifest.json") - .setArtifactKind("manifest") - .setImmutableObjectKey( - "artifacts/sha256/" + artifactDigest.substring("sha256:".length())) - .setContentDigest(artifactDigest) - .setContentType("application/json") - .setArtifactSchemaVersion(1) - .build()) - .build(); - var artifactState = - net.firedevops.firemud.gamedesign.v1.VersionAssetArtifactState.newBuilder() - .setTenantId(Long.toString(capability.tenantId())) - .setVersionId(11L) - .setArtifactState( - net.firedevops.firemud.gamedesign.v1.ArtifactState.ARTIFACT_STATE_PUBLISHED) - .setStateEpoch(2L) - .setManifestHash(manifestHash) - .setUpdatedAt("2026-04-15T10:00:00") - .addExportedManifestAssetKeys("manifest.json") - .setExportedVersionNumber(1) - .build(); - var versionState = - net.firedevops.firemud.gamedesign.v1.VersionStateSnapshot.newBuilder() - .setTenantId(Long.toString(capability.tenantId())) - .setVersionId(11L) - .setVersionState( - net.firedevops.firemud.gamedesign.v1.VersionLifecycleState - .VERSION_LIFECYCLE_STATE_PUBLISHED) - .setVersionStateEpoch(77L) - .setUpdatedAt("2026-04-15T10:00:00") - .build(); - return new RunOwnedInitialAdmissionFixtureCapability.LaunchReadEvidence( - RunOwnedInitialAdmissionLaunchEvidence.SCHEMA, - capability.gameTemplateId(), - bundle, - artifactState, - versionState, - launchDescriptor( - sourceEvidence, - bundle, - versionState, - capability.gameTemplateId(), - capability.operationId())); - } - - private static net.firedevops.firemud.gamedesign.v1.LaunchDescriptor launchDescriptor( - AuthoredWorldSourceEvidence sourceEvidence, - net.firedevops.firemud.gamedesign.v1.PublishedReleaseBundle bundle, - net.firedevops.firemud.gamedesign.v1.VersionStateSnapshot versionState, - long gameTemplateId, - String controlPlaneRequestId) { - var request = - new AuthoredWorldLaunchDescriptorEvidence.Request( - RunOwnedInitialAdmissionFixtureWireCodec.SOURCE_TARGET_NAMESPACE, - controlPlaneRequestId, - sourceEvidence.canonicalTenantId(), - sourceEvidence.worldSlug(), - sourceEvidence.operationId(), - sourceEvidence.evidenceDigest(), - gameTemplateId, - false, - null, - false, - null, - false, - null, - false, - null); - var evidence = - AuthoredWorldLaunchDescriptorEvidence.create( - request, - "launch-descriptor-fixture-11", - bundle.getVersionId(), - false, - null, - "{}", - bundle.getGenerationConfigRevision(), - versionState.getVersionStateEpoch(), - bundle.getId(), - bundle.getPublishedReleaseBundleRef(), - false, - null); - return AuthoredWorldLaunchDescriptorGrpcCodec.toLaunchDescriptorMessage(evidence); - } - - private static InitialAdmissionBindHold hold( - InitialAdmissionBindHoldStatus status, UUID namespaceId, String requestDigest) { - return InitialAdmissionBindHold.newBuilder() - .setHoldId(HOLD_ID.toString()) - .setHoldFence(HOLD_FENCE.toString()) - .setTenantId("7") - .setRealmUuid(REALM_ID.toString()) - .setPlayableStateNamespaceUuid(namespaceId.toString()) - .setPlayableStateScope(PlayableStateScope.PLAYABLE_STATE_SCOPE_SHARED) - .setGameInstanceId("42") - .setVersionId("11") - .setActiveLifecycleEpoch(4L) - .setInitialAdmissionRequestId(OPERATION_ID) - .setRequestDigest(requestDigest) - .setExpectedNoPriorPointer(true) - .setExpectedCatalogRevision(3L) - .setStatus(status) - .build(); - } - - private static InitialAdmissionBindOwnerProof proof( - InitialAdmissionBindHoldBinding binding, - Outcome outcome, - UUID attemptId, - String auditId, - long pointerVersion, - String auditDigest, - boolean futureCommitPrevented) { - return new InitialAdmissionBindOwnerProof( - outcome, - binding.holdId(), - binding.holdFence(), - binding.tenantId(), - binding.realmUuid(), - binding.playableStateNamespaceUuid(), - binding.playableStateScope(), - binding.gameInstanceId(), - binding.versionId(), - binding.activeLifecycleEpoch(), - binding.initialAdmissionRequestId(), - binding.requestDigest(), - binding.expectedNoPriorPointer(), - binding.expectedCatalogRevision(), - attemptId.toString(), - auditId, - pointerVersion, - auditDigest, - futureCommitPrevented); - } - - private record Fixture( - RunOwnedInitialAdmissionFixtureCoordinator coordinator, - RunOwnedInitialAdmissionFixtureCapability capability, - RunOwnedInitialAdmissionFixtureCapability.SourceReceipt sourceReceipt, - CommonGrpcClientProperties grpcProperties, - GameInstanceService gameInstanceService, - InitialAdmissionBindOwnerService ownerService, - WorldManagementClient worldClient, - AtomicReference request) {} -} diff --git a/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/security/CanonicalGameplayRosterOwnerReadInterceptorChainTest.java b/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/security/CanonicalGameplayRosterOwnerReadInterceptorChainTest.java index 9b65717afe..e61442cf4c 100644 --- a/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/security/CanonicalGameplayRosterOwnerReadInterceptorChainTest.java +++ b/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/security/CanonicalGameplayRosterOwnerReadInterceptorChainTest.java @@ -309,7 +309,12 @@ private static AuthTokenInterceptor configuredAuthInterceptor() { CONFIRM_METHOD, METHOD, "game_session.v1.CanonicalGameplayRosterOwnerReadService/GetPreseededActorAssignmentOwnerRead", - "game_session.v1.GameSessionService/AuthorizeStartSession") + "game_session.v1.GameSessionService/AuthorizeStartSession", + "game_session.v1.CanonicalGameplayAdmissionDecisionReadService/ListVisiblePublicProductionAdmissionTargets", + "game_session.v1.CanonicalGameplayAdmissionDecisionReadService/ResolvePublishedRealmAdmissionTarget", + "game_session.v1.CanonicalGameplayAdmissionDecisionReadService/GetOriginalNewNeverAdmittedDecision", + "game_session.v1.CanonicalGameplayAdmissionDecisionReadService/GetCanonicalGameplayAdmissionDecision", + "game_session.v1.CanonicalGameplayAdmissionDecisionReadService/GetPublishedRealmAdmissionOwnerRead") .doesNotContain("game_session.v1.*"); Set publicMethods = Set.copyOf(configured); return new AuthTokenInterceptor( diff --git a/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/security/PreseededActorAssignmentOwnerReadInterceptorChainTest.java b/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/security/PreseededActorAssignmentOwnerReadInterceptorChainTest.java index 380ca1cba5..ab2fdc983e 100644 --- a/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/security/PreseededActorAssignmentOwnerReadInterceptorChainTest.java +++ b/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/security/PreseededActorAssignmentOwnerReadInterceptorChainTest.java @@ -130,7 +130,12 @@ private static AuthTokenInterceptor configuredAuthInterceptor() { "game_session.v1.CanonicalGameplayRosterOwnerReadService/ConfirmCanonicalGameplayRosterRetirementAcknowledgement", "game_session.v1.CanonicalGameplayRosterOwnerReadService/GetCanonicalGameplayRosterOwnerRead", METHOD, - "game_session.v1.GameSessionService/AuthorizeStartSession") + "game_session.v1.GameSessionService/AuthorizeStartSession", + "game_session.v1.CanonicalGameplayAdmissionDecisionReadService/ListVisiblePublicProductionAdmissionTargets", + "game_session.v1.CanonicalGameplayAdmissionDecisionReadService/ResolvePublishedRealmAdmissionTarget", + "game_session.v1.CanonicalGameplayAdmissionDecisionReadService/GetOriginalNewNeverAdmittedDecision", + "game_session.v1.CanonicalGameplayAdmissionDecisionReadService/GetCanonicalGameplayAdmissionDecision", + "game_session.v1.CanonicalGameplayAdmissionDecisionReadService/GetPublishedRealmAdmissionOwnerRead") .doesNotContain("game_session.v1.*"); Set publicMethods = Set.copyOf(configured); return new AuthTokenInterceptor( diff --git a/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/service/impl/AuthenticatedCanonicalInitialAdmissionWorldVerifierTest.java b/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/service/impl/AuthenticatedCanonicalInitialAdmissionWorldVerifierTest.java index 60d514ce31..367fd0e94b 100644 --- a/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/service/impl/AuthenticatedCanonicalInitialAdmissionWorldVerifierTest.java +++ b/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/service/impl/AuthenticatedCanonicalInitialAdmissionWorldVerifierTest.java @@ -281,6 +281,9 @@ private static WorldCanonicalInitialAdmissionHoldState worldState( when(lifecycle.request()).thenReturn(lifecycleRequest); when(lifecycle.lifecycleStatus()).thenReturn(lifecycleStatus); when(lifecycle.lifecycleEpoch()).thenReturn(lifecycleEpoch); + when(state.lifecycleRequest()).thenReturn(lifecycleRequest); + when(state.lifecycleStatus()).thenReturn(lifecycleStatus); + when(state.lifecycleEpoch()).thenReturn(lifecycleEpoch); return state; } diff --git a/services/game-session-service/src/testFixtures/java/net/firedevops/firemud/gamesession/testsupport/GameplayCrossServiceStack.java b/services/game-session-service/src/testFixtures/java/net/firedevops/firemud/gamesession/testsupport/GameplayCrossServiceStack.java index 94341287c7..cf4795e561 100644 --- a/services/game-session-service/src/testFixtures/java/net/firedevops/firemud/gamesession/testsupport/GameplayCrossServiceStack.java +++ b/services/game-session-service/src/testFixtures/java/net/firedevops/firemud/gamesession/testsupport/GameplayCrossServiceStack.java @@ -213,8 +213,8 @@ public long freshGameplayBaseline( jdbc.execute("TRUNCATE TABLE runtime_region_status RESTART IDENTITY"); // This is a disposable Testcontainers baseline reset, not runtime/bootstrap behavior. Keep // the FK descendants explicit and temporarily suspend only the launch-evidence, retained - // actor-core, and Human runtime-completion TRUNCATE guards inside the same transaction; - // production SQL retains all three. + // actor-core, Human and fixture runtime-completion TRUNCATE guards inside the same + // transaction; production SQL retains all four. TransactionTemplate baselineReset = new TransactionTemplate(gameSession.bean(PlatformTransactionManager.class)); BaselineTruncateGuardStates originalGuardStates = @@ -227,16 +227,22 @@ public long freshGameplayBaseline( requireOriginalTruncateGuardState( jdbc, BaselineTruncateGuard.AUTHORED_ACTOR_CORE), requireOriginalTruncateGuardState( - jdbc, BaselineTruncateGuard.HUMAN_RUNTIME_COMPLETION)); + jdbc, BaselineTruncateGuard.HUMAN_RUNTIME_COMPLETION), + requireOriginalTruncateGuardState( + jdbc, BaselineTruncateGuard.FIXTURE_RUNTIME_COMPLETION)); disableTruncateGuard(jdbc, BaselineTruncateGuard.CANONICAL_LAUNCH); requireTruncateGuardState(jdbc, BaselineTruncateGuard.CANONICAL_LAUNCH, "D"); disableTruncateGuard(jdbc, BaselineTruncateGuard.AUTHORED_ACTOR_CORE); requireTruncateGuardState(jdbc, BaselineTruncateGuard.AUTHORED_ACTOR_CORE, "D"); disableTruncateGuard(jdbc, BaselineTruncateGuard.HUMAN_RUNTIME_COMPLETION); requireTruncateGuardState(jdbc, BaselineTruncateGuard.HUMAN_RUNTIME_COMPLETION, "D"); + disableTruncateGuard(jdbc, BaselineTruncateGuard.FIXTURE_RUNTIME_COMPLETION); + requireTruncateGuardState( + jdbc, BaselineTruncateGuard.FIXTURE_RUNTIME_COMPLETION, "D"); jdbc.execute( """ TRUNCATE TABLE + game_session_run_owned_fixture_runtime_completion, game_session_canonical_human_runtime_completion, gs_original_start_session_authored_actor_core_retention, game_session_canonical_closed_admission_pointer_request, @@ -273,6 +279,14 @@ public long freshGameplayBaseline( jdbc, BaselineTruncateGuard.HUMAN_RUNTIME_COMPLETION, originalStates.humanRuntimeCompletion()); + restoreTruncateGuard( + jdbc, + BaselineTruncateGuard.FIXTURE_RUNTIME_COMPLETION, + originalStates.fixtureRuntimeCompletion()); + requireTruncateGuardState( + jdbc, + BaselineTruncateGuard.FIXTURE_RUNTIME_COMPLETION, + originalStates.fixtureRuntimeCompletion()); return originalStates; }); requireTruncateGuardState( @@ -283,6 +297,10 @@ public long freshGameplayBaseline( jdbc, BaselineTruncateGuard.HUMAN_RUNTIME_COMPLETION, originalGuardStates.humanRuntimeCompletion()); + requireTruncateGuardState( + jdbc, + BaselineTruncateGuard.FIXTURE_RUNTIME_COMPLETION, + originalGuardStates.fixtureRuntimeCompletion()); if (characterIds.length > 0) { clearScreenBuffers(tenantId, gameplayInstanceId, characterIds); } @@ -308,7 +326,11 @@ private enum BaselineTruncateGuard { HUMAN_RUNTIME_COMPLETION( "Human runtime completion", "game_session_canonical_human_runtime_completion", - "game_session_canonical_human_runtime_completion_no_truncate"); + "game_session_canonical_human_runtime_completion_no_truncate"), + FIXTURE_RUNTIME_COMPLETION( + "run-owned fixture runtime completion", + "game_session_run_owned_fixture_runtime_completion", + "gs_run_owned_fixture_runtime_completion_no_truncate"); private final String description; private final String tableName; @@ -322,7 +344,10 @@ private enum BaselineTruncateGuard { } private record BaselineTruncateGuardStates( - String canonicalLaunch, String authoredActorCore, String humanRuntimeCompletion) {} + String canonicalLaunch, + String authoredActorCore, + String humanRuntimeCompletion, + String fixtureRuntimeCompletion) {} private static String requireOriginalTruncateGuardState( JdbcTemplate jdbc, BaselineTruncateGuard guard) { diff --git a/services/game-session-service/websocket-login-look-smoke.sh b/services/game-session-service/websocket-login-look-smoke.sh index 7546880f74..3bc2a06672 100644 --- a/services/game-session-service/websocket-login-look-smoke.sh +++ b/services/game-session-service/websocket-login-look-smoke.sh @@ -64,7 +64,7 @@ if [[ "$SMOKE_MUTATION_EXTENSION" == "true" ]]; then elif [[ "$SMOKE_WS_FIXTURE_MODE" == true ]]; then echo "Running canonical LOGIN, WORLDS, REALMS, JOIN, PLAY and LOOK over the claimed WebSocket fixture" else - echo "Running direct WebSocket WORLDS + LOGIN + PLAY + LOOK baseline against ${SMOKE_GAME_SESSION_WS_URL}" + echo "Running direct WebSocket WORLDS + LOGIN + fail-closed PLAY baseline against ${SMOKE_GAME_SESSION_WS_URL}" fi echo "Using login credentials (email and password redacted)" echo "Using session='${SMOKE_SESSION_ID}' tenant='${SMOKE_TENANT_ID}'" @@ -83,7 +83,7 @@ from smoke_common import ( PlayEntitlementUnavailable, canonical_fixture_play_steps, gameplay_item_container_equipment_steps, - login_play_look_steps, + websocket_fail_closed_play_steps, run_websocket_smoke_session, verify_smoke_account, wait_for_account_schema, @@ -155,15 +155,12 @@ elif fixture_mode: "check_hostname": True, } else: - steps = login_play_look_steps( + steps = websocket_fail_closed_play_steps( login_email, password, world, worlds_expect, login_expect, - play_expect, - look_expect, - look_timeout=look_timeout_seconds, ) if not fixture_mode: steps += [("LOGOUT", ["OK LOGOUT", "Logged out."], "LOGOUT")] diff --git a/services/world-management-service/src/main/java/net/firedevops/firemud/worldmanagement/config/PreV1RunOwnedFixtureInstallationConfiguration.java b/services/world-management-service/src/main/java/net/firedevops/firemud/worldmanagement/config/PreV1RunOwnedFixtureInstallationConfiguration.java new file mode 100644 index 0000000000..0f4d0f11db --- /dev/null +++ b/services/world-management-service/src/main/java/net/firedevops/firemud/worldmanagement/config/PreV1RunOwnedFixtureInstallationConfiguration.java @@ -0,0 +1,46 @@ +package net.firedevops.firemud.worldmanagement.config; + +import java.nio.file.Path; +import net.firedevops.firemud.common.prev1.PreV1GateWaivers; +import net.firedevops.firemud.worldmanagement.data.PreV1ComposeRuntimeInstallationSource; +import net.firedevops.firemud.worldmanagement.tenant.WorldRuntimeInstallationRegistry; +import org.jooq.DSLContext; +import org.springframework.beans.factory.annotation.Value; +import org.springframework.boot.autoconfigure.condition.ConditionalOnExpression; +import org.springframework.context.annotation.Bean; +import org.springframework.context.annotation.Configuration; +import org.springframework.core.env.Environment; +import org.springframework.transaction.PlatformTransactionManager; + +/** + * Registers the World runtime installation for the canonical run-owned fixture under the pre-v1 + * gate waivers, so the fixture launch can freeze its required owners before PREPARING and ACTIVE. + */ +@Configuration(proxyBeanMethods = false) +@ConditionalOnExpression( + "${FIREMUD_SMOKE_INITIAL_ADMISSION_FIXTURE_ENABLED:false}" + + " and ${firemud.pre-v1.gate-waivers.enabled:false}") +public class PreV1RunOwnedFixtureInstallationConfiguration { + + @Bean + WorldRuntimeInstallationRegistry runOwnedFixtureRuntimeInstallationRegistry( + Environment environment, + DSLContext dsl, + PlatformTransactionManager transactionManager, + @Value("${SERVICE_SCHEMA:public}") String schema, + @Value("${firemud.grpc.workload-namespace:}") String namespace, + @Value( + "${FIREMUD_WORLD_RUNTIME_INSTALLATION_INVENTORY_PATH:" + + "/etc/firemud/world-runtime-installation/inventory.json}") + String inventoryPath) { + if (!PreV1GateWaivers.from(environment).enabled()) { + throw new IllegalStateException("Compose runtime installation requires pre-v1 gate waivers"); + } + return new WorldRuntimeInstallationRegistry( + dsl, + transactionManager, + schema, + namespace, + new PreV1ComposeRuntimeInstallationSource(Path.of(inventoryPath))); + } +} diff --git a/services/world-management-service/src/main/java/net/firedevops/firemud/worldmanagement/config/RunOwnedFixtureInitialAdmissionHoldConfiguration.java b/services/world-management-service/src/main/java/net/firedevops/firemud/worldmanagement/config/RunOwnedFixtureInitialAdmissionHoldConfiguration.java new file mode 100644 index 0000000000..71648a513a --- /dev/null +++ b/services/world-management-service/src/main/java/net/firedevops/firemud/worldmanagement/config/RunOwnedFixtureInitialAdmissionHoldConfiguration.java @@ -0,0 +1,106 @@ +package net.firedevops.firemud.worldmanagement.config; + +import java.io.IOException; +import net.firedevops.firemud.common.config.ServiceEndpointsProperties; +import net.firedevops.firemud.common.grpc.CommonGrpcClientProperties; +import net.firedevops.firemud.common.grpc.GrpcChannelFactory; +import net.firedevops.firemud.common.prev1.PreV1GateWaivers; +import net.firedevops.firemud.worldmanagement.client.GrpcGameSessionCanonicalInitialAdmissionOwnerClient; +import net.firedevops.firemud.worldmanagement.service.RoomService; +import net.firedevops.firemud.worldmanagement.service.impl.RunOwnedFixtureLookWorldGrpcService; +import net.firedevops.firemud.worldmanagement.tenant.WorldAuthoredSourceIntakeRepository; +import net.firedevops.firemud.worldmanagement.tenant.WorldAuthoredVersionIdentityRepository; +import net.firedevops.firemud.worldmanagement.tenant.WorldCanonicalInitialAdmissionHoldGrpcService; +import net.firedevops.firemud.worldmanagement.tenant.WorldCanonicalInitialAdmissionHoldOwner; +import net.firedevops.firemud.worldmanagement.tenant.WorldCanonicalInitialAdmissionHoldRepository; +import net.firedevops.firemud.worldmanagement.tenant.WorldCanonicalInstanceAssociationRepository; +import net.firedevops.firemud.worldmanagement.tenant.WorldCanonicalInstanceLifecycleReadGrpcService; +import net.firedevops.firemud.worldmanagement.tenant.WorldCanonicalInstanceLifecycleReadRepository; +import net.firedevops.firemud.worldmanagement.tenant.WorldCompleteLaunchBindingRepository; +import org.jooq.DSLContext; +import org.springframework.beans.factory.annotation.Value; +import org.springframework.boot.autoconfigure.condition.ConditionalOnProperty; +import org.springframework.context.annotation.Bean; +import org.springframework.context.annotation.Configuration; +import org.springframework.core.env.Environment; +import org.springframework.transaction.PlatformTransactionManager; + +/** + * Registers the canonical initial-admission hold RPC for the run-owned Compose fixture, so Game + * Session can hold the fixture World instance before its first OPEN. Human holds keep their + * existing unregistered composition. + */ +@Configuration(proxyBeanMethods = false) +@ConditionalOnProperty( + name = "FIREMUD_SMOKE_INITIAL_ADMISSION_FIXTURE_ENABLED", + havingValue = "true") +public class RunOwnedFixtureInitialAdmissionHoldConfiguration { + + @Bean(destroyMethod = "close") + GrpcGameSessionCanonicalInitialAdmissionOwnerClient runOwnedFixtureGameSessionOwnerClient( + ServiceEndpointsProperties endpoints, + CommonGrpcClientProperties tlsProperties, + GrpcChannelFactory channelFactory, + @Value("${firemud.grpc.workload-namespace:}") String namespace) + throws IOException { + var client = + new GrpcGameSessionCanonicalInitialAdmissionOwnerClient( + endpoints, tlsProperties, channelFactory, namespace); + client.init(); + return client; + } + + @Bean + WorldCanonicalInstanceAssociationRepository runOwnedFixtureInstanceAssociationRepository( + DSLContext dsl) { + return new WorldCanonicalInstanceAssociationRepository( + dsl, + new WorldCompleteLaunchBindingRepository(dsl), + new WorldAuthoredSourceIntakeRepository(dsl), + new WorldAuthoredVersionIdentityRepository(dsl)); + } + + @Bean + WorldCanonicalInstanceLifecycleReadRepository runOwnedFixtureInstanceLifecycleReadRepository( + DSLContext dsl, + PlatformTransactionManager transactionManager, + WorldCanonicalInstanceAssociationRepository associations) { + return new WorldCanonicalInstanceLifecycleReadRepository(dsl, transactionManager, associations); + } + + /** Game Session's JOIN resolution reads the exact canonical instance lifecycle here. */ + @Bean + WorldCanonicalInstanceLifecycleReadGrpcService runOwnedFixtureInstanceLifecycleReadGrpcService( + WorldCanonicalInstanceLifecycleReadRepository lifecycle, + @Value("${firemud.grpc.workload-namespace:}") String namespace) { + return new WorldCanonicalInstanceLifecycleReadGrpcService(lifecycle, namespace); + } + + @Bean + @ConditionalOnProperty(name = PreV1GateWaivers.PROPERTY, havingValue = "true") + RunOwnedFixtureLookWorldGrpcService runOwnedFixtureLookWorldGrpcService( + WorldCanonicalInstanceLifecycleReadRepository lifecycle, + RoomService rooms, + Environment environment, + @Value("${firemud.grpc.workload-namespace:}") String namespace) { + if (!PreV1GateWaivers.from(environment).enabled()) { + throw new IllegalStateException("Run-owned fixture LOOK requires pre-v1 gate waivers"); + } + return new RunOwnedFixtureLookWorldGrpcService(lifecycle, rooms, namespace); + } + + @Bean + WorldCanonicalInitialAdmissionHoldGrpcService runOwnedFixtureInitialAdmissionHoldGrpcService( + DSLContext dsl, + PlatformTransactionManager transactionManager, + WorldCanonicalInstanceAssociationRepository associations, + WorldCanonicalInstanceLifecycleReadRepository lifecycle, + GrpcGameSessionCanonicalInitialAdmissionOwnerClient gameSessionOwner, + @Value("${firemud.grpc.workload-namespace:}") String namespace) { + var holds = + new WorldCanonicalInitialAdmissionHoldRepository( + dsl, transactionManager, associations, lifecycle); + return new WorldCanonicalInitialAdmissionHoldGrpcService( + new WorldCanonicalInitialAdmissionHoldOwner(holds, gameSessionOwner), namespace); + } +} diff --git a/services/world-management-service/src/main/java/net/firedevops/firemud/worldmanagement/data/PreV1ComposeRuntimeInstallationSource.java b/services/world-management-service/src/main/java/net/firedevops/firemud/worldmanagement/data/PreV1ComposeRuntimeInstallationSource.java new file mode 100644 index 0000000000..8b08ef5f4d --- /dev/null +++ b/services/world-management-service/src/main/java/net/firedevops/firemud/worldmanagement/data/PreV1ComposeRuntimeInstallationSource.java @@ -0,0 +1,56 @@ +package net.firedevops.firemud.worldmanagement.data; + +import java.nio.file.Path; +import java.util.Arrays; +import java.util.Objects; +import net.firedevops.firemud.common.smoke.RunOwnedFixtureImmutableFileReader; +import net.firedevops.firemud.worldmanagement.tenant.WorldRuntimeInstallationRegistry; +import net.firedevops.firemud.worldmanagement.tenant.WorldRuntimeInstallationRegistry.RegistryUnavailableException; + +/** + * Pre-v1 waiver (ADR 0185): Compose has no deployed installation controller, so the run-owned + * fixture reads its runtime installation inventory from a root-owned, read-only file written by the + * smoke wrapper. Holding re-reads the exact bytes; it cannot prevent a root change, which the + * deployed controller must do before v1. Never used under the prod profile. + */ +public final class PreV1ComposeRuntimeInstallationSource + implements WorldRuntimeInstallationRegistry.ProtectedInstallationSource { + private static final int MAX_INVENTORY_BYTES = 64 * 1024; + + private final Path inventoryPath; + + public PreV1ComposeRuntimeInstallationSource(Path inventoryPath) { + this.inventoryPath = Objects.requireNonNull(inventoryPath, "inventoryPath"); + } + + @Override + public WorldRuntimeInstallationRegistry.HeldInstallation acquireCurrent() { + byte[] held = read(); + return new WorldRuntimeInstallationRegistry.HeldInstallation() { + @Override + public byte[] exactArtifactBytes() { + return held.clone(); + } + + @Override + public void requireCurrent() { + if (!Arrays.equals(held, read())) { + throw new RegistryUnavailableException( + "Compose runtime installation inventory changed while held"); + } + } + + @Override + public void close() {} + }; + } + + private byte[] read() { + return RunOwnedFixtureImmutableFileReader.readBoundedImmutableFile( + inventoryPath, + MAX_INVENTORY_BYTES, + () -> + new RegistryUnavailableException( + "Compose runtime installation inventory is missing, writable or oversized")); + } +} diff --git a/services/world-management-service/src/main/java/net/firedevops/firemud/worldmanagement/data/RunOwnedWorldFixedPresetResources.java b/services/world-management-service/src/main/java/net/firedevops/firemud/worldmanagement/data/RunOwnedWorldFixedPresetResources.java index 8fd648bf0b..646bd2fbaa 100644 --- a/services/world-management-service/src/main/java/net/firedevops/firemud/worldmanagement/data/RunOwnedWorldFixedPresetResources.java +++ b/services/world-management-service/src/main/java/net/firedevops/firemud/worldmanagement/data/RunOwnedWorldFixedPresetResources.java @@ -85,6 +85,13 @@ public static Definition definition() { return new Definition(PRESET_ID, REGION, ZONE, List.of(STARTER_ROOM, SECONDARY_ROOM), EXITS); } + /** + * Returns the fixed preset's starter ROOM template identity, never a runtime or legacy row id. + */ + public static UUID starterRoomTemplateId() { + return STARTER_ROOM.templateId(); + } + /** * Builds a complete authorization plan before any World resource write is permitted. * diff --git a/services/world-management-service/src/main/java/net/firedevops/firemud/worldmanagement/service/impl/RunOwnedFixtureLookWorldGrpcService.java b/services/world-management-service/src/main/java/net/firedevops/firemud/worldmanagement/service/impl/RunOwnedFixtureLookWorldGrpcService.java new file mode 100644 index 0000000000..8089dfe595 --- /dev/null +++ b/services/world-management-service/src/main/java/net/firedevops/firemud/worldmanagement/service/impl/RunOwnedFixtureLookWorldGrpcService.java @@ -0,0 +1,99 @@ +package net.firedevops.firemud.worldmanagement.service.impl; + +import io.grpc.Status; +import io.grpc.stub.StreamObserver; +import java.util.Objects; +import net.firedevops.firemud.common.grpc.GrpcPeerIdentity; +import net.firedevops.firemud.common.security.SessionContext; +import net.firedevops.firemud.common.world.WorldCanonicalInstanceLifecycleEvidence; +import net.firedevops.firemud.common.world.WorldCanonicalInstanceLifecycleGrpcCodec; +import net.firedevops.firemud.worldmanagement.service.RoomService; +import net.firedevops.firemud.worldmanagement.tenant.WorldCanonicalInstanceLifecycleReadRepository; +import net.firedevops.firemud.worldmanagement.v1.ReadRunOwnedFixtureLookRoomRequest; +import net.firedevops.firemud.worldmanagement.v1.ReadRunOwnedFixtureLookRoomResponse; +import net.firedevops.firemud.worldmanagement.v1.RunOwnedFixtureLookWorldServiceGrpc; + +/** Reads actual World-owned topology and prose for the active run-owned fixture. */ +public final class RunOwnedFixtureLookWorldGrpcService + extends RunOwnedFixtureLookWorldServiceGrpc.RunOwnedFixtureLookWorldServiceImplBase { + private final WorldCanonicalInstanceLifecycleReadRepository lifecycle; + private final RoomService rooms; + private final String namespace; + + public RunOwnedFixtureLookWorldGrpcService( + WorldCanonicalInstanceLifecycleReadRepository lifecycle, + RoomService rooms, + String namespace) { + this.lifecycle = Objects.requireNonNull(lifecycle); + this.rooms = Objects.requireNonNull(rooms); + if (!GrpcPeerIdentity.isValidNamespace(namespace)) { + throw new IllegalArgumentException("A World workload namespace is required"); + } + this.namespace = namespace; + } + + @Override + public void readRunOwnedFixtureLookRoom( + ReadRunOwnedFixtureLookRoomRequest wire, + StreamObserver observer) { + GrpcPeerIdentity peer = GrpcPeerIdentity.current(); + if (peer == null) { + observer.onError(Status.UNAUTHENTICATED.asRuntimeException()); + return; + } + if (!peer.isService("game-logic-service") + || !peer.isInNamespace(namespace) + || SessionContext.hasAuthenticatedCallerContext() + || SessionContext.isInternalService()) { + observer.onError(Status.PERMISSION_DENIED.asRuntimeException()); + return; + } + + WorldCanonicalInstanceLifecycleEvidence.Request request; + try { + if (!wire.hasLifecycle() + || !wire.getUnknownFields().asMap().isEmpty() + || !wire.getExpectedRoomInstanceKey().matches("R-[1-9][0-9]{0,18}") + || wire.getPreferredLocale().length() > 128) { + throw new IllegalArgumentException("An exact fixture room selector is required"); + } + request = WorldCanonicalInstanceLifecycleGrpcCodec.fromRequest(wire.getLifecycle()); + } catch (IllegalArgumentException invalid) { + observer.onError(Status.INVALID_ARGUMENT.asRuntimeException()); + return; + } + if (!namespace.equals(request.targetNamespace())) { + observer.onError(Status.PERMISSION_DENIED.asRuntimeException()); + return; + } + + ReadRunOwnedFixtureLookRoomResponse response; + try { + var view = + lifecycle.readRunOwnedFixtureStartRoomView( + request, wire.getExpectedRoomInstanceKey(), wire.getPreferredLocale(), rooms); + if (view.isEmpty()) { + observer.onError(Status.NOT_FOUND.asRuntimeException()); + return; + } + var starter = view.orElseThrow(); + String tenant = request.canonicalTenantId().toString(); + String game = request.canonicalGameInstanceId().toString(); + String room = wire.getExpectedRoomInstanceKey(); + response = + ReadRunOwnedFixtureLookRoomResponse.newBuilder() + .setLifecycle( + WorldCanonicalInstanceLifecycleGrpcCodec.toFixtureResponse( + request, starter.lifecycle())) + .setSnapshot( + WorldManagementGrpcService.projectRoomSnapshot( + starter.snapshot(), tenant, game, tenant + ":" + game + ":" + room)) + .build(); + } catch (RuntimeException unavailable) { + observer.onError(Status.UNAVAILABLE.asRuntimeException()); + return; + } + observer.onNext(response); + observer.onCompleted(); + } +} diff --git a/services/world-management-service/src/main/java/net/firedevops/firemud/worldmanagement/service/impl/WorldLifecycleCommandServiceImpl.java b/services/world-management-service/src/main/java/net/firedevops/firemud/worldmanagement/service/impl/WorldLifecycleCommandServiceImpl.java index e0b10ea562..c07499cb5a 100644 --- a/services/world-management-service/src/main/java/net/firedevops/firemud/worldmanagement/service/impl/WorldLifecycleCommandServiceImpl.java +++ b/services/world-management-service/src/main/java/net/firedevops/firemud/worldmanagement/service/impl/WorldLifecycleCommandServiceImpl.java @@ -58,6 +58,7 @@ import net.firedevops.firemud.worldmanagement.tenant.WorldCompleteLaunchBindingRepository; import net.firedevops.firemud.worldmanagement.tenant.WorldDesignPublicationFenceEvidence.OwnerBinding; import net.firedevops.firemud.worldmanagement.tenant.WorldDesignPublicationFenceRepository; +import net.firedevops.firemud.worldmanagement.tenant.WorldRuntimeInstallationRegistry; import org.jooq.DSLContext; import org.slf4j.Logger; import org.springframework.beans.factory.annotation.Autowired; @@ -108,6 +109,7 @@ public class WorldLifecycleCommandServiceImpl implements WorldLifecycleCommandSe private final String workloadNamespace; private volatile RunOwnedWorldFixtureOwners runOwnedWorldFixtureOwners; + private volatile WorldRuntimeInstallationRegistry runtimeInstallationRegistry; private final TransactionOperations fixtureTransactionOperations; private final TransactionOperations prepareTransactionOperations; @@ -480,6 +482,25 @@ private static TransactionTemplate fixtureTransactionTemplate( return transaction; } + /** Present only where a runtime installation source is configured (Compose pre-v1 waiver). */ + @Autowired(required = false) + void setRuntimeInstallationRegistry(WorldRuntimeInstallationRegistry registry) { + this.runtimeInstallationRegistry = registry; + } + + /** + * Freezes the current installation's required owners for the canonical fixture instance and holds + * the installation through the owner's synchronous commit. + */ + private T withFixtureLaunchOwners( + RunOwnedCanonicalWorldLaunchEvidence fixtureEvidence, Supplier owner) { + WorldRuntimeInstallationRegistry registry = runtimeInstallationRegistry; + if (registry == null) throw fixtureEvidenceUnavailable(); + registry.register(); + return registry.withLaunchOwners( + fixtureEvidence.gameSessionAssociation().gameInstanceUuid(), owner); + } + @PostConstruct void initMetrics() { prepareCounter = meterRegistry.counter("world_instance_prepare_total"); @@ -601,25 +622,7 @@ WorldInstanceLifecycleSnapshotDto prepareRunOwnedFixture( throw fixtureEvidenceMismatch(); } prepareCounter.increment(); - WorldInstanceLifecycleSnapshotDto materializedSnapshot = snapshot(materialized); - return new WorldInstanceLifecycleSnapshotDto( - originalGameSessionRequest.tenantId(), - originalGameSessionRequest.gameInstanceId(), - materializedSnapshot.gameTemplateId(), - materializedSnapshot.controlPlaneRequestId(), - materializedSnapshot.launchDescriptorId(), - originalGameSessionRequest.versionId(), - materializedSnapshot.releaseBundleId(), - materializedSnapshot.generationConfigRevision(), - materializedSnapshot.publishedReleaseBundleRef(), - materializedSnapshot.versionStateEpoch(), - materializedSnapshot.lifecycleEpoch(), - materializedSnapshot.status(), - materializedSnapshot.remapSetId(), - materializedSnapshot.workflowId(), - materializedSnapshot.workflowFamily(), - materializedSnapshot.workflowRunId(), - materializedSnapshot.workflowStatus()); + return gameSessionSnapshot(originalGameSessionRequest, snapshot(materialized)); } private T executeFixtureOwnerTransaction(Supplier operation) { @@ -633,6 +636,13 @@ private T executeFixtureOwnerTransaction(Supplier operation) { @Timed(value = "world.prepareInstance") public WorldInstanceLifecycleSnapshotDto prepareWorldInstance( PreparedWorldInstanceRequest request) { + if (canonicalFixtureModeEnabled()) { + validatePrepareRequest(request); + RunOwnedCanonicalWorldLaunchEvidence fixtureEvidence = + runOwnedCanonicalWorldLaunchEvidenceProvider.requireAuthenticatedEvidence(); + return withFixtureLaunchOwners( + fixtureEvidence, () -> prepareRunOwnedFixture(request, fixtureEvidence)); + } if (prepareTransactionOperations == null) return preparePublishedWorldInstance(request); return Objects.requireNonNull( prepareTransactionOperations.execute(status -> preparePublishedWorldInstance(request)), @@ -730,10 +740,137 @@ private WorldInstanceLifecycleSnapshotDto preparePublishedWorldInstance( } @Override - @Transactional @Timed(value = "world.activateInstance") public WorldInstanceLifecycleSnapshotDto activatePreparedWorldInstance( long tenantId, long gameInstanceId, long expectedLifecycleEpoch) { + if (canonicalFixtureModeEnabled()) { + return activateRunOwnedFixture(tenantId, gameInstanceId, expectedLifecycleEpoch); + } + if (prepareTransactionOperations == null) { + return activatePublishedWorldInstance(tenantId, gameInstanceId, expectedLifecycleEpoch); + } + return Objects.requireNonNull( + prepareTransactionOperations.execute( + status -> + activatePublishedWorldInstance(tenantId, gameInstanceId, expectedLifecycleEpoch)), + "Activation transaction returned no World snapshot"); + } + + /** + * Activates the canonical fixture World row addressed by the authenticated Game Session + * allocation. The Game Session keys only select the retained association; the World-private keys, + * original request and preparation binding come from the owner's committed evidence. + */ + WorldInstanceLifecycleSnapshotDto activateRunOwnedFixture( + long tenantId, long gameInstanceId, long expectedLifecycleEpoch) { + requireNoAmbientFixtureReadTransaction(); + return activateRunOwnedFixture( + tenantId, + gameInstanceId, + expectedLifecycleEpoch, + runOwnedCanonicalWorldLaunchEvidenceProvider.requireAuthenticatedEvidence()); + } + + WorldInstanceLifecycleSnapshotDto activateRunOwnedFixture( + long tenantId, + long gameInstanceId, + long expectedLifecycleEpoch, + RunOwnedCanonicalWorldLaunchEvidence fixtureEvidence) { + requireNoAmbientFixtureReadTransaction(); + if (!canonicalFixtureModeEnabled()) throw fixtureWritesUnavailable(); + fixtureEvidence.requireFixedGameSessionPeer(); + fixtureEvidence.requireGameSessionAllocation(tenantId, gameInstanceId); + RunOwnedWorldFixtureOwners owners = requireRunOwnedWorldFixtureOwners(); + WorldCanonicalInstanceAssociation retained = + owners + .associationRepository() + .readOwnerAssociation(fixtureEvidence.gameSessionAssociation().gameInstanceUuid()) + .orElseThrow( + () -> + new IllegalArgumentException( + "WORLD_INSTANCE_NOT_FOUND: run-owned fixture World association is not prepared")); + WorldInstance prepared = + worldInstanceRepository + .findById(retained.worldInstanceId()) + .orElseThrow( + () -> + new IllegalStateException( + "RUN_OWNED_WORLD_INSTANCE_MISSING: fixture World row is missing")); + PreparedWorldInstanceRequest originalGameSessionRequest = + new PreparedWorldInstanceRequest( + tenantId, + gameInstanceId, + prepared.getGameTemplateId(), + prepared.getControlPlaneRequestId(), + prepared.getLaunchDescriptorId(), + fixtureEvidence.launchDescriptor().versionId(), + prepared.getScriptPatchVersion(), + prepared.getRuntimeFlagsJson(), + prepared.getGenerationConfigRevision(), + prepared.getReleaseBundleId(), + prepared.getPublishedReleaseBundleRef(), + prepared.getVersionStateEpoch(), + prepared.getRemapSetId()); + long expectedRowVersion = prepared.getRowVersion(); + boolean transitioned = + withFixtureLaunchOwners( + fixtureEvidence, + () -> + executeFixtureOwnerTransaction( + () -> { + WorldCanonicalInstanceAssociation association = + owners + .associationRepository() + .readRunOwnedFixtureAssociationInActivationTransaction( + fixtureEvidence, originalGameSessionRequest); + return owners + .associationRepository() + .activateRunOwnedFixtureInOwnerTransaction( + association, expectedLifecycleEpoch, expectedRowVersion); + })); + WorldInstance activated = + worldInstanceRepository + .findById(retained.worldInstanceId()) + .orElseThrow( + () -> + new IllegalStateException( + "RUN_OWNED_WORLD_INSTANCE_MISSING: fixture World row is missing")); + if (!STATUS_ACTIVE.equals(activated.getStatus())) throw lifecycleEpochMismatch(); + if (transitioned) { + activateCounter.increment(); + logger.info( + "Activated run-owned fixture world instance worldInstanceId={} lifecycleEpoch={}", + activated.getId(), + activated.getLifecycleEpoch()); + } + return gameSessionSnapshot(originalGameSessionRequest, snapshot(activated)); + } + + private static WorldInstanceLifecycleSnapshotDto gameSessionSnapshot( + PreparedWorldInstanceRequest originalGameSessionRequest, + WorldInstanceLifecycleSnapshotDto worldSnapshot) { + return new WorldInstanceLifecycleSnapshotDto( + originalGameSessionRequest.tenantId(), + originalGameSessionRequest.gameInstanceId(), + worldSnapshot.gameTemplateId(), + worldSnapshot.controlPlaneRequestId(), + worldSnapshot.launchDescriptorId(), + originalGameSessionRequest.versionId(), + worldSnapshot.releaseBundleId(), + worldSnapshot.generationConfigRevision(), + worldSnapshot.publishedReleaseBundleRef(), + worldSnapshot.versionStateEpoch(), + worldSnapshot.lifecycleEpoch(), + worldSnapshot.status(), + worldSnapshot.remapSetId(), + worldSnapshot.workflowId(), + worldSnapshot.workflowFamily(), + worldSnapshot.workflowRunId(), + worldSnapshot.workflowStatus()); + } + + private WorldInstanceLifecycleSnapshotDto activatePublishedWorldInstance( + long tenantId, long gameInstanceId, long expectedLifecycleEpoch) { WorldInstance worldInstance = requireWorldInstance(tenantId, gameInstanceId); if (worldInstance.getRunOwnedFixtureBindingSha256() != null) { if (!fixtureModeEnabled()) throw fixtureEvidenceUnavailable(); diff --git a/services/world-management-service/src/main/java/net/firedevops/firemud/worldmanagement/service/impl/WorldManagementGrpcService.java b/services/world-management-service/src/main/java/net/firedevops/firemud/worldmanagement/service/impl/WorldManagementGrpcService.java index d66a911be9..4e1897248c 100644 --- a/services/world-management-service/src/main/java/net/firedevops/firemud/worldmanagement/service/impl/WorldManagementGrpcService.java +++ b/services/world-management-service/src/main/java/net/firedevops/firemud/worldmanagement/service/impl/WorldManagementGrpcService.java @@ -671,18 +671,28 @@ public void getRoomSnapshot( } private RoomSnapshot toProto(RoomSnapshotDto snapshot) { + return projectRoomSnapshot( + snapshot, + snapshot.tenantId().toString(), + snapshot.gameInstanceId().toString(), + readFence( + snapshot.tenantId(), + snapshot.gameInstanceId(), + RuntimeRoomInstanceIds.canonical(snapshot.roomInstanceRowId()))); + } + + static RoomSnapshot projectRoomSnapshot( + RoomSnapshotDto snapshot, String tenantId, String gameInstanceId, String scopeMarker) { RoomSnapshot.Builder builder = RoomSnapshot.newBuilder(); - String runtimeRoomInstanceId = RuntimeRoomInstanceIds.canonical(snapshot.roomInstanceRowId()); builder - .setRoomInstanceId(runtimeRoomInstanceId) - .setTenantId(snapshot.tenantId().toString()) - .setGameInstanceId(snapshot.gameInstanceId().toString()) - .setWorldSnapshotId( - readFence(snapshot.tenantId(), snapshot.gameInstanceId(), runtimeRoomInstanceId)) + .setRoomInstanceId(RuntimeRoomInstanceIds.canonical(snapshot.roomInstanceRowId())) + .setTenantId(tenantId) + .setGameInstanceId(gameInstanceId) + .setWorldSnapshotId(scopeMarker) .setRoomName(snapshot.roomName()) .setShortDescription(snapshot.shortDescription()) .setLongDescription(snapshot.longDescription()); - snapshot.exits().forEach(exit -> builder.addExits(toProto(exit))); + snapshot.exits().forEach(exit -> builder.addExits(projectRoomExit(exit))); if (snapshot.ambientState() != null) { applyAmbientState(builder, snapshot); } @@ -779,7 +789,7 @@ private WorldInstanceLifecycleStatus toProtoStatus(String status) { }; } - private void applyAmbientState(RoomSnapshot.Builder builder, RoomSnapshotDto snapshot) { + private static void applyAmbientState(RoomSnapshot.Builder builder, RoomSnapshotDto snapshot) { String weather = snapshot.ambientState().get("weather"); if (weather == null || weather.isBlank()) { return; @@ -791,7 +801,7 @@ private void applyAmbientState(RoomSnapshot.Builder builder, RoomSnapshotDto sna .build()); } - private RoomExitSnapshot toProto(RoomExitSnapshotDto exit) { + private static RoomExitSnapshot projectRoomExit(RoomExitSnapshotDto exit) { RoomExitSnapshot.Builder builder = RoomExitSnapshot.newBuilder(); String targetRuntimeRoomInstanceId = RuntimeRoomInstanceIds.canonical(exit.targetRoomInstanceRowId()); diff --git a/services/world-management-service/src/main/java/net/firedevops/firemud/worldmanagement/tenant/WorldCanonicalInitialAdmissionHoldRepository.java b/services/world-management-service/src/main/java/net/firedevops/firemud/worldmanagement/tenant/WorldCanonicalInitialAdmissionHoldRepository.java index 61b41b74de..0baf354560 100644 --- a/services/world-management-service/src/main/java/net/firedevops/firemud/worldmanagement/tenant/WorldCanonicalInitialAdmissionHoldRepository.java +++ b/services/world-management-service/src/main/java/net/firedevops/firemud/worldmanagement/tenant/WorldCanonicalInitialAdmissionHoldRepository.java @@ -17,6 +17,7 @@ import net.firedevops.firemud.common.world.WorldCanonicalInitialAdmissionHoldState; import net.firedevops.firemud.common.world.WorldCanonicalInitialAdmissionHoldState.HoldStatus; import net.firedevops.firemud.common.world.WorldCanonicalInstanceLifecycleEvidence; +import net.firedevops.firemud.common.world.WorldRunOwnedFixtureLifecycleEvidence; import org.jooq.DSLContext; import org.jooq.Record; import org.jooq.exception.DataAccessException; @@ -71,14 +72,11 @@ public HoldIdentity acquire( new InvalidHoldEvidenceException( "Canonical World association is unavailable")); requireAssociationTarget(request, association); - if (association.isRunOwnedFixture()) { - throw new InvalidHoldEvidenceException( - "Run-owned fixture rows cannot acquire canonical initial-admission holds"); - } requireLifecycleRequestAssociation(lifecycleRequest, association); LockedWorldLifecycle lockedLifecycle = lockWorldLifecycleRow(request, association); + PrivateKeys keys = privateKeys(association); - long localTenantKey = association.worldPrepareFields().privateTenantKey(); + long localTenantKey = keys.tenantKey(); Record existing = dsl.fetchOne( "SELECT * FROM initial_admission_bind_hold " @@ -106,17 +104,19 @@ public HoldIdentity acquire( "Canonical World hold requires the exact current ACTIVE lifecycle epoch"); } - WorldCanonicalInstanceLifecycleEvidence lifecycle = - lifecycleRepository - .readForActivationInOwnerTransaction(lifecycleRequest) - .orElseThrow( - () -> - new InvalidHoldEvidenceException( - "Exact canonical World lifecycle evidence is unavailable")); - if (!"ACTIVE".equals(lifecycle.lifecycleStatus()) - || lifecycle.lifecycleEpoch() != request.activeLifecycleEpoch()) { - throw new InvalidHoldEvidenceException( - "Canonical World hold requires the exact current ACTIVE lifecycle evidence"); + if (!association.isRunOwnedFixture()) { + WorldCanonicalInstanceLifecycleEvidence lifecycle = + lifecycleRepository + .readForActivationInOwnerTransaction(lifecycleRequest) + .orElseThrow( + () -> + new InvalidHoldEvidenceException( + "Exact canonical World lifecycle evidence is unavailable")); + if (!"ACTIVE".equals(lifecycle.lifecycleStatus()) + || lifecycle.lifecycleEpoch() != request.activeLifecycleEpoch()) { + throw new InvalidHoldEvidenceException( + "Canonical World hold requires the exact current ACTIVE lifecycle evidence"); + } } Record activeForRealm = @@ -150,8 +150,8 @@ public HoldIdentity acquire( request.realmId(), request.playableStateNamespaceId(), request.playableStateScope(), - association.worldPrepareFields().privateGameInstanceKey(), - association.worldPrepareFields().localVersionKey(), + keys.gameInstanceKey(), + keys.versionKey(), request.activeLifecycleEpoch(), request.initialAdmissionRequestId(), request.initialAdmissionRequestDigest(), @@ -220,6 +220,14 @@ public Optional readState( new InvalidHoldEvidenceException( "Canonical World association is unavailable in the hold snapshot")); requireAssociationTarget(identity.request(), association); + if (association.isRunOwnedFixture()) { + requireLifecycleRequestAssociation(lifecycleRequest, association); + return Optional.of( + WorldCanonicalInitialAdmissionHoldState.runOwnedFixture( + identity, + parseStatus(required(row, "status", String.class)), + fixtureLifecycle(lifecycleRequest, association))); + } WorldCanonicalInstanceLifecycleEvidence lifecycle = lifecycleRepository .readForCurrentLocationInOwnerTransaction(lifecycleRequest) @@ -407,9 +415,86 @@ private static void requireAssociationTarget( } } + private record PrivateKeys(long tenantKey, long gameInstanceKey, long versionKey) {} + + private static PrivateKeys privateKeys(WorldCanonicalInstanceAssociation association) { + if (association.isRunOwnedFixture()) { + var keys = association.runOwnedFixture().worldPrivateKeys(); + return new PrivateKeys(keys.tenantId(), keys.gameInstanceId(), keys.versionId()); + } + var fields = association.worldPrepareFields(); + return new PrivateKeys( + fields.privateTenantKey(), fields.privateGameInstanceKey(), fields.localVersionKey()); + } + + /** Current fixture World lifecycle, read in the caller's owner snapshot. */ + private WorldRunOwnedFixtureLifecycleEvidence fixtureLifecycle( + WorldCanonicalInstanceLifecycleEvidence.Request lifecycleRequest, + WorldCanonicalInstanceAssociation association) { + Record row = + dsl.fetchOne( + "SELECT status,lifecycle_epoch,row_version FROM world_instance WHERE id=?", + association.worldInstanceId()); + if (row == null) { + throw new InvalidHoldEvidenceException( + "Canonical World fixture lifecycle row is unavailable"); + } + var fixture = association.runOwnedFixture(); + return new WorldRunOwnedFixtureLifecycleEvidence( + lifecycleRequest, + fixture.fixtureProvenanceDigest(), + fixture.preparationInputDigest(), + required(row, "status", String.class), + required(row, "lifecycle_epoch", Long.class), + required(row, "row_version", Long.class)); + } + + /** + * A fixture has no Human release attestation: its lifecycle request carries the retained fixture + * descriptor digests and the fixture provenance digest in place of the release attestation. + */ + private void requireFixtureLifecycleRequest( + WorldCanonicalInstanceLifecycleEvidence.Request lifecycleRequest, + WorldCanonicalInstanceAssociation association) { + var identity = association.identity(); + var fixture = association.runOwnedFixture(); + Record descriptor = + dsl.fetchOne( + "SELECT descriptor_request_digest, descriptor_result_digest " + + "FROM world_canonical_instance_association " + + "WHERE canonical_game_instance_id = ? AND canonical_authority_kind = 'RUN_OWNED_FIXTURE'", + identity.canonicalGameInstanceId()); + if (descriptor == null + || !lifecycleRequest.targetNamespace().equals(identity.targetNamespace()) + || !lifecycleRequest.canonicalTenantId().equals(identity.canonicalTenantId()) + || !lifecycleRequest.worldSlug().equals(identity.worldSlug()) + || !lifecycleRequest.canonicalGameInstanceId().equals(identity.canonicalGameInstanceId()) + || !lifecycleRequest.playableStateNamespaceId().equals(identity.playableStateNamespaceId()) + || !lifecycleRequest.playableStateScope().equals(identity.playableStateScope()) + || lifecycleRequest.publicProduction() != identity.publicProduction() + || !lifecycleRequest.controlPlaneRequestId().equals(identity.controlPlaneRequestId()) + || !lifecycleRequest.canonicalVersionId().equals(association.canonicalVersionId()) + || !lifecycleRequest + .expectedDescriptorRequestDigest() + .equals(required(descriptor, "descriptor_request_digest", String.class)) + || !lifecycleRequest + .expectedDescriptorResultDigest() + .equals(required(descriptor, "descriptor_result_digest", String.class)) + || !lifecycleRequest + .expectedReleaseAttestationDigest() + .equals(fixture.fixtureProvenanceDigest())) { + throw new InvalidHoldEvidenceException( + "Lifecycle read request differs from the exact immutable World fixture association"); + } + } + private void requireLifecycleRequestAssociation( WorldCanonicalInstanceLifecycleEvidence.Request lifecycleRequest, WorldCanonicalInstanceAssociation association) { + if (association.isRunOwnedFixture()) { + requireFixtureLifecycleRequest(lifecycleRequest, association); + return; + } var identity = association.identity(); var launch = association.completeLaunchBinding().evidence(); var descriptor = launch.descriptor(); @@ -446,10 +531,10 @@ private LockedWorldLifecycle lockWorldLifecycleRow( throw new InvalidHoldEvidenceException("Canonical World lifecycle row is unavailable"); } var identity = association.identity(); - var prepareFields = association.worldPrepareFields(); - if (required(row, "tenant_id", Long.class) != prepareFields.privateTenantKey() - || required(row, "game_instance_id", Long.class) != prepareFields.privateGameInstanceKey() - || required(row, "version_id", Long.class) != prepareFields.localVersionKey() + PrivateKeys keys = privateKeys(association); + if (required(row, "tenant_id", Long.class) != keys.tenantKey() + || required(row, "game_instance_id", Long.class) != keys.gameInstanceKey() + || required(row, "version_id", Long.class) != keys.versionKey() || !required(row, "canonical_game_instance_id", UUID.class) .equals(identity.canonicalGameInstanceId()) || !required(row, "canonical_target_namespace", String.class) @@ -463,8 +548,9 @@ private LockedWorldLifecycle lockWorldLifecycleRow( || !required(row, "public_production", Boolean.class).equals(identity.publicProduction()) || !required(row, "canonical_realm_id", UUID.class).equals(identity.canonicalRealmId()) || required(row, "catalog_revision", Long.class) != identity.catalogRevision() - || !required(row, "canonical_launch_binding_operation_id", UUID.class) - .equals(association.launchBindingOperationId()) + || (!association.isRunOwnedFixture() + && !required(row, "canonical_launch_binding_operation_id", UUID.class) + .equals(association.launchBindingOperationId())) || !request.canonicalGameInstanceId().equals(identity.canonicalGameInstanceId())) { throw new InvalidHoldEvidenceException( "Locked World lifecycle row differs from the immutable canonical association"); diff --git a/services/world-management-service/src/main/java/net/firedevops/firemud/worldmanagement/tenant/WorldCanonicalInstanceAssociationRepository.java b/services/world-management-service/src/main/java/net/firedevops/firemud/worldmanagement/tenant/WorldCanonicalInstanceAssociationRepository.java index b4cf8a0a06..8b46b5ba14 100644 --- a/services/world-management-service/src/main/java/net/firedevops/firemud/worldmanagement/tenant/WorldCanonicalInstanceAssociationRepository.java +++ b/services/world-management-service/src/main/java/net/firedevops/firemud/worldmanagement/tenant/WorldCanonicalInstanceAssociationRepository.java @@ -968,11 +968,96 @@ public WorldCanonicalInstanceAssociation readRunOwnedFixtureAssociationInActivat return stored; } - /** Fixture activation remains unavailable after PREPARING-only materialization. */ - public void activateRunOwnedFixtureInOwnerTransaction( + /** + * Moves the verified fixture World row from its original PREPARING epoch to ACTIVE. The owner + * retains one immutable activation row per fixture instance; the storage guard admits the exact + * lifecycle CAS only with that row, so a bare SQL update stays refused. An exact retry after a + * lost response returns {@code false} without mutation. + */ + public boolean activateRunOwnedFixtureInOwnerTransaction( WorldCanonicalInstanceAssociation association, long expectedEpoch, long expectedRowVersion) { - throw new IllegalStateException( - "RUN_OWNED_WORLD_ACTIVATION_UNAVAILABLE: fixture activation requires the later canonical lifecycle and hold composition"); + Objects.requireNonNull(association, "association"); + requireWritableActivationTransaction(); + if (!association.isRunOwnedFixture()) { + throw new RegistrationConflictException( + "Run-owned fixture activation cannot adopt a Human canonical World association"); + } + var fixture = association.runOwnedFixture(); + long preparingEpoch = fixture.preparingLifecycleEpoch(); + String bindingSha256 = fixture.preparationInputDigest().substring("sha256:".length()); + Record row = + dsl.fetchOne( + "SELECT status, lifecycle_epoch, row_version, run_owned_fixture_binding_sha256, " + + "run_owned_fixture_preparing_lifecycle_epoch, canonical_game_instance_id, " + + "canonical_authority_kind FROM world_instance WHERE id = ? FOR UPDATE", + association.worldInstanceId()); + if (row == null + || !"RUN_OWNED_FIXTURE".equals(row.get("canonical_authority_kind", String.class)) + || !bindingSha256.equals(row.get("run_owned_fixture_binding_sha256", String.class)) + || !Long.valueOf(preparingEpoch) + .equals(row.get("run_owned_fixture_preparing_lifecycle_epoch", Long.class)) + || !association + .identity() + .canonicalGameInstanceId() + .equals(row.get("canonical_game_instance_id", UUID.class))) { + throw new InvalidAssociationEvidenceException( + "RUN_OWNED_WORLD_ACTIVATION_BINDING_MISMATCH: World row differs from the fixture association"); + } + String status = row.get("status", String.class); + long lifecycleEpoch = row.get("lifecycle_epoch", Long.class); + long rowVersion = row.get("row_version", Long.class); + if ("ACTIVE".equals(status)) { + boolean retained = + dsl.fetchOne( + "SELECT 1 FROM world_run_owned_fixture_activation WHERE world_instance_id = ? " + + "AND canonical_game_instance_id = ? AND fixture_binding_sha256 = ? " + + "AND expected_lifecycle_epoch = ? AND result_lifecycle_epoch = ?", + association.worldInstanceId(), + association.identity().canonicalGameInstanceId(), + bindingSha256, + preparingEpoch, + preparingEpoch + 1L) + != null; + if (!retained + || lifecycleEpoch != preparingEpoch + 1L + || (expectedEpoch != preparingEpoch && expectedEpoch != lifecycleEpoch)) { + throw new IllegalStateException( + "LIFECYCLE_EPOCH_MISMATCH: fixture activation replay differs from the retained activation"); + } + return false; + } + if (!"PREPARING".equals(status) + || lifecycleEpoch != preparingEpoch + || expectedEpoch != preparingEpoch + || rowVersion != expectedRowVersion) { + throw new IllegalStateException( + "LIFECYCLE_EPOCH_MISMATCH: fixture activation requires the original PREPARING epoch"); + } + dsl.execute( + "INSERT INTO world_run_owned_fixture_activation (world_instance_id, " + + "canonical_game_instance_id, fixture_binding_sha256, expected_lifecycle_epoch, " + + "expected_row_version, result_lifecycle_epoch, result_row_version) " + + "VALUES (?, ?, ?, ?, ?, ?, ?)", + association.worldInstanceId(), + association.identity().canonicalGameInstanceId(), + bindingSha256, + preparingEpoch, + rowVersion, + preparingEpoch + 1L, + rowVersion + 1L); + int updated = + dsl.execute( + "UPDATE world_instance SET status = 'ACTIVE', lifecycle_epoch = lifecycle_epoch + 1, " + + "row_version = row_version + 1 WHERE id = ? AND status = 'PREPARING' " + + "AND lifecycle_epoch = ? AND row_version = ?", + association.worldInstanceId(), + preparingEpoch, + rowVersion); + if (updated != 1) { + throw new IllegalStateException( + "LIFECYCLE_EPOCH_MISMATCH: fixture World row changed during activation"); + } + return true; } private static void requireFixtureAssociationMatches( @@ -1377,10 +1462,7 @@ private static void requireStoredFixtureWorldRow( row.get(INSTANCE_FIXTURE_PREPARING_EPOCH, Long.class), fixture.preparingLifecycleEpoch()) || fixture.preparingLifecycleEpoch() != 1L - || !Objects.equals( - row.get(INSTANCE_LIFECYCLE_EPOCH, Long.class), fixture.preparingLifecycleEpoch()) - || !"PREPARING".equals(row.get(INSTANCE_STATUS, String.class)) - || !Objects.equals(row.get("row_version", Long.class), 0L) + || !isPreparingOrActivatedFixtureRow(row, fixture.preparingLifecycleEpoch()) || !Objects.equals( row.get(INSTANCE_CONTROL_PLANE_REQUEST_ID, String.class), identity.controlPlaneRequestId()) @@ -1416,6 +1498,23 @@ private static void requireStoredFixtureWorldRow( } } + /** + * The fixture row is either still at its original PREPARING epoch or was moved once to ACTIVE by + * the activation owner; the storage guard admits that move only with its immutable activation + * row. + */ + private static boolean isPreparingOrActivatedFixtureRow(Record row, long preparingEpoch) { + String status = row.get(INSTANCE_STATUS, String.class); + Long lifecycleEpoch = row.get(INSTANCE_LIFECYCLE_EPOCH, Long.class); + Long rowVersion = row.get("row_version", Long.class); + return ("PREPARING".equals(status) + && Objects.equals(lifecycleEpoch, preparingEpoch) + && Objects.equals(rowVersion, 0L)) + || ("ACTIVE".equals(status) + && Objects.equals(lifecycleEpoch, preparingEpoch + 1L) + && Objects.equals(rowVersion, 1L)); + } + private void requireInsertBornFixtureIdentity( Record row, long worldInstanceId, diff --git a/services/world-management-service/src/main/java/net/firedevops/firemud/worldmanagement/tenant/WorldCanonicalInstanceLifecycleReadGrpcService.java b/services/world-management-service/src/main/java/net/firedevops/firemud/worldmanagement/tenant/WorldCanonicalInstanceLifecycleReadGrpcService.java index 54f0d54731..1e9bbd3742 100644 --- a/services/world-management-service/src/main/java/net/firedevops/firemud/worldmanagement/tenant/WorldCanonicalInstanceLifecycleReadGrpcService.java +++ b/services/world-management-service/src/main/java/net/firedevops/firemud/worldmanagement/tenant/WorldCanonicalInstanceLifecycleReadGrpcService.java @@ -7,6 +7,8 @@ import net.firedevops.firemud.common.security.SessionContext; import net.firedevops.firemud.common.world.WorldCanonicalInstanceLifecycleEvidence; import net.firedevops.firemud.common.world.WorldCanonicalInstanceLifecycleGrpcCodec; +import net.firedevops.firemud.worldmanagement.v1.ReadRunOwnedFixtureStartRoomRequest; +import net.firedevops.firemud.worldmanagement.v1.ReadRunOwnedFixtureStartRoomResponse; import net.firedevops.firemud.worldmanagement.v1.ReadWorldCanonicalInstanceLifecycleRequest; import net.firedevops.firemud.worldmanagement.v1.ReadWorldCanonicalInstanceLifecycleResponse; import net.firedevops.firemud.worldmanagement.v1.WorldCanonicalInstanceLifecycleReadServiceGrpc; @@ -69,6 +71,15 @@ public void readWorldCanonicalInstanceLifecycle( WorldCanonicalInstanceLifecycleEvidence evidence; try { evidence = repository.read(readRequest).orElse(null); + if (evidence == null) { + var fixture = repository.readRunOwnedFixture(readRequest).orElse(null); + if (fixture != null) { + responseObserver.onNext( + WorldCanonicalInstanceLifecycleGrpcCodec.toFixtureResponse(readRequest, fixture)); + responseObserver.onCompleted(); + return; + } + } } catch ( WorldCanonicalInstanceLifecycleReadRepository.InvalidLifecycleEvidenceException inconsistent) { @@ -124,6 +135,58 @@ public void readWorldCanonicalInstanceLifecycle( responseObserver.onCompleted(); } + @Override + public void readRunOwnedFixtureStartRoom( + ReadRunOwnedFixtureStartRoomRequest request, + StreamObserver observer) { + if (!requireAuthenticatedGameSessionPeer(observer)) return; + if (TransactionSynchronizationManager.isActualTransactionActive() + || TransactionSynchronizationManager.isSynchronizationActive()) { + observer.onError(Status.FAILED_PRECONDITION.asRuntimeException()); + return; + } + WorldCanonicalInstanceLifecycleEvidence.Request selector; + try { + if (request == null + || !request.hasLifecycle() + || !request.getUnknownFields().asMap().isEmpty()) { + throw new IllegalArgumentException("A complete fixture lifecycle selector is required"); + } + selector = WorldCanonicalInstanceLifecycleGrpcCodec.fromRequest(request.getLifecycle()); + } catch (IllegalArgumentException invalid) { + observer.onError(Status.INVALID_ARGUMENT.asRuntimeException()); + return; + } + if (!trustedNamespace.equals(selector.targetNamespace())) { + observer.onError(Status.PERMISSION_DENIED.asRuntimeException()); + return; + } + final ReadRunOwnedFixtureStartRoomResponse response; + try { + var placement = repository.readRunOwnedFixtureStartRoom(selector); + if (placement.isEmpty()) { + observer.onError(Status.NOT_FOUND.asRuntimeException()); + return; + } + var startRoom = placement.orElseThrow(); + response = + ReadRunOwnedFixtureStartRoomResponse.newBuilder() + .setLifecycle( + WorldCanonicalInstanceLifecycleGrpcCodec.toFixtureResponse( + selector, startRoom.lifecycle())) + .setRoomInstanceKey(startRoom.roomKey()) + .build(); + } catch (RuntimeException unavailable) { + observer.onError( + Status.UNAVAILABLE + .withDescription("The run-owned fixture start room is unavailable") + .asRuntimeException()); + return; + } + observer.onNext(response); + observer.onCompleted(); + } + private boolean requireAuthenticatedGameSessionPeer(StreamObserver responseObserver) { GrpcPeerIdentity peer = GrpcPeerIdentity.current(); if (peer == null) { diff --git a/services/world-management-service/src/main/java/net/firedevops/firemud/worldmanagement/tenant/WorldCanonicalInstanceLifecycleReadRepository.java b/services/world-management-service/src/main/java/net/firedevops/firemud/worldmanagement/tenant/WorldCanonicalInstanceLifecycleReadRepository.java index 60045c83fc..22eb7d1052 100644 --- a/services/world-management-service/src/main/java/net/firedevops/firemud/worldmanagement/tenant/WorldCanonicalInstanceLifecycleReadRepository.java +++ b/services/world-management-service/src/main/java/net/firedevops/firemud/worldmanagement/tenant/WorldCanonicalInstanceLifecycleReadRepository.java @@ -21,6 +21,10 @@ import net.firedevops.firemud.common.world.WorldCanonicalInstanceLifecycleEvidence; import net.firedevops.firemud.common.world.WorldDraftStartLocationEvidence; import net.firedevops.firemud.common.world.WorldPublishedStartLocationEvidence; +import net.firedevops.firemud.common.world.WorldRunOwnedFixtureLifecycleEvidence; +import net.firedevops.firemud.worldmanagement.data.RunOwnedWorldFixedPresetResources; +import net.firedevops.firemud.worldmanagement.dto.RoomSnapshotDto; +import net.firedevops.firemud.worldmanagement.service.RoomService; import net.firedevops.firemud.worldmanagement.v1.WorldInboundSourceFamily; import org.jooq.DSLContext; import org.jooq.Record; @@ -113,6 +117,215 @@ public Optional read( })); } + /** + * Reads the exact run-owned fixture lifecycle. A fixture has no Human release attestation: its + * request carries the retained fixture descriptor digests and the fixture provenance digest in + * place of the release attestation. Any other association is an ordinary empty read. + */ + public Optional readRunOwnedFixture( + WorldCanonicalInstanceLifecycleEvidence.Request request) { + Objects.requireNonNull(request, "request"); + requireNoActiveTransaction("World run-owned fixture lifecycle read"); + return Optional.ofNullable( + transaction.execute( + status -> { + requireReadOnlyRepeatableReadOwnerTransaction(); + var snapshot = readRunOwnedFixtureSnapshotInCurrentOwnerTransaction(request); + return snapshot == null ? null : snapshot.lifecycle(); + })); + } + + /** + * Reads the actual fixed-preset starter room and exact ACTIVE fixture lifecycle in one owner + * snapshot. This supplies neither placement nor admission authority and never adopts legacy + * rooms. + */ + public Optional readRunOwnedFixtureStartRoom( + WorldCanonicalInstanceLifecycleEvidence.Request request) { + Objects.requireNonNull(request, "request"); + requireNoActiveTransaction("World run-owned fixture start-room read"); + return Optional.ofNullable( + transaction.execute( + status -> { + requireReadOnlyRepeatableReadOwnerTransaction(); + var snapshot = readRunOwnedFixtureSnapshotInCurrentOwnerTransaction(request); + if (snapshot == null || !"ACTIVE".equals(snapshot.lifecycle().lifecycleStatus())) { + return null; + } + long roomId = requireRunOwnedFixtureStartRoom(snapshot.association()); + return new FixtureStartRoom(snapshot.lifecycle(), "R-" + roomId); + })); + } + + public record FixtureStartRoom(WorldRunOwnedFixtureLifecycleEvidence lifecycle, String roomKey) {} + + /** + * Reads the existing room snapshot only after the exact ACTIVE fixture and its mapped starter + * room match the requested room key in the same owner snapshot. Private numeric selectors are + * resolved solely from retained World evidence; inconsistent room readback is refused. + */ + public Optional readRunOwnedFixtureStartRoomView( + WorldCanonicalInstanceLifecycleEvidence.Request request, + String expectedRoomKey, + String preferredLocale, + RoomService rooms) { + Objects.requireNonNull(request, "request"); + Objects.requireNonNull(expectedRoomKey, "expectedRoomKey"); + Objects.requireNonNull(rooms, "rooms"); + requireNoActiveTransaction("World run-owned fixture start-room view read"); + return Optional.ofNullable( + transaction.execute( + status -> { + requireReadOnlyRepeatableReadOwnerTransaction(); + var fixture = readRunOwnedFixtureSnapshotInCurrentOwnerTransaction(request); + if (fixture == null || !"ACTIVE".equals(fixture.lifecycle().lifecycleStatus())) { + return null; + } + long roomId = requireRunOwnedFixtureStartRoom(fixture.association()); + if (!("R-" + roomId).equals(expectedRoomKey)) { + return null; + } + if (!Boolean.FALSE.equals( + dsl.fetchValue( + "SELECT EXISTS (SELECT 1 FROM character_location" + + " WHERE canonical_game_instance_id = ? AND runtime_room_instance_id = ?)", + request.canonicalGameInstanceId(), + roomId))) { + throw invalid("Run-owned starter LOOK does not support populated World occupancy"); + } + var keys = fixture.association().runOwnedFixture().worldPrivateKeys(); + RoomSnapshotDto snapshot = + rooms.getRoomSnapshot( + keys.tenantId(), keys.gameInstanceId(), roomId, preferredLocale); + if (snapshot == null + || !Long.valueOf(roomId).equals(snapshot.roomInstanceRowId()) + || !Long.valueOf(keys.tenantId()).equals(snapshot.tenantId()) + || !Long.valueOf(keys.gameInstanceId()).equals(snapshot.gameInstanceId())) { + throw invalid("Run-owned fixture room snapshot differs from its mapped room scope"); + } + return new FixtureStartRoomView(fixture.lifecycle(), snapshot); + })); + } + + public record FixtureStartRoomView( + WorldRunOwnedFixtureLifecycleEvidence lifecycle, RoomSnapshotDto snapshot) {} + + private record RunOwnedFixtureSnapshot( + WorldCanonicalInstanceAssociation association, + WorldRunOwnedFixtureLifecycleEvidence lifecycle) {} + + private RunOwnedFixtureSnapshot readRunOwnedFixtureSnapshotInCurrentOwnerTransaction( + WorldCanonicalInstanceLifecycleEvidence.Request request) { + try { + Optional maybeAssociation = + associationRepository.readOwnerAssociationInOwnerTransaction( + request.canonicalGameInstanceId()); + if (maybeAssociation.isEmpty()) return null; + WorldCanonicalInstanceAssociation association = maybeAssociation.orElseThrow(); + if (!association.isRunOwnedFixture() || !matchesFixtureRequest(request, association)) { + return null; + } + Record row = + dsl.fetchOne( + "SELECT status,lifecycle_epoch,row_version FROM world_instance WHERE id=?", + association.worldInstanceId()); + if (row == null) return null; + var fixture = association.runOwnedFixture(); + return new RunOwnedFixtureSnapshot( + association, + new WorldRunOwnedFixtureLifecycleEvidence( + request, + fixture.fixtureProvenanceDigest(), + fixture.preparationInputDigest(), + required(row, "status", String.class), + required(row, "lifecycle_epoch", Long.class), + required(row, "row_version", Long.class))); + } catch (org.springframework.dao.DataAccessException | DataAccessException unavailable) { + throw unavailable; + } catch ( + WorldCanonicalInstanceAssociationRepository.InvalidAssociationEvidenceException + inconsistent) { + throw new InvalidLifecycleEvidenceException( + "Canonical World fixture association source evidence is inconsistent", inconsistent); + } + } + + private long requireRunOwnedFixtureStartRoom(WorldCanonicalInstanceAssociation association) { + var keys = association.runOwnedFixture().worldPrivateKeys(); + UUID templateId = RunOwnedWorldFixedPresetResources.starterRoomTemplateId(); + Record room = + dsl.fetchOne( + "SELECT m.runtime_room_instance_id,m.runtime_row_id,m.template_private_row_key," + + "r.id AS room_row_id,r.room_instance_row_id,r.template_room_id " + + "FROM world_canonical_instance_topology_identity m " + + "JOIN room_instance r ON r.id=m.runtime_row_id " + + "JOIN region_instance ri ON ri.id=r.region_instance_id " + + "JOIN zone_instance zi ON zi.id=r.zone_instance_id " + + "WHERE m.world_instance_id=? AND m.canonical_game_instance_id=? " + + "AND m.family='ROOM' AND m.template_id=? " + + "AND r.tenant_id=? AND r.game_instance_id=? " + + "AND ri.world_instance_id=? AND ri.tenant_id=? AND ri.game_instance_id=? " + + "AND zi.tenant_id=? AND zi.game_instance_id=? " + + "AND zi.region_instance_id=ri.id", + association.worldInstanceId(), + association.identity().canonicalGameInstanceId(), + templateId, + keys.tenantId(), + keys.gameInstanceId(), + association.worldInstanceId(), + keys.tenantId(), + keys.gameInstanceId(), + keys.tenantId(), + keys.gameInstanceId()); + if (room == null) { + throw invalid("Active run-owned fixture lacks its exact mapped scoped starter room"); + } + Long roomId = room.get("runtime_room_instance_id", Long.class); + Long templateRowId = room.get("template_private_row_key", Long.class); + if (roomId == null + || roomId <= 0 + || !roomId.equals(room.get("runtime_row_id", Long.class)) + || !roomId.equals(room.get("room_row_id", Long.class)) + || !roomId.equals(room.get("room_instance_row_id", Long.class)) + || templateRowId == null + || templateRowId <= 0 + || !templateRowId.equals(room.get("template_room_id", Long.class))) { + throw invalid("Run-owned fixture starter ROOM mapping differs from its actual runtime room"); + } + return roomId; + } + + private boolean matchesFixtureRequest( + WorldCanonicalInstanceLifecycleEvidence.Request request, + WorldCanonicalInstanceAssociation association) { + var identity = association.identity(); + Record descriptor = + dsl.fetchOne( + "SELECT descriptor_request_digest, descriptor_result_digest " + + "FROM world_canonical_instance_association " + + "WHERE canonical_game_instance_id = ? AND canonical_authority_kind = 'RUN_OWNED_FIXTURE'", + identity.canonicalGameInstanceId()); + return descriptor != null + && request.canonicalGameInstanceId().equals(identity.canonicalGameInstanceId()) + && request.targetNamespace().equals(identity.targetNamespace()) + && request.canonicalTenantId().equals(identity.canonicalTenantId()) + && request.worldSlug().equals(identity.worldSlug()) + && request.playableStateNamespaceId().equals(identity.playableStateNamespaceId()) + && request.playableStateScope().equals(identity.playableStateScope()) + && request.publicProduction() == identity.publicProduction() + && request.controlPlaneRequestId().equals(identity.controlPlaneRequestId()) + && request.canonicalVersionId().equals(association.canonicalVersionId()) + && request + .expectedDescriptorRequestDigest() + .equals(required(descriptor, "descriptor_request_digest", String.class)) + && request + .expectedDescriptorResultDigest() + .equals(required(descriptor, "descriptor_result_digest", String.class)) + && request + .expectedReleaseAttestationDigest() + .equals(association.runOwnedFixture().fixtureProvenanceDigest()); + } + /** * Reconstructs the same exact owner evidence while a writable activation transaction holds it. */ @@ -142,7 +355,8 @@ private WorldCanonicalInstanceLifecycleEvidence readInCurrentOwnerTransaction( request.canonicalGameInstanceId()); if (maybeAssociation.isEmpty()) return null; WorldCanonicalInstanceAssociation association = maybeAssociation.orElseThrow(); - if (!matchesRequest(request, association)) return null; + // The run-owned fixture has no Human launch binding; it answers readRunOwnedFixture only. + if (association.isRunOwnedFixture() || !matchesRequest(request, association)) return null; Record preparation = dsl.fetchOne( diff --git a/services/world-management-service/src/main/resources/application.yml b/services/world-management-service/src/main/resources/application.yml index db840be505..dc81661608 100644 --- a/services/world-management-service/src/main/resources/application.yml +++ b/services/world-management-service/src/main/resources/application.yml @@ -87,6 +87,14 @@ firemud: grpc: public-methods: - world_management.v1.WorldManagementService/Ping + # Registered only for the run-owned fixture; the service authenticates the exact + # same-namespace Game Session mTLS peer itself and carries no bearer token. + - world_management.v1.WorldCanonicalInitialAdmissionHoldService/AcquireCanonicalInitialAdmissionHold + - world_management.v1.WorldCanonicalInitialAdmissionHoldService/ReadCanonicalInitialAdmissionHoldIdentity + - world_management.v1.WorldCanonicalInitialAdmissionHoldService/ReadCanonicalInitialAdmissionHoldState + - world_management.v1.WorldCanonicalInstanceLifecycleReadService/ReadWorldCanonicalInstanceLifecycle + - world_management.v1.WorldCanonicalInstanceLifecycleReadService/ReadRunOwnedFixtureStartRoom + - world_management.v1.RunOwnedFixtureLookWorldService/ReadRunOwnedFixtureLookRoom grpc: cert-chain: ${FIREMUD_GRPC_CERT_CHAIN_PATH:certs/client.crt} private-key: ${FIREMUD_GRPC_PRIVATE_KEY_PATH:certs/client.key} diff --git a/services/world-management-service/src/main/resources/db/migration/V1070__world_run_owned_fixture_activation.sql b/services/world-management-service/src/main/resources/db/migration/V1070__world_run_owned_fixture_activation.sql new file mode 100644 index 0000000000..3a0c33ceb4 --- /dev/null +++ b/services/world-management-service/src/main/resources/db/migration/V1070__world_run_owned_fixture_activation.sql @@ -0,0 +1,309 @@ +-- Canonical run-owned fixture activation. The World lifecycle owner retains one immutable activation +-- row per fixture instance and, in the same transaction, moves the World row from its original +-- PREPARING epoch to ACTIVE. The storage guard admits only that exact CAS with its matching row; +-- every other fixture row mutation stays refused. Human activation guards are unchanged. +-- [jooq ignore start] +CREATE TABLE world_run_owned_fixture_activation ( + world_instance_id BIGINT PRIMARY KEY REFERENCES world_instance (id), + canonical_game_instance_id UUID NOT NULL UNIQUE, + fixture_binding_sha256 CHAR(64) NOT NULL CHECK (fixture_binding_sha256 ~ '^[0-9a-f]{64}$'), + expected_lifecycle_epoch BIGINT NOT NULL CHECK (expected_lifecycle_epoch = 1), + expected_row_version BIGINT NOT NULL CHECK (expected_row_version >= 0), + result_lifecycle_epoch BIGINT NOT NULL, + result_row_version BIGINT NOT NULL, + activated_at TIMESTAMPTZ NOT NULL DEFAULT now(), + CHECK (result_lifecycle_epoch = expected_lifecycle_epoch + 1), + CHECK (result_row_version = expected_row_version + 1) +); + +INSERT INTO world_runtime_family_classification(family_id,relation_name,family_role,state_class,fresh_disposition) +VALUES ('world_run_owned_fixture_activation','world_run_owned_fixture_activation','AUDIT','NOT_PAYLOAD','AUDIT_ONLY'); + +CREATE FUNCTION world_run_owned_fixture_activation_immutable() +RETURNS TRIGGER +LANGUAGE plpgsql SET search_path = pg_catalog, "${serviceSchema}" +AS $$ +BEGIN + RAISE EXCEPTION 'Run-owned fixture activation rows are immutable' + USING ERRCODE = '23514'; +END; +$$; +REVOKE ALL ON FUNCTION world_run_owned_fixture_activation_immutable() FROM PUBLIC; +CREATE TRIGGER trg_world_run_owned_fixture_activation_immutable + BEFORE UPDATE OR DELETE ON world_run_owned_fixture_activation + FOR EACH ROW EXECUTE FUNCTION world_run_owned_fixture_activation_immutable(); +CREATE TRIGGER trg_world_run_owned_fixture_activation_no_truncate + BEFORE TRUNCATE ON world_run_owned_fixture_activation + FOR EACH STATEMENT EXECUTE FUNCTION world_run_owned_fixture_activation_immutable(); + +DO $migration$ +DECLARE + original TEXT; + anchor TEXT := $anchor$IF OLD.canonical_authority_kind = 'RUN_OWNED_FIXTURE' + OR NEW.canonical_authority_kind = 'RUN_OWNED_FIXTURE' THEN + RAISE EXCEPTION 'Run-owned fixture World row mutations are disabled' + USING ERRCODE = '23514'; + END IF;$anchor$; + replacement TEXT := $replacement$IF OLD.canonical_authority_kind = 'RUN_OWNED_FIXTURE' + OR NEW.canonical_authority_kind = 'RUN_OWNED_FIXTURE' THEN + IF OLD.status = 'PREPARING' + AND NEW.status = 'ACTIVE' + AND OLD.lifecycle_epoch = OLD.run_owned_fixture_preparing_lifecycle_epoch + AND NEW.lifecycle_epoch = OLD.lifecycle_epoch + 1 + AND NEW.row_version = OLD.row_version + 1 + AND (to_jsonb(OLD) - ARRAY['status', 'lifecycle_epoch', 'row_version']) + = (to_jsonb(NEW) - ARRAY['status', 'lifecycle_epoch', 'row_version']) + AND EXISTS ( + SELECT 1 FROM "${serviceSchema}".world_run_owned_fixture_activation a + WHERE a.world_instance_id = OLD.id + AND a.canonical_game_instance_id = OLD.canonical_game_instance_id + AND a.fixture_binding_sha256 = OLD.run_owned_fixture_binding_sha256 + AND a.expected_lifecycle_epoch = OLD.lifecycle_epoch + AND a.expected_row_version = OLD.row_version + AND a.result_lifecycle_epoch = NEW.lifecycle_epoch + AND a.result_row_version = NEW.row_version) THEN + RETURN NEW; + END IF; + RAISE EXCEPTION 'Run-owned fixture World row mutations are disabled' + USING ERRCODE = '23514'; + END IF;$replacement$; +BEGIN + SELECT pg_get_functiondef( + '"${serviceSchema}".world_guard_canonical_activation_transition()'::REGPROCEDURE) + INTO STRICT original; + IF (length(original)-length(replace(original,anchor,'')))/length(anchor) <> 1 THEN + RAISE EXCEPTION 'Expected exactly one run-owned fixture World row-mutation anchor'; + END IF; + EXECUTE replace(original, anchor, replacement); +END; +$migration$; + +-- The reserved-tenant execution guard admits the same exact fixture CAS when its activation row +-- was inserted by the current transaction. +DO $migration$ +DECLARE + original TEXT; + anchor TEXT := $anchor$ RAISE EXCEPTION + 'World tenant key is reserved for a canonical authored source; no exact transaction execution manifest'$anchor$; +BEGIN + SELECT pg_get_functiondef('"${serviceSchema}".world_claim_legacy_numeric_tenant_key()'::REGPROCEDURE) + INTO STRICT original; + IF (length(original)-length(replace(original,anchor,'')))/length(anchor) <> 1 THEN + RAISE EXCEPTION 'Expected exactly one reserved-tenant execution denial guard'; + END IF; + original := replace(original,anchor,$replacement$ IF TG_TABLE_SCHEMA = '${serviceSchema}' AND TG_TABLE_NAME = 'world_instance' + AND TG_OP = 'UPDATE' + AND old_row->>'canonical_authority_kind' = 'RUN_OWNED_FIXTURE' + AND old_row->>'status' = 'PREPARING' AND new_row->>'status' = 'ACTIVE' + AND (old_row - ARRAY['status', 'lifecycle_epoch', 'row_version']) + = (new_row - ARRAY['status', 'lifecycle_epoch', 'row_version']) + AND EXISTS (SELECT 1 FROM "${serviceSchema}".world_run_owned_fixture_activation a + WHERE a.world_instance_id = (old_row->>'id')::BIGINT + AND a.canonical_game_instance_id::TEXT = old_row->>'canonical_game_instance_id' + AND a.expected_lifecycle_epoch = (old_row->>'lifecycle_epoch')::BIGINT + AND a.expected_row_version = (old_row->>'row_version')::BIGINT + AND a.result_lifecycle_epoch = (new_row->>'lifecycle_epoch')::BIGINT + AND a.result_row_version = (new_row->>'row_version')::BIGINT + AND a.xmin::TEXT = (txid_current() % 4294967296)::TEXT) THEN + RETURN NEW; + END IF; +$replacement$ || anchor); + EXECUTE original; +END; +$migration$; + +-- Run-owned fixture associations may acquire a typed initial-admission hold through the World +-- owner (ACTIVE fixture row, exact association target). The V1040 refusal is removed; Human and +-- legacy acquisitions keep their existing validation. +DO $migration$ +DECLARE + original TEXT; + anchor TEXT := $anchor$ IF TG_OP = 'INSERT' AND EXISTS ( + SELECT 1 + FROM "${serviceSchema}".world_canonical_instance_association a + JOIN "${serviceSchema}".world_instance wi ON wi.id = a.world_instance_id + WHERE a.schema_version = 3 + AND a.canonical_authority_kind = 'RUN_OWNED_FIXTURE' + AND (a.canonical_game_instance_id = NEW.canonical_game_instance_id + OR (wi.tenant_id = NEW.tenant_id + AND wi.game_instance_id = NEW.game_instance_id + AND wi.version_id = NEW.version_id))) THEN + RAISE EXCEPTION 'Run-owned fixture initial-admission holds are disabled' + USING ERRCODE = '23514'; + END IF; +$anchor$; +BEGIN + SELECT pg_get_functiondef( + '"${serviceSchema}".world_guard_canonical_initial_admission_hold()'::REGPROCEDURE) + INTO STRICT original; + IF (length(original)-length(replace(original,anchor,'')))/length(anchor) <> 1 THEN + RAISE EXCEPTION 'Expected exactly one run-owned fixture hold refusal'; + END IF; + EXECUTE replace(original, anchor, ''); +END; +$migration$; + +-- The guarded finalizer may settle a fixture hold from the exact Game Session terminal proof. +DO $migration$ +DECLARE + original TEXT; + anchor TEXT := $anchor$ IF EXISTS ( + SELECT 1 + FROM "${serviceSchema}".world_canonical_instance_association a + JOIN "${serviceSchema}".world_instance wi ON wi.id = a.world_instance_id + WHERE a.schema_version = 3 + AND a.canonical_authority_kind = 'RUN_OWNED_FIXTURE' + AND (a.canonical_game_instance_id = candidate.canonical_game_instance_id + OR (wi.tenant_id = candidate.tenant_id + AND wi.game_instance_id = candidate.game_instance_id + AND wi.version_id = candidate.version_id))) THEN + RAISE EXCEPTION 'Run-owned fixture initial-admission hold finalization is disabled' + USING ERRCODE = '23514'; + END IF; +$anchor$; +BEGIN + SELECT pg_get_functiondef( + '"${serviceSchema}".world_finalize_canonical_initial_admission_hold(uuid,uuid,text,text,text,text,bigint,timestamptz,boolean,bytea,text)'::REGPROCEDURE) + INTO STRICT original; + IF (length(original)-length(replace(original,anchor,'')))/length(anchor) <> 1 THEN + RAISE EXCEPTION 'Expected exactly one run-owned fixture hold finalization refusal'; + END IF; + EXECUTE replace(original, anchor, ''); +END; +$migration$; + +-- V1070 joins the catalog installation set: its own history row is sealed as an installation +-- marker, exactly as V1046-V1050, so the post-commit history row cannot drift the seal. +CREATE OR REPLACE FUNCTION world_runtime_family_catalog_installed() RETURNS BOOLEAN +LANGUAGE SQL STABLE +SET search_path = "${serviceSchema}", pg_catalog +AS $$ + SELECT EXISTS (SELECT 1 FROM "${flyway:table}" + WHERE version='1046' AND script='V1046__world_owner_runtime_family_catalog.sql' AND success) + AND EXISTS (SELECT 1 FROM "${flyway:table}" + WHERE version='1047' AND script='V1047__world_catalog_snapshot_exact_frames.sql' AND success) + AND EXISTS (SELECT 1 FROM "${flyway:table}" + WHERE version='1048' AND script='V1048__world_protected_installation_registry.sql' AND success) + AND EXISTS (SELECT 1 FROM "${flyway:table}" WHERE version='1049' + AND script='V1049__world_private_fresh_operation.sql' AND success) + AND EXISTS (SELECT 1 FROM "${flyway:table}" WHERE version='1050' + AND script='V1050__world_private_fresh_settlement_binding.sql' AND success) + AND EXISTS (SELECT 1 FROM "${flyway:table}" WHERE version='1070' + AND script='V1070__world_run_owned_fixture_activation.sql' AND success); +$$; + +CREATE OR REPLACE FUNCTION world_runtime_family_catalog_bytes(p_epoch BIGINT) RETURNS BYTEA +LANGUAGE plpgsql STABLE +SET search_path = "${serviceSchema}", pg_catalog +AS $$ +DECLARE + v_families JSONB; + v_facts JSONB; +BEGIN + IF p_epoch IS NULL OR p_epoch <= 0 THEN + RAISE EXCEPTION 'Positive World catalog epoch required' USING ERRCODE = '23514'; + END IF; + IF EXISTS ( + SELECT c.relname FROM pg_class c JOIN pg_namespace n ON n.oid=c.relnamespace + WHERE n.nspname='${serviceSchema}' AND c.relkind IN ('r','p','f') + EXCEPT SELECT relation_name FROM world_runtime_family_classification WHERE component_name='' + ) OR EXISTS ( + SELECT 1 FROM world_runtime_family_classification f + LEFT JOIN pg_namespace n ON n.nspname='${serviceSchema}' + LEFT JOIN pg_class c ON c.relnamespace=n.oid AND c.relname=f.relation_name AND c.relkind IN ('r','p','f') + WHERE c.oid IS NULL OR (f.component_name<>'' AND NOT EXISTS ( + SELECT 1 FROM pg_attribute a WHERE a.attrelid=c.oid AND a.attname=f.component_name + AND a.attnum>0 AND NOT a.attisdropped)) + ) THEN + RAISE EXCEPTION 'Unclassified or changed World schema family' USING ERRCODE = '23514'; + END IF; + + SELECT jsonb_agg(jsonb_build_object('familyId',family_id,'relation',relation_name, + 'component',component_name,'role',family_role,'stateClass',state_class, + 'freshDisposition',fresh_disposition) ORDER BY family_id COLLATE "C") + INTO v_families FROM world_runtime_family_classification; + + WITH relations AS ( + SELECT c.* FROM pg_class c JOIN pg_namespace n ON n.oid=c.relnamespace + WHERE n.nspname='${serviceSchema}' + ), definitions(kind,identity,definition) AS ( + SELECT 'TABLE',c.relname::TEXT,jsonb_build_array(c.relkind,c.relpersistence, + c.relrowsecurity,c.relforcerowsecurity,c.reloptions,pg_get_partkeydef(c.oid))::TEXT + FROM relations c WHERE c.relkind IN ('r','p','f') + UNION ALL + SELECT 'COLUMN',c.relname||'.'||a.attname,jsonb_build_array(a.attnum, + format_type(a.atttypid,a.atttypmod),a.attnotnull,a.attidentity,a.attgenerated, + pg_get_expr(d.adbin,d.adrelid),co.collname)::TEXT + FROM relations c JOIN pg_attribute a ON a.attrelid=c.oid + LEFT JOIN pg_attrdef d ON d.adrelid=c.oid AND d.adnum=a.attnum + LEFT JOIN pg_collation co ON co.oid=a.attcollation + WHERE c.relkind IN ('r','p','f','v','m') AND a.attnum>0 AND NOT a.attisdropped + UNION ALL + SELECT 'CONSTRAINT',c.relname||'.'||k.conname, + jsonb_build_array(pg_get_constraintdef(k.oid,true),k.convalidated,k.condeferrable,k.condeferred)::TEXT + FROM relations c JOIN pg_constraint k ON k.conrelid=c.oid + UNION ALL + SELECT 'INDEX',c.relname::TEXT,jsonb_build_array(pg_get_indexdef(c.oid),i.indisvalid,i.indisready)::TEXT + FROM relations c JOIN pg_index i ON i.indexrelid=c.oid + UNION ALL + SELECT 'TRIGGER',c.relname||'.'||t.tgname,jsonb_build_array(pg_get_triggerdef(t.oid,true),t.tgenabled)::TEXT + FROM relations c JOIN pg_trigger t ON t.tgrelid=c.oid WHERE NOT t.tgisinternal + UNION ALL + SELECT 'POLICY',c.relname||'.'||p.polname, + jsonb_build_array(p.polcmd,p.polpermissive, + (SELECT jsonb_agg(r.rolname ORDER BY r.rolname COLLATE "C") FROM pg_roles r WHERE r.oid=ANY(p.polroles)), + pg_get_expr(p.polqual,p.polrelid),pg_get_expr(p.polwithcheck,p.polrelid))::TEXT + FROM relations c JOIN pg_policy p ON p.polrelid=c.oid + UNION ALL + SELECT 'RULE',c.relname||'.'||r.rulename,pg_get_ruledef(r.oid,true) + FROM relations c JOIN pg_rewrite r ON r.ev_class=c.oid + UNION ALL + SELECT 'ROUTINE',p.proname||'('||pg_get_function_identity_arguments(p.oid)||')',pg_get_functiondef(p.oid) + FROM pg_proc p JOIN pg_namespace n ON n.oid=p.pronamespace + WHERE n.nspname='${serviceSchema}' AND p.prokind IN ('f','p') + UNION ALL + SELECT 'SEQUENCE',c.relname::TEXT,(to_jsonb(s)-'seqrelid')::TEXT + FROM relations c JOIN pg_sequence s ON s.seqrelid=c.oid + UNION ALL + SELECT 'VIEW',c.relname::TEXT,jsonb_build_array(pg_get_viewdef(c.oid,true),c.reloptions)::TEXT + FROM relations c WHERE c.relkind IN ('v','m') + UNION ALL + SELECT 'TYPE',t.typname::TEXT,jsonb_build_array(t.typtype,t.typnotnull,t.typdefault, + (SELECT jsonb_agg(e.enumlabel ORDER BY e.enumsortorder) FROM pg_enum e WHERE e.enumtypid=t.oid))::TEXT + FROM pg_type t JOIN pg_namespace n ON n.oid=t.typnamespace WHERE n.nspname='${serviceSchema}' + UNION ALL + SELECT 'MIGRATION',installed_rank::TEXT||':'||coalesce(version,'repeatable')||':'||script, + jsonb_build_array(version,type,script,checksum,success)::TEXT + FROM "${flyway:table}" WHERE version IS DISTINCT FROM '1046' AND version IS DISTINCT FROM '1047' AND version IS DISTINCT FROM '1048' AND version IS DISTINCT FROM '1049' AND version IS DISTINCT FROM '1050' AND version IS DISTINCT FROM '1070' + UNION ALL + SELECT 'MIGRATION','catalog-installation:1046','V1046__world_owner_runtime_family_catalog.sql' + UNION ALL + SELECT 'MIGRATION','catalog-installation:1047','V1047__world_catalog_snapshot_exact_frames.sql' + UNION ALL + SELECT 'MIGRATION','catalog-installation:1048','V1048__world_protected_installation_registry.sql' + UNION ALL + SELECT 'MIGRATION','catalog-installation:1049','V1049__world_private_fresh_operation.sql' + UNION ALL + SELECT 'MIGRATION','catalog-installation:1050','V1050__world_private_fresh_settlement_binding.sql' + UNION ALL + SELECT 'MIGRATION','catalog-installation:1070','V1070__world_run_owned_fixture_activation.sql' + ) + SELECT jsonb_agg(jsonb_build_object('kind',kind,'identity',identity, + 'definitionDigest','sha256:'||encode(sha256(convert_to(definition,'UTF8')),'hex')) + ORDER BY (kind||'/'||identity) COLLATE "C") INTO v_facts FROM definitions; + + IF jsonb_array_length(v_families)>512 OR jsonb_array_length(v_facts)>16384 THEN + RAISE EXCEPTION 'Complete World catalog exceeds source bounds' USING ERRCODE = '23514'; + END IF; + RETURN convert_to(jsonb_build_object('schema','world-runtime-family-catalog/v1', + 'owner','world-management-service','catalogEpoch',p_epoch::TEXT, + 'families',v_families,'schemaFacts',v_facts)::TEXT,'UTF8'); +END; +$$; + +-- The new owner table and guard change advance the sealed World schema catalog epoch. +INSERT INTO world_runtime_family_catalog_epoch(catalog_epoch,catalog_bytes,catalog_digest) +SELECT next_epoch,bytes,'sha256:'||encode(sha256(bytes),'hex') +FROM (SELECT coalesce(max(catalog_epoch),0)+1 AS next_epoch FROM world_runtime_family_catalog_epoch) next +CROSS JOIN LATERAL (SELECT world_runtime_family_catalog_bytes(next.next_epoch) AS bytes) seal; +-- [jooq ignore stop] diff --git a/services/world-management-service/src/test/java/integration/net/firedevops/firemud/worldmanagement/RunOwnedWorldLaunchEvidenceMtlsIntegrationTest.java b/services/world-management-service/src/test/java/integration/net/firedevops/firemud/worldmanagement/RunOwnedWorldLaunchEvidenceMtlsIntegrationTest.java index b370c30aa9..f5365bce0a 100644 --- a/services/world-management-service/src/test/java/integration/net/firedevops/firemud/worldmanagement/RunOwnedWorldLaunchEvidenceMtlsIntegrationTest.java +++ b/services/world-management-service/src/test/java/integration/net/firedevops/firemud/worldmanagement/RunOwnedWorldLaunchEvidenceMtlsIntegrationTest.java @@ -1328,7 +1328,7 @@ private static RunOwnedInitialAdmissionFixtureWireCodec.Capability capability( true, false, "SHARED", - "ALLOW_NEW", + "PRESEEDED_ONLY", fingerprint(pki.gameSessionClient().certificate()), GS_URI, fingerprint(pki.caCertificateValue()), diff --git a/services/world-management-service/src/test/java/integration/net/firedevops/firemud/worldmanagement/data/RunOwnedWorldFixedPresetResourcesPostgresIntegrationTest.java b/services/world-management-service/src/test/java/integration/net/firedevops/firemud/worldmanagement/data/RunOwnedWorldFixedPresetResourcesPostgresIntegrationTest.java index 163e03ce44..37a4d30b01 100644 --- a/services/world-management-service/src/test/java/integration/net/firedevops/firemud/worldmanagement/data/RunOwnedWorldFixedPresetResourcesPostgresIntegrationTest.java +++ b/services/world-management-service/src/test/java/integration/net/firedevops/firemud/worldmanagement/data/RunOwnedWorldFixedPresetResourcesPostgresIntegrationTest.java @@ -38,6 +38,9 @@ import net.firedevops.firemud.common.grpc.GrpcPeerIdentity; import net.firedevops.firemud.common.publication.PublicationDigestRequestBinding; import net.firedevops.firemud.common.tenant.AuthoredWorldSourceClient; +import net.firedevops.firemud.common.world.WorldCanonicalInitialAdmissionHold; +import net.firedevops.firemud.common.world.WorldCanonicalInitialAdmissionHoldState; +import net.firedevops.firemud.common.world.WorldCanonicalInstanceLifecycleEvidence; import net.firedevops.firemud.gamedesign.v1.VersionLifecycleState; import net.firedevops.firemud.test.PostgresBackedServiceTestSupport; import net.firedevops.firemud.test.TestContainerImages; @@ -46,16 +49,22 @@ import net.firedevops.firemud.worldmanagement.client.GameDesignClient; import net.firedevops.firemud.worldmanagement.client.GameSessionClient; import net.firedevops.firemud.worldmanagement.client.GrpcGameSessionInitialAdmissionBindProofClient; +import net.firedevops.firemud.worldmanagement.config.WorldProperties; import net.firedevops.firemud.worldmanagement.dto.PreparedWorldInstanceRequest; import net.firedevops.firemud.worldmanagement.dto.WorldInstanceLifecycleSnapshotDto; +import net.firedevops.firemud.worldmanagement.repository.RoomInstanceExitRepository; +import net.firedevops.firemud.worldmanagement.repository.RoomInstanceRepository; +import net.firedevops.firemud.worldmanagement.service.impl.RoomServiceImpl; import net.firedevops.firemud.worldmanagement.service.impl.RunOwnedWorldFixtureLifecycleTestFactory; import net.firedevops.firemud.worldmanagement.service.impl.WorldLifecycleCommandServiceImpl; import net.firedevops.firemud.worldmanagement.tenant.WorldAuthoredSourceIntakeReceipt; import net.firedevops.firemud.worldmanagement.tenant.WorldAuthoredSourceIntakeRepository; import net.firedevops.firemud.worldmanagement.tenant.WorldAuthoredVersionIdentityReceipt; import net.firedevops.firemud.worldmanagement.tenant.WorldAuthoredVersionIdentityRepository; +import net.firedevops.firemud.worldmanagement.tenant.WorldCanonicalInitialAdmissionHoldRepository; import net.firedevops.firemud.worldmanagement.tenant.WorldCanonicalInstanceAssociation; import net.firedevops.firemud.worldmanagement.tenant.WorldCanonicalInstanceAssociationRepository; +import net.firedevops.firemud.worldmanagement.tenant.WorldCanonicalInstanceLifecycleReadRepository; import net.firedevops.firemud.worldmanagement.tenant.WorldCompleteLaunchBindingRepository; import net.firedevops.firemud.worldmanagement.tenant.WorldDesignPublicationFenceEvidence.OwnerBinding; import net.firedevops.firemud.worldmanagement.tenant.WorldDesignPublicationFenceRepository; @@ -819,6 +828,162 @@ void actualFixtureMaterializationRetainsUnderOwnerSavepoint() { assertNoPendingManifests(allocatedFixture.worldInstanceId()); } + @Test + void fixtureActivationMovesOriginalPreparingEpochToActiveOnceAndReplaysExactly() + throws Exception { + var evidence = controlledEvidence(); + var service = nativeService(evidence); + prepareWithInstallation(service, evidence); + var association = + associationRepository() + .readRunOwnedFixtureAssociation( + evidence, RunOwnedWorldFixtureEvidenceTestFixtures.request(evidence)); + long id = association.worldInstanceId(); + var request = RunOwnedWorldFixtureEvidenceTestFixtures.request(evidence); + + var activated = + RunOwnedWorldFixtureLifecycleTestFactory.activate( + service, evidence, controlledInstallation, 1L); + + assertThat(activated.status()).isEqualTo("ACTIVE"); + assertThat(activated.lifecycleEpoch()).isEqualTo(2L); + assertThat(activated.tenantId()).isEqualTo(request.tenantId()); + assertThat(activated.gameInstanceId()).isEqualTo(request.gameInstanceId()); + assertThat( + scalarLong( + "SELECT count(*) FROM world_run_owned_fixture_activation WHERE world_instance_id = ?", + id)) + .isEqualTo(1L); + assertThat(scalarLong("SELECT row_version FROM world_instance WHERE id = ?", id)).isEqualTo(1L); + + var replay = + RunOwnedWorldFixtureLifecycleTestFactory.activate( + service, evidence, controlledInstallation, 1L); + assertThat(replay.status()).isEqualTo("ACTIVE"); + assertThat(replay.lifecycleEpoch()).isEqualTo(2L); + assertThat(scalarLong("SELECT row_version FROM world_instance WHERE id = ?", id)).isEqualTo(1L); + assertThatThrownBy( + () -> + RunOwnedWorldFixtureLifecycleTestFactory.activate( + service, evidence, controlledInstallation, 3L)) + .hasMessageStartingWith("LIFECYCLE_EPOCH_MISMATCH:"); + assertSqlState( + () -> + dsl.execute( + "UPDATE world_instance SET status = 'TERMINATING', lifecycle_epoch = 3, row_version = 2 WHERE id = ?", + id), + "23514"); + assertSqlState( + () -> + dsl.execute( + "DELETE FROM world_run_owned_fixture_activation WHERE world_instance_id = ?", id), + "23514"); + } + + @Test + void activeFixtureAcquiresAndReadsTypedInitialAdmissionHoldWithFixtureLifecycle() + throws Exception { + var evidence = controlledEvidence(); + var service = nativeService(evidence); + prepareWithInstallation(service, evidence); + RunOwnedWorldFixtureLifecycleTestFactory.activate( + service, evidence, controlledInstallation, 1L); + var association = + associationRepository() + .readRunOwnedFixtureAssociation( + evidence, RunOwnedWorldFixtureEvidenceTestFixtures.request(evidence)); + var identity = association.identity(); + var holdRequest = + new WorldCanonicalInitialAdmissionHold.Request( + identity.targetNamespace(), + identity.canonicalTenantId(), + identity.worldSlug(), + identity.canonicalRealmId(), + identity.playableStateNamespaceId(), + identity.playableStateScope(), + identity.canonicalGameInstanceId(), + association.canonicalVersionId(), + 2L, + "fixture-initial-admission-1", + "a".repeat(64), + WorldCanonicalInitialAdmissionHold.InitialAdmissionOrigin.NO_PRIOR_POINTER, + identity.catalogRevision(), + null); + var lifecycleRequest = + new WorldCanonicalInstanceLifecycleEvidence.Request( + WorldCanonicalInstanceLifecycleEvidence.Request.SCHEMA_VERSION, + UUID.randomUUID(), + identity.targetNamespace(), + identity.canonicalTenantId(), + identity.worldSlug(), + identity.canonicalGameInstanceId(), + identity.playableStateNamespaceId(), + identity.playableStateScope(), + identity.publicProduction(), + identity.controlPlaneRequestId(), + association.canonicalVersionId(), + evidence.launchDescriptor().requestDigest(), + evidence.launchDescriptor().resultDigest(), + association.runOwnedFixture().fixtureProvenanceDigest()); + var lifecycleRepository = + new WorldCanonicalInstanceLifecycleReadRepository( + dsl, transactionManager, associationRepository()); + var holds = + new WorldCanonicalInitialAdmissionHoldRepository( + dsl, transactionManager, associationRepository(), lifecycleRepository); + + var room = lifecycleRepository.readRunOwnedFixtureStartRoom(lifecycleRequest).orElseThrow(); + var privateKeys = association.runOwnedFixture().worldPrivateKeys(); + long storedStartRoom = + dsl.fetchSingle( + "SELECT room_instance_row_id FROM room_instance " + + "WHERE tenant_id = ? AND game_instance_id = ? AND name = ?", + privateKeys.tenantId(), + privateKeys.gameInstanceId(), + "Candle-lit Antechamber") + .get(0, Long.class); + assertThat(room.roomKey()).isEqualTo("R-" + storedStartRoom); + assertThat(room.lifecycle()) + .isEqualTo(lifecycleRepository.readRunOwnedFixture(lifecycleRequest).orElseThrow()); + assertThat(room.lifecycle().lifecycleStatus()).isEqualTo("ACTIVE"); + + var rooms = + new RoomServiceImpl( + new RoomInstanceRepository(dsl), + null, + null, + new WorldProperties(), + new RoomInstanceExitRepository(dsl), + tools.jackson.databind.json.JsonMapper.builder().build()); + var view = + lifecycleRepository + .readRunOwnedFixtureStartRoomView(lifecycleRequest, room.roomKey(), "", rooms) + .orElseThrow(); + assertThat(view.lifecycle()).isEqualTo(room.lifecycle()); + assertThat(view.snapshot().roomInstanceRowId()).isEqualTo(storedStartRoom); + assertThat(view.snapshot().roomName()).isEqualTo("Candle-lit Antechamber"); + assertThat(view.snapshot().longDescription()).isNotBlank(); + assertThat( + lifecycleRepository.readRunOwnedFixtureStartRoomView( + lifecycleRequest, "R-0", "", rooms)) + .isEmpty(); + + var hold = holds.acquire(holdRequest, lifecycleRequest); + assertThat(holds.acquire(holdRequest, lifecycleRequest)).isEqualTo(hold); + var state = holds.readState(hold, lifecycleRequest).orElseThrow(); + + assertThat(state.isRunOwnedFixture()).isTrue(); + assertThat(state.isPendingAtExpectedActiveEpoch()).isTrue(); + assertThat(WorldCanonicalInitialAdmissionHoldState.fromStored(state.canonicalBytes())) + .isEqualTo(state); + assertSqlState( + () -> + dsl.execute( + "UPDATE world_instance SET status = 'TERMINATING', lifecycle_epoch = 3, row_version = 2 WHERE id = ?", + association.worldInstanceId()), + "55000"); + } + @Test void fixturePreparingCannotActivateAcquireHoldsPlaceActorsOrReuseConsumedManifests() throws Exception { @@ -850,7 +1015,7 @@ void fixturePreparingCannotActivateAcquireHoldsPlaceActorsOrReuseConsumedManifes associationRepository() .activateRunOwnedFixtureInOwnerTransaction(association, 1L, 0L)) .isInstanceOf(IllegalStateException.class) - .hasMessageStartingWith("RUN_OWNED_WORLD_ACTIVATION_UNAVAILABLE:"); + .hasMessageContaining("writable READ COMMITTED owner transaction"); assertThat( dsl.fetchSingle( "SELECT to_regprocedure(?)", @@ -911,13 +1076,13 @@ void fixturePreparingCannotActivateAcquireHoldsPlaceActorsOrReuseConsumedManifes omitCanonical ? association.worldPrivateKeys().gameInstanceId() : null); selectors.put( "version_id", omitCanonical ? association.worldPrivateKeys().versionId() : null); + // Fixture holds go through the World owner only; a partial raw row is still refused. assertSqlState( () -> dsl.execute( "INSERT INTO initial_admission_bind_hold SELECT (jsonb_populate_record(NULL::initial_admission_bind_hold, ?::jsonb)).*", json(selectors)), - "23514", - "disabled"); + omitCanonical ? "23514" : "23502"); } assertSqlState( () -> @@ -1501,8 +1666,8 @@ public void bindEnd(ExecuteContext context) { .fetch( "SELECT catalog_epoch FROM world_runtime_family_catalog_epoch ORDER BY catalog_epoch") .getValues(0, Long.class)) - .as("V1046 through V1050 install five consecutive catalog epochs") - .containsExactly(1L, 2L, 3L, 4L, 5L); + .as("V1046 through V1050 and V1070 install six consecutive catalog epochs") + .containsExactly(1L, 2L, 3L, 4L, 5L, 6L); assertThat( connection .fetchSingle("SELECT count(*) FROM world_runtime_family_catalog_snapshot") @@ -1529,6 +1694,12 @@ public void bindEnd(ExecuteContext context) { .isNotNull() .isEmpty(); } + assertThat( + retainedRowsAtDefaultFrontierOriginalColumns.remove( + "world_run_owned_fixture_activation")) + .as("new additive V1070 fixture activation table is installed and empty") + .isNotNull() + .isEmpty(); for (String extendedTable : List.of("world_instance", "world_canonical_instance_topology_identity")) { assertThat( @@ -3284,6 +3455,7 @@ private static List remainingVersions() { versions.add("1048"); versions.add("1049"); versions.add("1050"); + versions.add("1070"); return List.copyOf(versions); } diff --git a/services/world-management-service/src/test/java/integration/net/firedevops/firemud/worldmanagement/data/RunOwnedWorldFixtureEvidenceTestFixtures.java b/services/world-management-service/src/test/java/integration/net/firedevops/firemud/worldmanagement/data/RunOwnedWorldFixtureEvidenceTestFixtures.java index 98b4c8a95a..5be4a0124b 100644 --- a/services/world-management-service/src/test/java/integration/net/firedevops/firemud/worldmanagement/data/RunOwnedWorldFixtureEvidenceTestFixtures.java +++ b/services/world-management-service/src/test/java/integration/net/firedevops/firemud/worldmanagement/data/RunOwnedWorldFixtureEvidenceTestFixtures.java @@ -153,7 +153,7 @@ public static RunOwnedCanonicalWorldLaunchEvidence create(ObjectMapper objectMap true, false, "SHARED", - "ALLOW_NEW", + "PRESEEDED_ONLY", "a".repeat(64), RunOwnedInitialAdmissionFixtureWireCodec.GAME_SESSION_URI_SAN, "b".repeat(64), diff --git a/services/world-management-service/src/test/java/integration/net/firedevops/firemud/worldmanagement/service/impl/RunOwnedCanonicalWorldLaunchEvidenceMtlsIntegrationTest.java b/services/world-management-service/src/test/java/integration/net/firedevops/firemud/worldmanagement/service/impl/RunOwnedCanonicalWorldLaunchEvidenceMtlsIntegrationTest.java index cb10dfd07d..551c0b521e 100644 --- a/services/world-management-service/src/test/java/integration/net/firedevops/firemud/worldmanagement/service/impl/RunOwnedCanonicalWorldLaunchEvidenceMtlsIntegrationTest.java +++ b/services/world-management-service/src/test/java/integration/net/firedevops/firemud/worldmanagement/service/impl/RunOwnedCanonicalWorldLaunchEvidenceMtlsIntegrationTest.java @@ -849,7 +849,7 @@ private static AuthoredWorldLaunchDescriptorEvidence descriptorEvidence( private static String capabilityJson(TestPki pki, String operationId, String claimDigest) throws Exception { return """ - {"schema":"firemud.run-owned-initial-admission-fixture.v1","runId":"%s","composeProjectName":"%s","operationId":"%s","tenantId":42,"gameTemplateId":17,"ownerAccountId":9,"worldSlug":"demo","worldDisplayName":"Demo World","realmSlug":"production","realmDisplayName":"Live Realm","visible":true,"publicProductionRealm":true,"requiresCharacterSelection":false,"stateScope":"SHARED","characterCreationPolicy":"ALLOW_NEW","gameSessionLeafSha256":"%s","gameSessionUriSan":"%s","caCertificateSha256":"%s","worldManagementUriSan":"%s","worldManagementLeafSha256":"%s","claimDigest":"%s"}\ + {"schema":"firemud.run-owned-initial-admission-fixture.v1","runId":"%s","composeProjectName":"%s","operationId":"%s","tenantId":42,"gameTemplateId":17,"ownerAccountId":9,"worldSlug":"demo","worldDisplayName":"Demo World","realmSlug":"production","realmDisplayName":"Live Realm","visible":true,"publicProductionRealm":true,"requiresCharacterSelection":false,"stateScope":"SHARED","characterCreationPolicy":"PRESEEDED_ONLY","gameSessionLeafSha256":"%s","gameSessionUriSan":"%s","caCertificateSha256":"%s","worldManagementUriSan":"%s","worldManagementLeafSha256":"%s","claimDigest":"%s"}\ """ .formatted( RUN_ID, diff --git a/services/world-management-service/src/test/java/integration/net/firedevops/firemud/worldmanagement/service/impl/RunOwnedWorldFixtureLifecycleTestFactory.java b/services/world-management-service/src/test/java/integration/net/firedevops/firemud/worldmanagement/service/impl/RunOwnedWorldFixtureLifecycleTestFactory.java index 59b0fe929e..af582e5437 100644 --- a/services/world-management-service/src/test/java/integration/net/firedevops/firemud/worldmanagement/service/impl/RunOwnedWorldFixtureLifecycleTestFactory.java +++ b/services/world-management-service/src/test/java/integration/net/firedevops/firemud/worldmanagement/service/impl/RunOwnedWorldFixtureLifecycleTestFactory.java @@ -26,6 +26,7 @@ import net.firedevops.firemud.worldmanagement.tenant.WorldCanonicalInstanceAssociationRepository; import net.firedevops.firemud.worldmanagement.tenant.WorldCompleteLaunchBindingRepository; import net.firedevops.firemud.worldmanagement.tenant.WorldDesignPublicationFenceRepository; +import net.firedevops.firemud.worldmanagement.tenant.WorldRuntimeInstallationRegistry; import org.jooq.DSLContext; import org.springframework.transaction.PlatformTransactionManager; import org.springframework.transaction.TransactionDefinition; @@ -93,4 +94,16 @@ public static WorldInstanceLifecycleSnapshotDto prepare( return service.prepareRunOwnedFixture( RunOwnedWorldFixtureEvidenceTestFixtures.request(evidence), evidence); } + + /** Canonical fixture activation through the owner path with an explicit installation. */ + public static WorldInstanceLifecycleSnapshotDto activate( + WorldLifecycleCommandServiceImpl service, + RunOwnedCanonicalWorldLaunchEvidence evidence, + WorldRuntimeInstallationRegistry installation, + long expectedLifecycleEpoch) { + service.setRuntimeInstallationRegistry(installation); + var request = RunOwnedWorldFixtureEvidenceTestFixtures.request(evidence); + return service.activateRunOwnedFixture( + request.tenantId(), request.gameInstanceId(), expectedLifecycleEpoch, evidence); + } } diff --git a/services/world-management-service/src/test/java/integration/net/firedevops/firemud/worldmanagement/tenant/WorldGraphApplicationReceiptDigestPostgresIntegrationTest.java b/services/world-management-service/src/test/java/integration/net/firedevops/firemud/worldmanagement/tenant/WorldGraphApplicationReceiptDigestPostgresIntegrationTest.java index 314ae18205..2e4103ee41 100644 --- a/services/world-management-service/src/test/java/integration/net/firedevops/firemud/worldmanagement/tenant/WorldGraphApplicationReceiptDigestPostgresIntegrationTest.java +++ b/services/world-management-service/src/test/java/integration/net/firedevops/firemud/worldmanagement/tenant/WorldGraphApplicationReceiptDigestPostgresIntegrationTest.java @@ -195,7 +195,7 @@ void forwardMigrationBindsSemanticReceiptDigestOnFreshAndUpgradedSchemas() throw assertThat(fresh.info().pending()).isEmpty(); // Predicate-only CTAS clones deliberately lack real owner keys. Keep this controlled - // probe at its catalog frontier; fresh and upgraded real schemas advance through V1050. + // probe at its catalog frontier; fresh and upgraded real schemas advance through V1070. Flyway probeCurrent = flyway( probeSource, @@ -207,7 +207,7 @@ void forwardMigrationBindsSemanticReceiptDigestOnFreshAndUpgradedSchemas() throw probeCurrent.validate(); assertThat(probeCurrent.info().pending()).isEmpty(); - assertThat(latestVersion(upgradeDsl)).isEqualTo("1050"); + assertThat(latestVersion(upgradeDsl)).isEqualTo("1070"); assertThat(latestVersion(freshDsl)).isEqualTo(latestVersion(upgradeDsl)); assertThat(latestVersion(probeDsl)).isEqualTo("1048"); assertThat(migrationHistory(upgradeDsl, "1012")).isEqualTo(history1012Before); diff --git a/services/world-management-service/src/test/java/integration/net/firedevops/firemud/worldmanagement/tenant/WorldPrivateFreshOperationPostgresIntegrationTest.java b/services/world-management-service/src/test/java/integration/net/firedevops/firemud/worldmanagement/tenant/WorldPrivateFreshOperationPostgresIntegrationTest.java index 630e7cd28b..787347746e 100644 --- a/services/world-management-service/src/test/java/integration/net/firedevops/firemud/worldmanagement/tenant/WorldPrivateFreshOperationPostgresIntegrationTest.java +++ b/services/world-management-service/src/test/java/integration/net/firedevops/firemud/worldmanagement/tenant/WorldPrivateFreshOperationPostgresIntegrationTest.java @@ -214,7 +214,7 @@ void abortIsAppendOnlyExactReplayAndCannotBecomeMaterialized() throws Exception assertThat( f.dsl .fetch( - "SELECT to_jsonb(h)::TEXT||':'||xmin::TEXT value FROM flyway_schema_history_world_management_service h WHERE version IS DISTINCT FROM '1050' ORDER BY installed_rank") + "SELECT to_jsonb(h)::TEXT||':'||xmin::TEXT value FROM flyway_schema_history_world_management_service h WHERE version IS DISTINCT FROM '1050' AND version IS DISTINCT FROM '1070' ORDER BY installed_rank") .getValues(0, String.class)) .isEqualTo(history); assertThat( @@ -392,7 +392,7 @@ void forwardUpgradeRetainsCatalogHistoryAndAddsLivePrivateFamiliesWithoutPayload assertThat( f.dsl .fetch( - "SELECT to_jsonb(h)::TEXT||':'||xmin::TEXT value FROM flyway_schema_history_world_management_service h WHERE version IS DISTINCT FROM '1049' AND version IS DISTINCT FROM '1050' ORDER BY installed_rank") + "SELECT to_jsonb(h)::TEXT||':'||xmin::TEXT value FROM flyway_schema_history_world_management_service h WHERE version IS DISTINCT FROM '1049' AND version IS DISTINCT FROM '1050' AND version IS DISTINCT FROM '1070' ORDER BY installed_rank") .getValues(0, String.class)) .isEqualTo(history); assertThatThrownBy(() -> oldOwner.readExact(oldSnapshot.request())) @@ -401,7 +401,7 @@ void forwardUpgradeRetainsCatalogHistoryAndAddsLivePrivateFamiliesWithoutPayload new WorldRuntimeFamilyCatalogRepository(f.dsl, f.manager, f.schema, NS) .read(new WorldRuntimeFamilyCatalog.Request(UUID.randomUUID(), NS)) .catalog(); - assertThat(catalog.catalogEpoch()).isEqualTo(5); + assertThat(catalog.catalogEpoch()).isEqualTo(6); assertThat(catalog.families()) .extracting(WorldRuntimeFamilyCatalog.Family::familyId) .contains( @@ -412,7 +412,7 @@ void forwardUpgradeRetainsCatalogHistoryAndAddsLivePrivateFamiliesWithoutPayload assertThat( f.dsl .fetchSingle( - "SELECT catalog_bytes=world_runtime_family_catalog_bytes(catalog_epoch) FROM world_runtime_family_catalog_epoch WHERE catalog_epoch=5") + "SELECT catalog_bytes=world_runtime_family_catalog_bytes(catalog_epoch) FROM world_runtime_family_catalog_epoch WHERE catalog_epoch=6") .get(0, Boolean.class)) .isTrue(); assertThat(f.count("world_private_fresh_operation")).isZero(); diff --git a/services/world-management-service/src/test/java/integration/net/firedevops/firemud/worldmanagement/tenant/WorldRuntimeFamilyCatalogPostgresIntegrationTest.java b/services/world-management-service/src/test/java/integration/net/firedevops/firemud/worldmanagement/tenant/WorldRuntimeFamilyCatalogPostgresIntegrationTest.java index 6bef591ca7..1bede88602 100644 --- a/services/world-management-service/src/test/java/integration/net/firedevops/firemud/worldmanagement/tenant/WorldRuntimeFamilyCatalogPostgresIntegrationTest.java +++ b/services/world-management-service/src/test/java/integration/net/firedevops/firemud/worldmanagement/tenant/WorldRuntimeFamilyCatalogPostgresIntegrationTest.java @@ -75,7 +75,7 @@ void actualCompleteCurrentCensusIncludesEmptyRuntimeAndNonPayloadFamilies() thro try (Fixture f = fixture(null)) { var evidence = f.owner().read(request()); var catalog = evidence.catalog(); - assertThat(catalog.catalogEpoch()).isEqualTo(5); + assertThat(catalog.catalogEpoch()).isEqualTo(6); assertThat( catalog.schemaFacts().stream() .filter(fact -> fact.kind() == FactKind.TABLE) @@ -207,7 +207,7 @@ void additiveForwardMigrationRetainsLegacyPayloadAndPriorMigrationHistoryExactly assertThat( f.dsl .fetch( - "SELECT to_jsonb(h)::text FROM flyway_schema_history_world_management_service h WHERE version IS DISTINCT FROM '1046' AND version IS DISTINCT FROM '1047' AND version IS DISTINCT FROM '1048' AND version IS DISTINCT FROM '1049' AND version IS DISTINCT FROM '1050' ORDER BY installed_rank") + "SELECT to_jsonb(h)::text FROM flyway_schema_history_world_management_service h WHERE version IS DISTINCT FROM '1046' AND version IS DISTINCT FROM '1047' AND version IS DISTINCT FROM '1048' AND version IS DISTINCT FROM '1049' AND version IS DISTINCT FROM '1050' AND version IS DISTINCT FROM '1070' ORDER BY installed_rank") .getValues(0, String.class)) .isEqualTo(historyBefore); f.owner().read(request()); @@ -316,7 +316,7 @@ void installedViewAndMaterializedViewOptionsInvalidateTheSealWithoutResampling() migration(f.source, f.schema, null).migrate(); Request read = request(); var original = f.owner().read(read); - assertThat(original.catalog().catalogEpoch()).isEqualTo(5); + assertThat(original.catalog().catalogEpoch()).isEqualTo(6); assertThat(original.catalog().schemaFacts()) .anyMatch( fact -> @@ -368,7 +368,7 @@ void removalAndClassificationChangeAreExplicitlyInvalidating() throws Exception .isInstanceOf(WorldRuntimeFamilyCatalogRepository.CatalogConflictException.class); assertThatThrownBy(() -> f.owner().read(request())) .isInstanceOf(WorldRuntimeFamilyCatalogRepository.CatalogConflictException.class); - assertThat(f.count("world_runtime_family_catalog_epoch")).isEqualTo(5); + assertThat(f.count("world_runtime_family_catalog_epoch")).isEqualTo(6); } } @@ -396,7 +396,7 @@ void oldMigrationFactChangeInvalidatesTheSealAndMissingOwnerEpochNeverMeansCompl void directSnapshotInsertRequiresBothSuccessfulExactCatalogMigrationRows() throws Exception { try (Fixture f = fixture(null)) { var catalog = f.owner().read(request()).catalog(); - for (String version : List.of("1046", "1047", "1048", "1049", "1050")) { + for (String version : List.of("1046", "1047", "1048", "1049", "1050", "1070")) { for (String column : List.of("success", "script")) { Request read = request(); var evidence = new Evidence(read, UUID.randomUUID(), catalog); @@ -549,8 +549,8 @@ void explicitOwnerEpochAdvanceInvalidatesOldRequestsWithoutRewritingTheirEvidenc + " ('region_instance.name','region_instance','name','RUNTIME_PAYLOAD','S3','REQUIRED_TOPOLOGY')"); f.dsl.execute( "INSERT INTO world_runtime_family_catalog_epoch(catalog_epoch,catalog_bytes,catalog_digest)" - + " SELECT 6,bytes,'sha256:'||encode(sha256(bytes),'hex') FROM" - + " (SELECT world_runtime_family_catalog_bytes(6) AS bytes) revised"); + + " SELECT 7,bytes,'sha256:'||encode(sha256(bytes),'hex') FROM" + + " (SELECT world_runtime_family_catalog_bytes(7) AS bytes) revised"); assertThatThrownBy(() -> f.owner().readExact(read)) .isInstanceOf(WorldRuntimeFamilyCatalogRepository.CatalogConflictException.class); assertThatThrownBy(() -> f.owner().read(read)) @@ -563,9 +563,9 @@ void explicitOwnerEpochAdvanceInvalidatesOldRequestsWithoutRewritingTheirEvidenc .get(0, byte[].class)) .isEqualTo(WorldRuntimeFamilyCatalogCodec.evidenceBytes(original)); var revised = f.owner().read(request()); - assertThat(revised.catalog().catalogEpoch()).isEqualTo(6); + assertThat(revised.catalog().catalogEpoch()).isEqualTo(7); assertThat(revised.catalog().digest()).isNotEqualTo(original.catalog().digest()); - assertThat(f.count("world_runtime_family_catalog_epoch")).isEqualTo(6); + assertThat(f.count("world_runtime_family_catalog_epoch")).isEqualTo(7); } } diff --git a/services/world-management-service/src/test/java/unit/net/firedevops/firemud/worldmanagement/data/RunOwnedCanonicalWorldLaunchEvidenceTestFixtures.java b/services/world-management-service/src/test/java/unit/net/firedevops/firemud/worldmanagement/data/RunOwnedCanonicalWorldLaunchEvidenceTestFixtures.java index 30fa5e7de3..c5563b0a8b 100644 --- a/services/world-management-service/src/test/java/unit/net/firedevops/firemud/worldmanagement/data/RunOwnedCanonicalWorldLaunchEvidenceTestFixtures.java +++ b/services/world-management-service/src/test/java/unit/net/firedevops/firemud/worldmanagement/data/RunOwnedCanonicalWorldLaunchEvidenceTestFixtures.java @@ -184,7 +184,7 @@ static RunOwnedCanonicalWorldLaunchEvidence create( true, false, "SHARED", - "ALLOW_NEW", + "PRESEEDED_ONLY", gameSessionLeafSha256, RunOwnedInitialAdmissionFixtureWireCodec.GAME_SESSION_URI_SAN, caCertificateSha256, diff --git a/services/world-management-service/src/test/java/unit/net/firedevops/firemud/worldmanagement/data/RunOwnedWorldLaunchEvidenceProviderTest.java b/services/world-management-service/src/test/java/unit/net/firedevops/firemud/worldmanagement/data/RunOwnedWorldLaunchEvidenceProviderTest.java index 05f602cc9d..ce866de1e2 100644 --- a/services/world-management-service/src/test/java/unit/net/firedevops/firemud/worldmanagement/data/RunOwnedWorldLaunchEvidenceProviderTest.java +++ b/services/world-management-service/src/test/java/unit/net/firedevops/firemud/worldmanagement/data/RunOwnedWorldLaunchEvidenceProviderTest.java @@ -338,7 +338,7 @@ private static RunOwnedWorldLaunchEvidence fixtureEvidence() { true, false, "SHARED", - "ALLOW_NEW", + "PRESEEDED_ONLY", "a".repeat(64), RunOwnedInitialAdmissionFixtureWireCodec.GAME_SESSION_URI_SAN, "b".repeat(64), diff --git a/services/world-management-service/src/test/java/unit/net/firedevops/firemud/worldmanagement/tenant/WorldCanonicalInstanceLifecycleReadGrpcServiceTest.java b/services/world-management-service/src/test/java/unit/net/firedevops/firemud/worldmanagement/tenant/WorldCanonicalInstanceLifecycleReadGrpcServiceTest.java index b1cf53af57..3a95485164 100644 --- a/services/world-management-service/src/test/java/unit/net/firedevops/firemud/worldmanagement/tenant/WorldCanonicalInstanceLifecycleReadGrpcServiceTest.java +++ b/services/world-management-service/src/test/java/unit/net/firedevops/firemud/worldmanagement/tenant/WorldCanonicalInstanceLifecycleReadGrpcServiceTest.java @@ -19,8 +19,11 @@ import net.firedevops.firemud.common.security.SessionContext; import net.firedevops.firemud.common.world.WorldCanonicalInstanceLifecycleEvidence; import net.firedevops.firemud.common.world.WorldCanonicalInstanceLifecycleGrpcCodec; +import net.firedevops.firemud.common.world.WorldRunOwnedFixtureLifecycleEvidence; import net.firedevops.firemud.worldmanagement.tenant.WorldCanonicalInstanceLifecycleReadGrpcService; import net.firedevops.firemud.worldmanagement.tenant.WorldCanonicalInstanceLifecycleReadRepository; +import net.firedevops.firemud.worldmanagement.v1.ReadRunOwnedFixtureStartRoomRequest; +import net.firedevops.firemud.worldmanagement.v1.ReadRunOwnedFixtureStartRoomResponse; import net.firedevops.firemud.worldmanagement.v1.ReadWorldCanonicalInstanceLifecycleRequest; import net.firedevops.firemud.worldmanagement.v1.ReadWorldCanonicalInstanceLifecycleResponse; import org.junit.jupiter.api.Test; @@ -34,14 +37,14 @@ void rejectsActualOrSynchronizationTransactionBeforeParsingOrOwnerAccess() { var repository = mock(WorldCanonicalInstanceLifecycleReadRepository.class); var service = new WorldCanonicalInstanceLifecycleReadGrpcService(repository, "test"); var malformed = ReadWorldCanonicalInstanceLifecycleRequest.getDefaultInstance(); - Collector actual; + Collector actual; TransactionSynchronizationManager.setActualTransactionActive(true); try { actual = call(service, malformed, peer("game-session-service", "test")); } finally { TransactionSynchronizationManager.setActualTransactionActive(false); } - Collector synchronization; + Collector synchronization; TransactionSynchronizationManager.initSynchronization(); try { synchronization = call(service, malformed, peer("game-session-service", "test")); @@ -62,9 +65,9 @@ void rejectsWrongServiceOrNamespaceBeforeDecodingAndStorageAccess() { .setCanonicalRequestBytes(ByteString.copyFromUtf8("not-json")) .build(); - Collector wrongService = call(service, malformed, peer("account-service", "test")); - Collector wrongNamespace = call(service, malformed, peer("game-session-service", "other")); - Collector wrongRequestNamespace = + var wrongService = call(service, malformed, peer("account-service", "test")); + var wrongNamespace = call(service, malformed, peer("game-session-service", "other")); + var wrongRequestNamespace = call( service, WorldCanonicalInstanceLifecycleGrpcCodec.toRequest(request("other")), @@ -80,7 +83,7 @@ void rejectsMissingPeerIdentityAsUnauthenticatedBeforeStorageAccess() { var repository = mock(WorldCanonicalInstanceLifecycleReadRepository.class); var service = new WorldCanonicalInstanceLifecycleReadGrpcService(repository, "test"); - Collector result = + var result = call(service, ReadWorldCanonicalInstanceLifecycleRequest.getDefaultInstance(), null); assertThat(result.error).isEqualTo(Status.Code.UNAUTHENTICATED); @@ -92,7 +95,7 @@ void rejectsAuthenticatedEndUserContextBeforeDecodingOrStorageAccess() { var repository = mock(WorldCanonicalInstanceLifecycleReadRepository.class); var service = new WorldCanonicalInstanceLifecycleReadGrpcService(repository, "test"); SessionContext.setContext("11111111-1111-4111-8111-111111111111", List.of(), Map.of()); - Collector result; + Collector result; try { result = call( @@ -113,7 +116,7 @@ void exactSameNamespaceGameSessionPeerReachesOnlyExactLifecycleRequest() { var read = request("test"); when(repository.read(read)).thenReturn(Optional.empty()); - Collector result = + var result = call( service, WorldCanonicalInstanceLifecycleGrpcCodec.toRequest(read), @@ -131,7 +134,7 @@ void mapsSpringResourceFailureToUnavailableWithoutLeakingStorageDetails() { when(repository.read(read)) .thenThrow(new DataAccessResourceFailureException("private storage detail")); - Collector result = + var result = call( service, WorldCanonicalInstanceLifecycleGrpcCodec.toRequest(read), @@ -150,7 +153,7 @@ void mapsTransactionCreationFailureToUnavailableWithoutLeakingStorageDetails() { when(repository.read(read)) .thenThrow(new CannotCreateTransactionException("private transaction detail")); - Collector result = + var result = call( service, WorldCanonicalInstanceLifecycleGrpcCodec.toRequest(read), @@ -178,7 +181,7 @@ void classifiesJooqAndSpringStorageFailuresAtTheLifecycleRpcBoundary() { var read = request("test"); when(repository.read(read)).thenThrow(failure.failure); - Collector result = + var result = call( service, WorldCanonicalInstanceLifecycleGrpcCodec.toRequest(read), @@ -198,7 +201,7 @@ void mapsNonSqlTooManyRowsToFailedPreconditionWithoutLeakingDetails() { when(repository.read(read)) .thenThrow(new org.jooq.exception.TooManyRowsException("private duplicate evidence")); - Collector result = + var result = call( service, WorldCanonicalInstanceLifecycleGrpcCodec.toRequest(read), @@ -218,17 +221,62 @@ void authenticatedPeerWithMalformedRequestFailsBeforeStorageAccess() { .setCanonicalRequestBytes(ByteString.copyFromUtf8("not-json")) .build(); - Collector result = call(service, malformed, peer("game-session-service", "test")); + var result = call(service, malformed, peer("game-session-service", "test")); assertThat(result.error).isEqualTo(Status.Code.INVALID_ARGUMENT); verifyNoInteractions(repository); } - private static Collector call( + @Test + void fixtureStartRoomRequiresTheExactGameSessionPeerAndReturnsTheOwnerRoom() { + var repository = mock(WorldCanonicalInstanceLifecycleReadRepository.class); + var service = new WorldCanonicalInstanceLifecycleReadGrpcService(repository, "test"); + var read = request("test"); + var request = + ReadRunOwnedFixtureStartRoomRequest.newBuilder() + .setLifecycle(WorldCanonicalInstanceLifecycleGrpcCodec.toRequest(read)) + .build(); + + var rejected = new Collector(); + Context.current() + .withValue(GrpcPeerIdentity.CONTEXT_KEY, peer("game-logic-service", "test")) + .run(() -> service.readRunOwnedFixtureStartRoom(request, rejected)); + assertThat(rejected.error).isEqualTo(Status.Code.PERMISSION_DENIED); + verifyNoInteractions(repository); + + var evidence = + new WorldRunOwnedFixtureLifecycleEvidence( + read, + read.expectedReleaseAttestationDigest(), + "sha256:" + "e".repeat(64), + "ACTIVE", + 3, + 4); + when(repository.readRunOwnedFixtureStartRoom(read)) + .thenReturn( + Optional.of( + new WorldCanonicalInstanceLifecycleReadRepository.FixtureStartRoom( + evidence, "R-37"))); + var admitted = new Collector(); + Context.current() + .withValue(GrpcPeerIdentity.CONTEXT_KEY, peer("game-session-service", "test")) + .run(() -> service.readRunOwnedFixtureStartRoom(request, admitted)); + + assertThat(admitted.error).isNull(); + assertThat(admitted.completed).isTrue(); + assertThat(admitted.value.getRoomInstanceKey()).isEqualTo("R-37"); + assertThat( + WorldCanonicalInstanceLifecycleGrpcCodec.fromFixtureResponse( + read, admitted.value.getLifecycle())) + .isEqualTo(evidence); + verify(repository).readRunOwnedFixtureStartRoom(read); + } + + private static Collector call( WorldCanonicalInstanceLifecycleReadGrpcService service, ReadWorldCanonicalInstanceLifecycleRequest request, GrpcPeerIdentity peer) { - Collector response = new Collector(); + var response = new Collector(); Context context = peer == null ? Context.ROOT @@ -277,15 +325,14 @@ private static org.springframework.dao.DataAccessException springFailure(String private record StorageFailureCase(Throwable failure, Status.Code expectedCode) {} - private static final class Collector - implements StreamObserver { - private ReadWorldCanonicalInstanceLifecycleResponse value; + private static final class Collector implements StreamObserver { + private T value; private Status.Code error; private String description; private boolean completed; @Override - public void onNext(ReadWorldCanonicalInstanceLifecycleResponse response) { + public void onNext(T response) { value = response; }