From ea703d2e09b046103f4dd4aa495416e09a3fe14f Mon Sep 17 00:00:00 2001 From: Ben Hook <5009589+benhook1013@users.noreply.github.com> Date: Fri, 2 Oct 2026 19:43:26 +1300 Subject: [PATCH 01/20] feat: add durable owner-fenced initial admission foundation --- .../game-session-service/api-contracts.md | 8 + .../world-management-service/api-contracts.md | 14 + .../runtime-and-data.md | 8 + .../system-architecture-multi-tenancy.md | 1 + ...e-session-runtime-and-tick-coordination.md | 2 + .../world-runtime-and-movement.md | 2 + dev-tools/certs/README.md | 2 +- dev-tools/certs/ensure-dev-certs.sh | 4 +- dev-tools/tests/compose-grpc-mtls-contract.sh | 25 +- docker/docker-compose.grpc-mtls.override.yml | 7 +- .../v1/game_session_service.proto | 11 + .../v1/world_management_service.proto | 48 ++ .../command/text/GameplayWorldCatalog.java | 374 ++++++++- ...ayAdmissionPointerBootstrapProperties.java | 7 +- ...yAdmissionPointerBootstrapInitializer.java | 135 ++-- .../entity/GameplayAdmissionPointer.java | 4 + .../entity/GameplayAdmissionPointerEvent.java | 4 + .../entity/InitialAdmissionBindAttempt.java | 33 + .../entity/InitialAdmissionBindCatalog.java | 22 + ...meplayAdmissionPointerEventRepository.java | 12 + .../GameplayAdmissionPointerRepository.java | 99 ++- ...InitialAdmissionBindAttemptRepository.java | 298 +++++++ ...InitialAdmissionBindCatalogRepository.java | 133 +++ .../GameplayAdmissionPointerSnapshot.java | 70 +- ...InitialAdmissionBindCatalogDescriptor.java | 16 + .../InitialAdmissionBindHoldBinding.java | 17 + .../InitialAdmissionBindOwnerProof.java | 32 + .../InitialAdmissionBindOwnerProofReader.java | 6 + .../InitialAdmissionBindOwnerService.java | 18 + .../service/InitialAdmissionBindRequest.java | 12 + ...eplayAdmissionPointerAuthorityService.java | 59 +- ...abaseInitialAdmissionBindOwnerService.java | 654 +++++++++++++++ ...onAdmissionPointerControlPlaneService.java | 62 +- .../GameSessionControlPlaneGrpcService.java | 15 + .../service/impl/GameSessionGrpcService.java | 116 ++- ...SessionRuntimeControlPlaneReadService.java | 39 +- .../src/main/resources/application.yml | 2 +- ...V5__separate_gameplay_catalog_revision.sql | 4 + .../V6__persist_gameplay_realm_identity.sql | 74 ++ .../V7__audit_gameplay_catalog_revision.sql | 8 + ...8__initial_admission_bind_owner_ledger.sql | 103 +++ ...issionPointerMigrationIntegrationTest.java | 326 ++++++++ ...lAdmissionBindPostgresIntegrationTest.java | 170 ++++ .../text/GameplayWorldCatalogTest.java | 346 +++++++- ...issionPointerBootstrapInitializerTest.java | 235 ++++-- ...ayAdmissionPointerEventRepositoryTest.java | 106 +++ ...ameplayAdmissionPointerRepositoryTest.java | 214 +++++ ...yAdmissionPointerAuthorityServiceTest.java | 99 +++ ...ameSessionControlPlaneGrpcServiceTest.java | 309 ++----- .../impl/GameSessionGrpcServiceTest.java | 761 +++++++++++++++++- ...ionRuntimeControlPlaneReadServiceTest.java | 148 +++- .../impl/InitialAdmissionBindServiceTest.java | 305 +++++++ ...essionInitialAdmissionBindProofClient.java | 9 + .../dto/InitialAdmissionBindHoldDto.java | 20 + .../dto/InitialAdmissionBindHoldRequest.java | 14 + .../dto/InitialAdmissionBindOwnerProof.java | 33 + .../entity/InitialAdmissionBindHold.java | 29 + .../InitialAdmissionBindHoldRepository.java | 236 ++++++ .../repository/WorldInstanceRepository.java | 23 + .../InitialAdmissionBindHoldService.java | 14 + .../InitialAdmissionBindHoldReconciler.java | 74 ++ .../InitialAdmissionBindHoldServiceImpl.java | 450 +++++++++++ .../InitialAdmissionBindWorkloadGuard.java | 31 + .../WorldLifecycleCommandServiceImpl.java | 74 +- .../impl/WorldManagementGrpcService.java | 122 +++ .../V23__initial_admission_bind_hold.sql | 69 ++ ...issionBindHoldPostgresIntegrationTest.java | 248 ++++++ ...itialAdmissionBindHoldServiceImplTest.java | 411 ++++++++++ .../WorldLifecycleCommandServiceImplTest.java | 39 + .../impl/WorldManagementGrpcServiceTest.java | 172 ++++ 70 files changed, 7129 insertions(+), 518 deletions(-) create mode 100644 services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/entity/InitialAdmissionBindAttempt.java create mode 100644 services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/entity/InitialAdmissionBindCatalog.java create mode 100644 services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/repository/InitialAdmissionBindAttemptRepository.java create mode 100644 services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/repository/InitialAdmissionBindCatalogRepository.java create mode 100644 services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/service/InitialAdmissionBindCatalogDescriptor.java create mode 100644 services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/service/InitialAdmissionBindHoldBinding.java create mode 100644 services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/service/InitialAdmissionBindOwnerProof.java create mode 100644 services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/service/InitialAdmissionBindOwnerProofReader.java create mode 100644 services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/service/InitialAdmissionBindOwnerService.java create mode 100644 services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/service/InitialAdmissionBindRequest.java create mode 100644 services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/service/impl/DatabaseInitialAdmissionBindOwnerService.java create mode 100644 services/game-session-service/src/main/resources/db/migration/V5__separate_gameplay_catalog_revision.sql create mode 100644 services/game-session-service/src/main/resources/db/migration/V6__persist_gameplay_realm_identity.sql create mode 100644 services/game-session-service/src/main/resources/db/migration/V7__audit_gameplay_catalog_revision.sql create mode 100644 services/game-session-service/src/main/resources/db/migration/V8__initial_admission_bind_owner_ledger.sql create mode 100644 services/game-session-service/src/test/java/integration/net/firedevops/firemud/gamesession/repository/GameplayAdmissionPointerMigrationIntegrationTest.java create mode 100644 services/game-session-service/src/test/java/integration/net/firedevops/firemud/gamesession/service/InitialAdmissionBindPostgresIntegrationTest.java create mode 100644 services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/repository/GameplayAdmissionPointerEventRepositoryTest.java create mode 100644 services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/repository/GameplayAdmissionPointerRepositoryTest.java create mode 100644 services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/service/impl/InitialAdmissionBindServiceTest.java create mode 100644 services/world-management-service/src/main/java/net/firedevops/firemud/worldmanagement/client/GameSessionInitialAdmissionBindProofClient.java create mode 100644 services/world-management-service/src/main/java/net/firedevops/firemud/worldmanagement/dto/InitialAdmissionBindHoldDto.java create mode 100644 services/world-management-service/src/main/java/net/firedevops/firemud/worldmanagement/dto/InitialAdmissionBindHoldRequest.java create mode 100644 services/world-management-service/src/main/java/net/firedevops/firemud/worldmanagement/dto/InitialAdmissionBindOwnerProof.java create mode 100644 services/world-management-service/src/main/java/net/firedevops/firemud/worldmanagement/entity/InitialAdmissionBindHold.java create mode 100644 services/world-management-service/src/main/java/net/firedevops/firemud/worldmanagement/repository/InitialAdmissionBindHoldRepository.java create mode 100644 services/world-management-service/src/main/java/net/firedevops/firemud/worldmanagement/service/InitialAdmissionBindHoldService.java create mode 100644 services/world-management-service/src/main/java/net/firedevops/firemud/worldmanagement/service/impl/InitialAdmissionBindHoldReconciler.java create mode 100644 services/world-management-service/src/main/java/net/firedevops/firemud/worldmanagement/service/impl/InitialAdmissionBindHoldServiceImpl.java create mode 100644 services/world-management-service/src/main/java/net/firedevops/firemud/worldmanagement/service/impl/InitialAdmissionBindWorkloadGuard.java create mode 100644 services/world-management-service/src/main/resources/db/migration/V23__initial_admission_bind_hold.sql create mode 100644 services/world-management-service/src/test/java/integration/net/firedevops/firemud/worldmanagement/InitialAdmissionBindHoldPostgresIntegrationTest.java create mode 100644 services/world-management-service/src/test/java/unit/net/firedevops/firemud/worldmanagement/service/impl/InitialAdmissionBindHoldServiceImplTest.java diff --git a/design/architecture/microservices/game-session-service/api-contracts.md b/design/architecture/microservices/game-session-service/api-contracts.md index 107049f91b..477970bf8c 100644 --- a/design/architecture/microservices/game-session-service/api-contracts.md +++ b/design/architecture/microservices/game-session-service/api-contracts.md @@ -46,6 +46,14 @@ After World proves the target `ACTIVE`, it acquires one durable, opaque cutover Lost responses reconcile through the exact hold identity and authoritative World/Game Session reads. Game Session may request an abort only when owner evidence proves that its pointer transaction did not commit and the prior pointer remains authoritative; contradictory or unavailable evidence remains `RECONCILIATION_REQUIRED` and cannot be treated as a failed cutover or permit termination. The hold's World-owned `expiresAt` is diagnostic/repair input only and never auto-releases it. The current Game Session wire, durable transaction, and focused proof do not yet carry or prove this hold binding; see the [World cutover hold contract](../world-management-service/api-contracts.md#replacement-cutover-hold-contract). +### Initial admission bind + +The first admission-pointer bind for a realm is a separate owner transaction from replacement cutover. Game Session owns a durable attempt ledger with one stable request identity and canonical digest, plus the terminal outcome `COMMITTED` or `ABORTED`. Its initial pointer transaction must prove that no pointer exists for the exact `{tenantId, realmId}` and atomically bind the World-issued initial-bind hold identity/fence, the same request identity/digest, `{tenantId, realmId, playableStateNamespaceId, playableStateScope}`, target `gameInstanceId`/`versionId` and exact `ACTIVE` lifecycle epoch, and `catalogRevision` with the new pointer and matching append-only audit event. The durable `COMMITTED` attempt outcome commits in that same transaction. This owner-side no-prior-pointer check is not replaced by a bootstrap snapshot, startup configuration, public raw-pointer RPC, or external operator write bypass. + +An exact retry or post-restart recovery reuses the same attempt and hold identities and reconciles the durable attempt, pointer, and audit. Game Session may record `ABORTED` only as a durable terminal outcome that prevents any later commit for that same attempt. World may accept that exact, authenticated owner-readback outcome bound to the same hold and tuple as abort proof; pointer absence, `NOT_FOUND`, `PENDING`, unavailable reads, mismatched tuple/audit, or contradictory evidence is not proof. World finalization requires an authenticated exact Game Session owner readback of the same hold and request identity/digest, tuple, committed pointer, matching audit, and `COMMITTED` outcome. Ambiguous results remain termination-fenced while automatic reconciliation retries; elapsed time does not release the World hold. See the World-owned [initial admission bind hold contract](../world-management-service/api-contracts.md#initial-admission-bind-hold-contract). + +The current Game Session foundation includes local durable catalog/intent, pointer/audit, and commit/abort proof components. Focused local owner-ledger tests pass and PostgreSQL integration tests compile, but live database race/restart proof remains unavailable. The authenticated owner-read adapter, fixture delivery/coordinator, and durable `StartSession` retry integration are not wired. There is no startup autoactivation or new fixture ingress, and ambiguous outcomes continue to fence World termination. The existing cutover transaction and [replacement hold contract](../world-management-service/api-contracts.md#replacement-cutover-hold-contract) remain distinct; the canonical initial-bind contract is owned by [World](../world-management-service/api-contracts.md#initial-admission-bind-hold-contract). + ## Session Front-End and Lease-Owner Routing Game Session deliberately separates socket ownership from region execution ownership: diff --git a/design/architecture/microservices/world-management-service/api-contracts.md b/design/architecture/microservices/world-management-service/api-contracts.md index 6d80432f1d..30233245d8 100644 --- a/design/architecture/microservices/world-management-service/api-contracts.md +++ b/design/architecture/microservices/world-management-service/api-contracts.md @@ -257,6 +257,20 @@ Game Session must bind `cutoverHoldId`, `cutoverHoldFence`, the exact `playableS The authoritative `expiresAt` is a diagnostic and repair trigger only. Expiry never auto-releases an unresolved hold, and no operator bypass or numeric TTL policy is implied. The current service lacks the hold table/state, coordinated acquire/finalize RPC or wire fields, owner-read reconciliation, termination predicate, and focused runtime proof; this documentation-only parcel does not add or claim those artifacts, which remain required target implementation and proof work. +## Initial Admission Bind Hold Contract + +World Management owns a separate durable one-shot hold for the first admission-pointer bind of an already active realm runtime. It closes the race between proving the target `ACTIVE` and Game Session committing the realm's first admission pointer. It is not a replacement cutover hold, does not add a `world_instance` lifecycle state, and does not make the initial bind a distributed transaction. The normal termination request identity, frozen owner set and registry revision, idempotent cleanup acknowledgements, and final lifecycle compare-and-set remain required after the hold is safely resolved. + +One initial-bind execution records one stable control-plane request identity and canonical request digest, one opaque hold identity and equality-only World fence, and the exact `{tenantId, realmId, playableStateNamespaceId, playableStateScope}` binding, the initial no-prior-pointer condition, target `gameInstanceId` and `versionId`, exact target `ACTIVE` lifecycle epoch, and `catalogRevision`. The canonical digest binds the immutable request and realm-target tuple. Exact acquire, read, finalize, abort-proof, and reconciliation retries reuse that identity and fence; a conflicting request cannot silently reuse or replace the hold. The initial-bind condition is distinct from replacement's expected prior pointer/version and does not authorize replacing an existing pointer. + +World acquires the hold in its own database transaction by serializing on the target lifecycle row, checking the exact `ACTIVE` state and epoch, and rejecting a conflicting nonterminal hold. It does not make remote Game Session or catalog reads inside that transaction. Every termination compare-and-set for the target instance, whether initiated by ordinary shutdown or another lifecycle path, must honor absence of a nonterminal initial-bind or replacement hold under the same database serialization. While either hold is nonterminal, termination remains pending and retryable and cannot advance the lifecycle epoch. Once the initial hold is finalized or safely aborted, the existing termination and all-owner cleanup contract continues unchanged. + +Game Session owns the initial-bind attempt outcome and the admission pointer. It may create the first pointer only when its local transaction proves that no pointer previously existed for the exact `{tenantId, realmId}` and binds the same hold identity/fence, request identity/digest, namespace/scope, target instance/`versionId`, `ACTIVE` epoch, and `catalogRevision`. That transaction atomically commits the pointer, its matching append-only audit event, and the durable attempt outcome `COMMITTED`. Startup configuration, an admission snapshot, a public raw-pointer RPC, or an external operator write bypass is not lifecycle authority and cannot substitute for this owner transaction. + +World finalizes only after an authenticated exact Game Session owner readback proves the same hold and request identity/digest, complete realm-target tuple, no-prior-pointer transition, committed pointer, matching audit event, and durable `COMMITTED` outcome. Definitive abort requires an authenticated exact readback of the durable `ABORTED` outcome bound to that same hold and tuple, with storage semantics that prevent any later commit for that attempt; World may then safely abort the hold. Pointer absence, a snapshot, `NOT_FOUND`, `PENDING`, an unavailable read, a tuple or audit mismatch, or contradictory evidence is not abort proof and never releases the hold. Any ambiguous or mismatched result leaves termination fenced and is reconciled automatically from the durable World hold and Game Session attempt record after retries, response loss, or process restart. Timeouts are repair triggers only; no hold is auto-released by elapsed time. + +The current slice implements the typed `AcquireInitialAdmissionBindHold` RPC restricted to the authenticated Game Session workload, a separate durable World hold record, lifecycle-row serialization that blocks termination while the hold is unresolved, and scheduled fail-closed reconciliation. The authenticated Game Session owner-read adapter is not wired, so owner proof cannot yet resolve holds end to end. The 27 World focused tests passed; the three PostgreSQL race/restart integration cases were skipped without Docker and remain unproven here. The replacement hold contract above remains separate. + ## Instance Termination Contract World Management owns the authoritative lifecycle row and monotonic epoch for `gameInstanceId` rows. The lifecycle state, owner registry, cleanup acknowledgements, and Temporal boundary are owned by [ADR 0123](../../decisions/adr-0123-database-authoritative-temporal-coordinated-world-lifecycle.md); this section records the World API consequence. Teardown is cross-service: diff --git a/design/architecture/microservices/world-management-service/runtime-and-data.md b/design/architecture/microservices/world-management-service/runtime-and-data.md index f58bce5725..6dc7956c8c 100644 --- a/design/architecture/microservices/world-management-service/runtime-and-data.md +++ b/design/architecture/microservices/world-management-service/runtime-and-data.md @@ -112,6 +112,14 @@ After target activation, the World local transaction locks source and target lif Game Session binds the hold identity/fence, exact lifecycle proofs, and the applicable canonical private/playtest lifecycle proof tuple, including that exact namespace/scope proof tuple, into its local pointer/audit/prepared-execution/source-cleanup/drain-fence transaction. World finalizes the hold only after authoritative post-swap Game Session readback proves that exact namespace/scope-and-lifecycle-proof-bound transaction committed. Abort requires owner evidence that the pointer transaction did not commit and the prior pointer remains authoritative; contradictory or unavailable evidence keeps the hold unresolved and termination-blocking. `expiresAt` only triggers diagnostics or repair and never auto-releases an unresolved hold. The current implementation has no hold record, coordinated wire/RPC surface, termination predicate, or focused proof; those remain target implementation gaps. +### Initial admission bind hold ownership + +The initial realm bind uses a separate World-owned hold because it has no source pointer or source runtime to preserve. Its durable record binds one stable request identity and canonical digest, opaque hold identity and equality-only fence, exact `{tenantId, realmId, playableStateNamespaceId, playableStateScope}`, initial no-prior-pointer condition, target `gameInstanceId`/`versionId` and exact `ACTIVE` epoch, and `catalogRevision`. It is separate from the replacement hold and from the lifecycle state machine. The hold acquire transaction serializes on the target `world_instance` lifecycle row, verifies the exact `ACTIVE` epoch, and rejects a conflicting nonterminal hold; it performs no remote reads while the World transaction is open. + +The World termination compare-and-set checks that neither an initial-bind nor replacement hold is nonterminal under the same lifecycle-row serialization. A held instance cannot enter `TERMINATING` or advance its lifecycle epoch. Resolving the hold does not weaken ordinary termination: the stable cleanup request, frozen owner/registry snapshot, owner acknowledgements, and final `TERMINATED` compare-and-set remain in force. Game Session must atomically commit the first pointer, matching append-only audit, and terminal attempt outcome in its own database; World then uses authenticated exact owner readback to finalize or to accept only a durable `ABORTED` outcome bound to the same hold/tuple that prevents a later commit for that attempt. Missing, pending, unavailable, mismatched, or contradictory evidence leaves the hold nonterminal. Durable records and the automatic reconciliation path recover the exact identity/fence after response loss or restart; timeout or expiry only triggers repair and never auto-releases the hold. The full normative contract is in [Initial Admission Bind Hold Contract](./api-contracts.md#initial-admission-bind-hold-contract). + +World now persists the initial-bind hold separately and includes it in the lifecycle-row termination check; its scheduled reconciler keeps the hold blocking when no authenticated owner reader is available. The authenticated Game Session owner-read adapter is not wired, and the three PostgreSQL race/restart tests were skipped without Docker. See the [World API contract](./api-contracts.md#initial-admission-bind-hold-contract) for the canonical contract and current proof status. + ### Runtime configuration and events - `generation_rule_template`, or equivalent version-scoped tables, stores publish-affecting procedural-generation inputs keyed by `(tenantId, versionId)` for Draft/Published design data. diff --git a/design/architecture/system-architecture-multi-tenancy.md b/design/architecture/system-architecture-multi-tenancy.md index 43b67cfcbf..96e34fc46f 100644 --- a/design/architecture/system-architecture-multi-tenancy.md +++ b/design/architecture/system-architecture-multi-tenancy.md @@ -176,6 +176,7 @@ Pointer freshness and cutover rules: - **Target transaction boundary:** the persistence key and uniqueness constraint are `{tenantId, realmId}`. Existing-route mutations require an expected positive version and use one atomic database conditional write; checking a version in memory before an unconditional update is not compare-and-set. - In that target, the pointer, append-only audit event, and idempotent request outcome commit atomically when held in the Game Session database. A replacement cutover that changes `gameInstanceId` additionally commits its prepared-cutover execution state in that transaction; ordinary `OPEN` or `CLOSED` updates do not require a prepared upgrade. - A replacement cutover additionally stores and binds validated references to World Management's one-shot `cutoverHoldId`/`cutoverHoldFence` and exact source/target `ACTIVE` lifecycle proofs in that same Game Session transaction; this persists the Game Session pointer, audit, and prepared-execution binding only—it does not transact World state or form a cross-service transaction. World remains the hold and lifecycle owner; Game Session finalizes no hold from local state and requests termination only after authoritative post-swap readback proves the hold-bound pointer, audit, prepared-execution, source-cleanup, and drain-fence commit. See [World's cutover hold contract](microservices/world-management-service/api-contracts.md#replacement-cutover-hold-contract). +- Initial pointer creation has a distinct World-owned hold: it binds the exact tenant/realm/namespace/scope, catalog revision, target `ACTIVE` instance/`versionId`/epoch, and no-prior-pointer condition while Game Session atomically writes the first pointer, matching audit, and durable attempt outcome. Only exact authenticated owner readback can finalize or safely abort it; ambiguous outcomes keep termination fenced and reconcile automatically. This rule does not use snapshots or startup configuration as pointer authority and does not change replacement or ordinary termination contracts. See [World's initial admission bind hold contract](microservices/world-management-service/api-contracts.md#initial-admission-bind-hold-contract). - The pointer governs new or renewed bindings. An already connected player remains authorized by the bound game instance and its runtime fences until the explicit bounded source drain ends; ordinary actions do not re-read pointer authority or eject the player merely because the pointer advanced. ## Account-to-Game Relationships 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 deabb15fca..ad14efc767 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 @@ -8,6 +8,8 @@ This is a non-normative implementation tracker for Game Session runtime and tick This tracker consolidates the live Game Session execution substrate by capability. The recorded boundaries describe current implementation status and bounded follow-up work. +The initial-admission foundation now includes durable catalog/intent and pointer/audit commit/abort proof components. Its three local owner-ledger tests pass and PostgreSQL integration tests compile; live database race/restart proof is not claimed. The authenticated owner-read adapter, fixture delivery/coordinator, and durable `StartSession` retry integration remain unwired; no startup autoactivation or new fixture ingress is added. Ambiguous outcomes continue to fence World termination. See the [Game Session API status](../../architecture/microservices/game-session-service/api-contracts.md#initial-admission-bind) and canonical [World contract](../../architecture/microservices/world-management-service/api-contracts.md#initial-admission-bind-hold-contract). + 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). Current residual: `/actuator/settings/effective` is admitted by the shared HTTP `PRIVILEGED` requirement but does not bind scoped roles to the requested tenant or persisted session tenant. A tenant-scoped caller can read another tenant's effective settings; route-aware scoped/global authorization and focused cross-tenant denial proof remain open. This route is excluded from the tenant/scope/identity validation coverage recorded below until that route-aware authorization and denial proof exist. 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 a8ccf449ab..095161d714 100644 --- a/design/project-management/implementation-tracking/world-runtime-and-movement.md +++ b/design/project-management/implementation-tracking/world-runtime-and-movement.md @@ -8,6 +8,8 @@ This is a non-normative implementation tracker for world runtime and movement. C This tracker is the permanent reader-facing implementation record for world runtime, room reads, movement, lifecycle orchestration, and Draft topology mutation. Canonical target-state design remains under [design/architecture](../../architecture/README.md). +The initial-admission foundation now has a typed Game Session workload-only acquire RPC, a durable World hold, lifecycle-row termination serialization, and scheduled fail-closed reconciliation. The authenticated owner-read adapter is not wired. The 27 World focused tests passed; three PostgreSQL race/restart tests were skipped without Docker. See the [World initial-bind contract](../../architecture/microservices/world-management-service/api-contracts.md#initial-admission-bind-hold-contract). + ## Packet 4 Status and Proof Gaps - `GR-2.1` / `AR-3.1`: [ADR 0122](../../architecture/decisions/adr-0122-stable-playable-state-namespaces-for-runtime-replacement.md) requires world runtime state to distinguish the durable playable-state namespace and `playableStateScope` from a disposable instance and to classify owner data before replacement. Current world instance and lifecycle evidence remains partial; no exhaustive S1/S2/S3 mapping or cleanup proof is claimed. diff --git a/dev-tools/certs/README.md b/dev-tools/certs/README.md index c8c32ec3c7..9a5b79dd34 100644 --- a/dev-tools/certs/README.md +++ b/dev-tools/certs/README.md @@ -10,6 +10,6 @@ Generated certificate outputs in this directory are ignored by Git and should no - `dev-tools/certs/generate-dev-certs.sh --workload` signs local development or test-only gRPC workload leaves for the five publication services, Account, Game Session, and Social Groups with the exact SPIFFE URI and service DNS SANs. The Account, Game Session, and Entity Management leaves support the canonical local Compose gameplay proof, while the remaining local Compose services may use the shared development leaf. Hosted preview and dev-demo do not use this signing mode; their standalone workload leaves come from the protected `firemud-ca-issuer` through the scoped certificate writer. - Standalone hosted runs retain the legacy shared bundle for other gRPC workloads and consume eight cert-manager-issued runtime-facing `firemud-grpc-` leaf Secrets: five publication workloads, Account, Game Session, and Social Groups. They do not create or retain a CA private key in a runtime namespace; a missing or invalid issuer-projected leaf fails closed. - `dev-tools/certs/ensure-dev-certs.sh` guarantees the canonical local smoke entrypoints have the required cert/key set in place before Compose boots. -- `dev-tools/certs/ensure-dev-certs.sh --compose-mtls ` creates the dedicated canonical smoke fixture beneath the active run-owned Compose state directory. The authority and CA private key remain in a host-only mode-0700 directory; each of the eleven Java application containers receives a read-only `/app/certs` mount containing only that service's leaf key, certificate, and public CA certificate. Account, Game Session, and Entity Management receive distinct `dev`-namespace SPIFFE leaves; the remaining services use the shared local development leaf. The fixture is intentionally retained while its Compose project may be restarted and should be removed only after that exact project is torn down. +- `dev-tools/certs/ensure-dev-certs.sh --compose-mtls ` creates the dedicated canonical smoke fixture beneath the active run-owned Compose state directory. The authority and CA private key remain in a host-only mode-0700 directory; each of the eleven Java application containers receives a read-only `/app/certs` mount containing only that service's leaf key, certificate, and public CA certificate. Account, Game Session, Entity Management, and World Management receive distinct `dev`-namespace SPIFFE leaves; World Management's leaf supports its authenticated Game Session owner-read path for the initial admission bind. This is local Compose wiring only; hosted deployments continue to use their separate certificate issuer. The remaining services use the shared local development leaf. The fixture is intentionally retained while its Compose project may be restarted and should be removed only after that exact project is torn down. - The three canonical runtime-proof entrypoints layer `docker/docker-compose.grpc-mtls.override.yml` last. Ordinary `docker/docker-compose.override.yml` remains the plaintext local debugging profile. Hosted certificate provisioning is separate: hosted runtime namespaces receive cert-manager-issued standalone workload leaves and never mount the local CA private key. - `dev-tools/certs/clean-dev-certs.sh` removes generated certificate files from `dev-tools/certs/` unless a target directory or `CERT_DIR` override is provided. diff --git a/dev-tools/certs/ensure-dev-certs.sh b/dev-tools/certs/ensure-dev-certs.sh index 2e3ee9f718..39ff717d51 100644 --- a/dev-tools/certs/ensure-dev-certs.sh +++ b/dev-tools/certs/ensure-dev-certs.sh @@ -94,7 +94,7 @@ ensure_compose_mtls_certs() { for service in "${services[@]}"; do local service_dir="$COMPOSE_MTLS_STAGE_DIR/$service" mkdir -m 755 -- "$service_dir" - if [[ "$service" == account-service || "$service" == game-session-service || "$service" == entity-management-service ]]; then + if [[ "$service" == account-service || "$service" == game-session-service || "$service" == entity-management-service || "$service" == world-management-service ]]; then "$GENERATOR" --workload \ "$authority_dir/ca.crt" "$authority_dir/ca.key" \ "$service_dir/client.crt" "$service_dir/client.key" dev "$service" @@ -154,7 +154,7 @@ ensure_compose_mtls_certs() { echo "Compose mTLS workload fixture contains an unexpected service directory." >&2 return 1 fi - for service in account-service game-session-service entity-management-service; do + for service in account-service game-session-service entity-management-service world-management-service; do local san_output san_output="$(openssl x509 -in "$workloads_dir/$service/client.crt" -noout -ext subjectAltName)" if [[ "$san_output" != *"URI:spiffe://firemud/ns/dev/sa/$service"* ]]; then diff --git a/dev-tools/tests/compose-grpc-mtls-contract.sh b/dev-tools/tests/compose-grpc-mtls-contract.sh index e622a208cc..29af9f9422 100644 --- a/dev-tools/tests/compose-grpc-mtls-contract.sh +++ b/dev-tools/tests/compose-grpc-mtls-contract.sh @@ -79,21 +79,34 @@ for service in "${services[@]}"; do [[ "$cert_public_key" == "$leaf_public_key" ]] done +identity_services=( + account-service game-session-service entity-management-service world-management-service +) declare -A identity_fingerprints=() -for service in account-service game-session-service entity-management-service; do +for service in "${identity_services[@]}"; do echo "Checking exact workload identity: $service" san_output="$(openssl x509 -in "$workloads_dir/$service/client.crt" -noout -ext subjectAltName)" [[ "$san_output" == *"URI:spiffe://firemud/ns/dev/sa/$service"* ]] identity_fingerprints["$service"]="$(openssl x509 -in "$workloads_dir/$service/client.crt" -noout -fingerprint -sha256)" done -[[ "${identity_fingerprints[account-service]}" != "${identity_fingerprints[game-session-service]}" ]] -[[ "${identity_fingerprints[account-service]}" != "${identity_fingerprints[entity-management-service]}" ]] -[[ "${identity_fingerprints[game-session-service]}" != "${identity_fingerprints[entity-management-service]}" ]] +for ((left = 0; left < ${#identity_services[@]}; left++)); do + for ((right = left + 1; right < ${#identity_services[@]}; right++)); do + left_service="${identity_services[$left]}" + right_service="${identity_services[$right]}" + [[ "${identity_fingerprints[$left_service]}" != "${identity_fingerprints[$right_service]}" ]] + done +done echo "Checking canonical Compose entrypoints." mtls_compose="$ROOT_DIR/docker/docker-compose.grpc-mtls.override.yml" rg -Fq 'FIREMUD_GRPC_PLAINTEXT: "false"' "$mtls_compose" rg -Fq 'GRPC_SERVER_TLS_ENABLED: "true"' "$mtls_compose" -rg -Fq 'FIREMUD_GRPC_WORKLOAD_NAMESPACE: dev' "$mtls_compose" +rg -Fq 'client-auth: REQUIRE' "$ROOT_DIR/services/world-management-service/src/main/resources/application.yml" +world_guard="$ROOT_DIR/services/world-management-service/src/main/java/net/firedevops/firemud/worldmanagement/service/impl/InitialAdmissionBindWorkloadGuard.java" +world_grpc="$ROOT_DIR/services/world-management-service/src/main/java/net/firedevops/firemud/worldmanagement/service/impl/WorldManagementGrpcService.java" +rg -Fq 'world_management.v1.WorldManagementService/AcquireInitialAdmissionBindHold' "$world_guard" +rg -Fq 'peerIdentity.isService("game-session-service")' "$world_guard" +rg -Fq 'peerIdentity.isInNamespace(trustedNamespace)' "$world_guard" +rg -Fq 'firemud.grpc.workload-namespace' "$world_grpc" for service in "${services[@]}"; do rg -Fq "\${FIREMUD_COMPOSE_GRPC_MTLS_CERT_ROOT:?canonical smoke must set a run-owned mTLS certificate root}/workloads/$service:/app/certs:ro" "$mtls_compose" done @@ -168,6 +181,8 @@ for name in app_names: assert service.get("build") is None, f"image-only proof must not build {name}" entity_namespace = services["entity-management-service"]["environment"].get("FIREMUD_GRPC_WORKLOAD_NAMESPACE") assert entity_namespace == "dev", entity_namespace +wms_namespace = services["world-management-service"]["environment"].get("FIREMUD_GRPC_WORKLOAD_NAMESPACE") +assert wms_namespace == "dev", wms_namespace assert services["account-service"]["image"].endswith(":contract") print("Verified Compose mTLS wiring and image-only service configuration.") PY diff --git a/docker/docker-compose.grpc-mtls.override.yml b/docker/docker-compose.grpc-mtls.override.yml index 8e964e51a9..b3039ac50c 100644 --- a/docker/docker-compose.grpc-mtls.override.yml +++ b/docker/docker-compose.grpc-mtls.override.yml @@ -1,7 +1,7 @@ # Canonical fresh/image/restart smoke profile. This deliberately overrides the -# ordinary local plaintext profile. Account, Game Session, and Entity -# Management receive distinct dev-namespace SPIFFE leaves; the other eight -# local apps share the local client leaf. Each app gets only its scoped +# ordinary local plaintext profile. Account, Game Session, Entity Management, +# and World Management receive distinct dev-namespace SPIFFE leaves; the other +# seven local apps share the local client leaf. Each app gets only its scoped # read-only leaf mount and the public CA certificate under /app/certs. The CA # private key stays host-only and is never mounted into an app. x-grpc-mtls-environment: &grpc-mtls-environment @@ -77,5 +77,6 @@ services: world-management-service: environment: <<: *grpc-mtls-environment + FIREMUD_GRPC_WORKLOAD_NAMESPACE: dev volumes: - ${FIREMUD_COMPOSE_GRPC_MTLS_CERT_ROOT:?canonical smoke must set a run-owned mTLS certificate root}/workloads/world-management-service:/app/certs:ro diff --git a/protos/game-session/v1/game_session_service.proto b/protos/game-session/v1/game_session_service.proto index 4261870f11..7d111009d8 100644 --- a/protos/game-session/v1/game_session_service.proto +++ b/protos/game-session/v1/game_session_service.proto @@ -206,6 +206,9 @@ message GameplayRealm { string state_scope = 9; string character_creation_policy = 10; bool public_production_realm = 11; + int64 catalog_revision = 12; + string realm_id = 13; + string playable_state_namespace_id = 14; } message ListGameplayRealmsResponse { @@ -232,6 +235,9 @@ message GameplayAdmissionPointer { string state_scope = 10; string character_creation_policy = 11; bool public_production_realm = 12; + int64 catalog_revision = 13; + string realm_id = 14; + string playable_state_namespace_id = 15; } message GetAdmissionPointerResponse { @@ -410,6 +416,11 @@ message AdmissionPointerControlPlaneEntry { int64 occurred_at_ms = 15; string prepared_version_upgrade_id = 16; bool public_production_realm = 17; + optional int64 catalog_revision = 18; + // Empty for historical audit rows that predate durable pointer identity. + string realm_id = 19; + // Empty for historical audit rows that predate durable pointer identity. + string playable_state_namespace_id = 20; } message ListAdmissionPointersRequest {} diff --git a/protos/world-management/v1/world_management_service.proto b/protos/world-management/v1/world_management_service.proto index 8c182551ba..d9c7fd624c 100644 --- a/protos/world-management/v1/world_management_service.proto +++ b/protos/world-management/v1/world_management_service.proto @@ -2,6 +2,7 @@ syntax = "proto3"; package world_management.v1; +import "entity-management/v1/entity_management_service.proto"; import "shared/v1/errors.proto"; import "shared/v1/instance_refs.proto"; @@ -18,6 +19,8 @@ service WorldManagementService { returns (FailPreparedWorldInstanceResponse); rpc GetWorldInstanceLifecycle(GetWorldInstanceLifecycleRequest) returns (GetWorldInstanceLifecycleResponse); + rpc AcquireInitialAdmissionBindHold(AcquireInitialAdmissionBindHoldRequest) + returns (AcquireInitialAdmissionBindHoldResponse); rpc TerminateWorldInstance(TerminateWorldInstanceRequest) returns (TerminateWorldInstanceResponse); rpc GetRoom(GetRoomRequest) returns (GetRoomResponse); @@ -114,6 +117,51 @@ message GetWorldInstanceLifecycleResponse { shared.v1.ErrorDetail error = 2; } +message AcquireInitialAdmissionBindHoldRequest { + string tenant_id = 1; + string game_instance_id = 2; + string version_id = 3; + int64 expected_active_lifecycle_epoch = 4; + string initial_admission_request_id = 5; + string request_digest = 6; + string realm_uuid = 7; + string playable_state_namespace_uuid = 8; + entity_management.v1.PlayableStateScope playable_state_scope = 9; + bool expected_no_prior_pointer = 10; + int64 expected_catalog_revision = 11; +} + +enum InitialAdmissionBindHoldStatus { + INITIAL_ADMISSION_BIND_HOLD_STATUS_UNSPECIFIED = 0; + INITIAL_ADMISSION_BIND_HOLD_STATUS_PENDING = 1; + INITIAL_ADMISSION_BIND_HOLD_STATUS_RECONCILIATION_REQUIRED = 2; + INITIAL_ADMISSION_BIND_HOLD_STATUS_COMMITTED = 3; + INITIAL_ADMISSION_BIND_HOLD_STATUS_ABORTED = 4; +} + +message InitialAdmissionBindHold { + string hold_id = 1; + string hold_fence = 2; + string tenant_id = 3; + string realm_uuid = 4; + string playable_state_namespace_uuid = 5; + entity_management.v1.PlayableStateScope playable_state_scope = 6; + string game_instance_id = 7; + string version_id = 8; + int64 active_lifecycle_epoch = 9; + string initial_admission_request_id = 10; + string request_digest = 11; + bool expected_no_prior_pointer = 12; + int64 expected_catalog_revision = 13; + InitialAdmissionBindHoldStatus status = 14; + int64 diagnostic_expires_at_epoch_millis = 15; +} + +message AcquireInitialAdmissionBindHoldResponse { + InitialAdmissionBindHold hold = 1; + shared.v1.ErrorDetail error = 2; +} + message TerminateWorldInstanceRequest { string tenant_id = 1; string game_instance_id = 2; diff --git a/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/command/text/GameplayWorldCatalog.java b/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/command/text/GameplayWorldCatalog.java index b24f5862c0..c64d2f7b74 100644 --- a/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/command/text/GameplayWorldCatalog.java +++ b/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/command/text/GameplayWorldCatalog.java @@ -1,13 +1,17 @@ package net.firedevops.firemud.gamesession.command.text; import java.util.ArrayList; +import java.util.HashMap; import java.util.LinkedHashMap; import java.util.List; import java.util.Locale; import java.util.Map; import java.util.Objects; import java.util.Optional; +import java.util.Set; +import java.util.UUID; import java.util.function.Supplier; +import java.util.stream.Collectors; import net.firedevops.firemud.gamesession.presentation.RealmBrowseViewOutput; import net.firedevops.firemud.gamesession.presentation.WorldsViewOutput; import net.firedevops.firemud.gamesession.service.GameplayAdmissionPointerAuthorityService; @@ -20,9 +24,17 @@ @Component public final class GameplayWorldCatalog { private final Supplier> worldSupplier; + private final Supplier> authorityPointerSupplier; private GameplayWorldCatalog(Supplier> worldSupplier) { + this(worldSupplier, null); + } + + private GameplayWorldCatalog( + Supplier> worldSupplier, + Supplier> authorityPointerSupplier) { this.worldSupplier = Objects.requireNonNull(worldSupplier, "worldSupplier must not be null"); + this.authorityPointerSupplier = authorityPointerSupplier; } @Autowired @@ -31,23 +43,31 @@ public GameplayWorldCatalog(GameplayAdmissionPointerAuthorityService authoritySe () -> { Objects.requireNonNull(authorityService, "authorityService must not be null"); return toWorlds(authorityService.listPointers()); + }, + () -> { + Objects.requireNonNull(authorityService, "authorityService must not be null"); + return authorityService.listPointers(); }); } public static GameplayWorldCatalog forWorldViews(List worlds) { - return new GameplayWorldCatalog(() -> normalizeWorlds(worlds)); + return new GameplayWorldCatalog(() -> worlds); } public static GameplayWorldCatalog forWorldSupplier(Supplier> worldSupplier) { - return new GameplayWorldCatalog(() -> normalizeWorlds(worldSupplier.get())); + return new GameplayWorldCatalog(worldSupplier); } public WorldsViewOutput browseView() { - return new WorldsViewOutput(worldEntries()); + return new WorldsViewOutput(worldEntries(loadWorldSnapshot())); } public Optional browseRealms(String worldSelector) { - return resolveWorld(worldSelector) + if (worldSelector == null || worldSelector.isBlank()) { + return Optional.empty(); + } + CatalogSnapshot snapshot = loadWorldSnapshot(); + return resolveWorld(worldSelector, snapshot) .map(world -> new RealmBrowseViewOutput(world.slug(), realmEntries(world))); } @@ -55,7 +75,34 @@ public Optional resolveWorld(String selector) { if (selector == null || selector.isBlank()) { return Optional.empty(); } - List worlds = visibleWorlds(); + return resolveWorld(selector, loadWorldSnapshot()); + } + + private Optional resolveWorld(String selector, CatalogSnapshot snapshot) { + List visibleWorlds = visibleWorlds(snapshot); + List indexedWorlds = discoverableWorlds(snapshot); + try { + int index = Integer.parseInt(selector); + if (index >= 1 && index <= indexedWorlds.size()) { + return Optional.of(indexedWorlds.get(index - 1)); + } + } catch (NumberFormatException ignored) { + // Fall back to slug matching. + } + String normalized = selector.trim().toLowerCase(Locale.ROOT); + return visibleWorlds.stream() + .filter(world -> normalized.equals(world.slug().toLowerCase(Locale.ROOT))) + .findFirst(); + } + + public Optional resolveWorldFromAuthoritySnapshot(String selector) { + if (selector == null || selector.isBlank()) { + return Optional.empty(); + } + return resolveWorld(selector, visibleWorldsFromAuthoritySnapshot()); + } + + private Optional resolveWorld(String selector, List worlds) { try { int index = Integer.parseInt(selector); if (index >= 1 && index <= worlds.size()) { @@ -105,10 +152,81 @@ public Optional resolveDefaultRealm(WorldView world) { if (visibleRealms.isEmpty()) { return Optional.empty(); } + return resolveDefaultRealm(world, loadWorldSnapshot()); + } + + private Optional resolveDefaultRealm(WorldView world, CatalogSnapshot snapshot) { + if (world == null) { + return Optional.empty(); + } + List visibleRealms = visibleRealms(world); + if (visibleRealms.isEmpty()) { + return Optional.empty(); + } + List publicProductionRealms = + visibleRealms.stream().filter(RealmView::publicProductionRealm).toList(); + if (publicProductionRealms.size() > 1) { + return Optional.empty(); + } + if (publicProductionRealms.size() == 1) { + RealmView publicRealm = publicProductionRealms.getFirst(); + return publicProductionRealmCardinality(snapshot, publicRealm.tenantId()) + == PublicProductionRealmCardinality.EXACTLY_ONE + ? Optional.of(publicRealm) + : Optional.empty(); + } + // Non-public presentation remains available only when its tenant has an unambiguous public + // production realm elsewhere in the catalog; zero or multiple public targets never default. + return visibleRealms.stream() + .map(RealmView::tenantId) + .distinct() + .allMatch( + tenantId -> + publicProductionRealmCardinality(snapshot, tenantId) + == PublicProductionRealmCardinality.EXACTLY_ONE) + ? Optional.of(visibleRealms.getFirst()) + : Optional.empty(); + } + + /** + * Returns the tenant-wide cardinality of visible, player-addressable public-production realms. + */ + public PublicProductionRealmCardinality publicProductionRealmCardinality(long tenantId) { + if (tenantId <= 0L) { + return PublicProductionRealmCardinality.ZERO; + } + return publicProductionRealmCardinality(loadWorldSnapshot(), tenantId); + } + + private PublicProductionRealmCardinality publicProductionRealmCardinality( + CatalogSnapshot snapshot, long tenantId) { + return switch (Long.compare( + snapshot.publicProductionRealmCounts().getOrDefault(tenantId, 0L), 1L)) { + case -1 -> PublicProductionRealmCardinality.ZERO; + case 0 -> PublicProductionRealmCardinality.EXACTLY_ONE; + default -> PublicProductionRealmCardinality.MULTIPLE; + }; + } + + public boolean hasValidPublicProductionRealm(long tenantId) { + return publicProductionRealmCardinality(tenantId) + == PublicProductionRealmCardinality.EXACTLY_ONE; + } + + /** Returns whether each tenant represented by this world has unambiguous public routing. */ + public boolean hasValidPublicProductionRealm(WorldView world) { + List visibleRealms = visibleRealms(world); + if (visibleRealms.isEmpty()) { + return false; + } + CatalogSnapshot snapshot = loadWorldSnapshot(); return visibleRealms.stream() - .filter(RealmView::publicProductionRealm) - .findFirst() - .or(() -> Optional.of(visibleRealms.get(0))); + .map(RealmView::tenantId) + .distinct() + .allMatch( + tenantId -> + publicProductionRealmCardinality(snapshot, tenantId) + == PublicProductionRealmCardinality.EXACTLY_ONE); } public boolean requiresExplicitRealmSelection(WorldView world) { @@ -116,8 +234,9 @@ public boolean requiresExplicitRealmSelection(WorldView world) { } public Optional resolveRealmByRuntimeTarget(long tenantId, long gameInstanceId) { + CatalogSnapshot snapshot = loadWorldSnapshot(); List matches = - normalizeWorlds(worldSupplier.get()).stream() + snapshot.worlds().stream() .flatMap(world -> world.realms().stream()) .filter(realm -> realm.tenantId() == tenantId) .filter(realm -> realm.gameInstanceId() == gameInstanceId) @@ -126,8 +245,9 @@ public Optional resolveRealmByRuntimeTarget(long tenantId, long gameI } public Optional resolveRuntimeTarget(long tenantId, long gameInstanceId) { + CatalogSnapshot snapshot = loadWorldSnapshot(); List matches = - normalizeWorlds(worldSupplier.get()).stream() + snapshot.worlds().stream() .flatMap( world -> world.realms().stream() @@ -150,7 +270,7 @@ public Optional resolveRealmTarget(String worldSlug, String } String normalizedWorld = worldSlug.trim().toLowerCase(Locale.ROOT); String normalizedRealm = realmSlug.trim().toLowerCase(Locale.ROOT); - return visibleWorlds().stream() + return visibleWorlds(loadWorldSnapshot()).stream() .filter(world -> normalizedWorld.equals(world.slug().toLowerCase(Locale.ROOT))) .flatMap( world -> @@ -174,20 +294,89 @@ public List visibleRealms(WorldView world) { } public List visibleWorlds() { - return normalizeWorlds(worldSupplier.get()).stream() - .filter(this::hasVisibleRealmEntries) - .toList(); + return visibleWorlds(loadWorldSnapshot()); + } + + private List visibleWorlds(CatalogSnapshot snapshot) { + return snapshot.worlds().stream().filter(this::hasVisibleRealmEntries).toList(); } - private List worldEntries() { - List worlds = visibleWorlds(); + /** + * Builds the visible world projection from one authoritative pointer-list snapshot. + * + *

Text discovery intentionally continues to use {@link #visibleWorlds()}, which filters + * malformed or ambiguous rows for its existing negative-admission behavior. The gRPC discovery + * boundary validates completeness and tenant-global public-realm uniqueness on one exact snapshot + * before projecting it. + */ + public List visibleWorldsFromAuthoritySnapshot() { + if (authorityPointerSupplier == null) { + return visibleWorlds(); + } + List pointers = authorityPointerSupplier.get(); + if (pointers == null) { + throw new AuthorityPointerUnavailableException( + "Authoritative gameplay pointer list is unavailable"); + } + for (GameplayAdmissionPointerSnapshot pointer : pointers) { + if (!hasCompleteAuthorityPointer(pointer)) { + throw new AuthorityPointerUnavailableException( + "Authoritative gameplay pointer is incomplete"); + } + } + requireExactlyOneVisiblePublicProductionRealmPerTenant(pointers); + return toWorlds(pointers).stream().filter(this::hasVisibleRealmEntries).toList(); + } + + /** + * Requires a direct public-production admission target to match the sole visible public realm in + * its tenant's current authoritative pointer snapshot. + */ + public void requireUniqueVisiblePublicProductionRealm( + GameplayAdmissionPointerSnapshot expectedPointer) { + if (authorityPointerSupplier == null) { + throw new AuthorityPointerUnavailableException( + "Authoritative gameplay pointer list is unavailable"); + } + if (expectedPointer == null || expectedPointer.tenantId() <= 0L) { + throw new AuthorityPointerUnavailableException( + "Authoritative public-production realm identity is unavailable"); + } + List pointers = authorityPointerSupplier.get(); + if (pointers == null) { + throw new AuthorityPointerUnavailableException( + "Authoritative gameplay pointer list is unavailable"); + } + for (GameplayAdmissionPointerSnapshot pointer : pointers) { + if (pointer == null || pointer.tenantId() == expectedPointer.tenantId()) { + if (!hasCompleteAuthorityPointer(pointer)) { + throw new AuthorityPointerUnavailableException( + "Authoritative gameplay pointer is incomplete"); + } + } + } + + List publicRealms = + pointers.stream() + .filter(pointer -> pointer.tenantId() == expectedPointer.tenantId()) + .filter(GameplayAdmissionPointerSnapshot::visible) + .filter(GameplayAdmissionPointerSnapshot::publicProductionRealm) + .toList(); + if (publicRealms.size() != 1 || !publicRealms.getFirst().equals(expectedPointer)) { + throw new AuthorityPointerUnavailableException( + "Authoritative public-production realm is not unique for tenant " + + expectedPointer.tenantId()); + } + } + + private List worldEntries(CatalogSnapshot snapshot) { + List worlds = discoverableWorlds(snapshot); ArrayList entries = new ArrayList<>(worlds.size()); - for (int i = 0; i < worlds.size(); i++) { - WorldView world = worlds.get(i); - RealmView defaultRealm = defaultRealm(world); + for (WorldView world : worlds) { + RealmView defaultRealm = defaultRealm(world, snapshot); entries.add( new WorldsViewOutput.WorldEntry( - i + 1, + entries.size() + 1, world.slug(), world.displayName(), defaultRealm.gameInstanceId(), @@ -218,13 +407,35 @@ private boolean hasVisibleRealmEntries(WorldView world) { return world != null && !visibleRealms(world).isEmpty(); } - private RealmView defaultRealm(WorldView world) { - return resolveDefaultRealm(world) - .orElseGet( - () -> { - return new RealmView( - "production", "Live Realm", 0L, 0L, 1L, true, true, false, "SHARED", "ALLOW_NEW"); - }); + private List discoverableWorlds(CatalogSnapshot snapshot) { + return visibleWorlds(snapshot).stream() + .filter(world -> resolveDefaultRealm(world, snapshot).isPresent()) + .toList(); + } + + private boolean isPlayerAddressable(RealmView realm) { + return realm != null + && realm.visible() + && realm.slug() != null + && !realm.slug().isBlank() + && realm.tenantId() > 0L; + } + + private RealmView defaultRealm(WorldView world, CatalogSnapshot snapshot) { + return resolveDefaultRealm(world, snapshot).orElseThrow(); + } + + private CatalogSnapshot loadWorldSnapshot() { + List worlds = normalizeWorlds(worldSupplier.get()); + Map publicProductionRealmCounts = new HashMap<>(); + for (WorldView world : worlds) { + for (RealmView realm : world.realms()) { + if (isPlayerAddressable(realm) && realm.publicProductionRealm()) { + publicProductionRealmCounts.merge(realm.tenantId(), 1L, Long::sum); + } + } + } + return new CatalogSnapshot(worlds, Map.copyOf(publicProductionRealmCounts)); } private static List normalizeWorlds(List worlds) { @@ -268,12 +479,42 @@ private static List toWorlds(List p .toList()); } + private static void requireExactlyOneVisiblePublicProductionRealmPerTenant( + List pointers) { + Set tenantIds = + pointers.stream() + .map(GameplayAdmissionPointerSnapshot::tenantId) + .collect(Collectors.toSet()); + Map publicRealmCounts = new HashMap<>(); + for (GameplayAdmissionPointerSnapshot pointer : pointers) { + if (pointer.visible() && pointer.publicProductionRealm()) { + publicRealmCounts.merge(pointer.tenantId(), 1L, Long::sum); + } + } + for (long tenantId : tenantIds) { + if (publicRealmCounts.getOrDefault(tenantId, 0L) != 1L) { + throw new AuthorityPointerUnavailableException( + "Authoritative public-production realm count is invalid for tenant " + tenantId); + } + } + } + private static boolean hasCompleteAuthorityPointer(GameplayAdmissionPointerSnapshot pointer) { return GameplayAdmissionPointerSnapshots.hasCompleteRoutingBundle(pointer) + && pointer.catalogRevision() > 0L + && pointer.realmId() != null + && pointer.playableStateNamespaceId() != null + && ("SHARED".equals(pointer.stateScope()) || "ISOLATED".equals(pointer.stateScope())) && pointer.characterCreationPolicy() != null && !pointer.characterCreationPolicy().isBlank(); } + public static final class AuthorityPointerUnavailableException extends RuntimeException { + public AuthorityPointerUnavailableException(String message) { + super(message); + } + } + private static RealmView toRealmView(GameplayAdmissionPointerSnapshot pointer) { return new RealmView( pointer.realmSlug(), @@ -285,7 +526,10 @@ private static RealmView toRealmView(GameplayAdmissionPointerSnapshot pointer) { pointer.publicProductionRealm(), pointer.requiresCharacterSelection(), pointer.stateScope(), - pointer.characterCreationPolicy()); + pointer.characterCreationPolicy(), + pointer.catalogRevision(), + pointer.realmId(), + pointer.playableStateNamespaceId()); } private static WorldView copyWorldView(WorldView input) { @@ -312,9 +556,15 @@ private static RealmView copyRealmView(RealmView input) { input.publicProductionRealm(), input.requiresCharacterSelection(), input.stateScope(), - input.characterCreationPolicy()); + input.characterCreationPolicy(), + input.catalogRevision(), + input.realmId(), + input.playableStateNamespaceId()); } + private record CatalogSnapshot( + List worlds, Map publicProductionRealmCounts) {} + public record WorldView(String slug, String displayName, List realms) { public WorldView { realms = realms == null ? List.of() : List.copyOf(realms); @@ -331,11 +581,75 @@ public record RealmView( boolean publicProductionRealm, boolean requiresCharacterSelection, String stateScope, - String characterCreationPolicy) {} + String characterCreationPolicy, + long catalogRevision, + UUID realmId, + UUID playableStateNamespaceId) { + /** Creates a synthetic realm view without authoritative identity evidence. */ + public RealmView( + String slug, + String displayName, + long tenantId, + long gameInstanceId, + long pointerVersion, + boolean visible, + boolean publicProductionRealm, + boolean requiresCharacterSelection, + String stateScope, + String characterCreationPolicy, + long catalogRevision) { + this( + slug, + displayName, + tenantId, + gameInstanceId, + pointerVersion, + visible, + publicProductionRealm, + requiresCharacterSelection, + stateScope, + characterCreationPolicy, + catalogRevision, + null, + null); + } + + /** Creates a synthetic realm view without authoritative catalog revision evidence. */ + public RealmView( + String slug, + String displayName, + long tenantId, + long gameInstanceId, + long pointerVersion, + boolean visible, + boolean publicProductionRealm, + boolean requiresCharacterSelection, + String stateScope, + String characterCreationPolicy) { + this( + slug, + displayName, + tenantId, + gameInstanceId, + pointerVersion, + visible, + publicProductionRealm, + requiresCharacterSelection, + stateScope, + characterCreationPolicy, + 0L); + } + } public record RuntimeRealmTarget( String worldSlug, String worldDisplayName, String realmSlug, String realmDisplayName) {} + public enum PublicProductionRealmCardinality { + ZERO, + EXACTLY_ONE, + MULTIPLE + } + private static final class MutableWorldAccumulator { private final String slug; private final String displayName; diff --git a/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/config/GameplayAdmissionPointerBootstrapProperties.java b/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/config/GameplayAdmissionPointerBootstrapProperties.java index 65ac39f720..4d8cb0385b 100644 --- a/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/config/GameplayAdmissionPointerBootstrapProperties.java +++ b/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/config/GameplayAdmissionPointerBootstrapProperties.java @@ -12,14 +12,15 @@ public class GameplayAdmissionPointerBootstrapProperties { private List pointers = new ArrayList<>( List.of( - defaultPointerSeed("demo", "Demo World", 1L, 1L, false), - defaultPointerSeed("sandbox", "Builder Sandbox", 1L, 2L, true))); + defaultPointerSeed("demo", "Demo World", 1L, 1L, true, false), + defaultPointerSeed("sandbox", "Builder Sandbox", 1L, 2L, false, true))); private static PointerSeed defaultPointerSeed( String worldSlug, String worldDisplayName, long tenantId, long gameInstanceId, + boolean publicProductionRealm, boolean requiresCharacterSelection) { PointerSeed pointer = new PointerSeed(); pointer.setWorldSlug(worldSlug); @@ -29,7 +30,7 @@ private static PointerSeed defaultPointerSeed( pointer.setTenantId(tenantId); pointer.setGameInstanceId(gameInstanceId); pointer.setVisible(true); - pointer.setPublicProductionRealm(true); + pointer.setPublicProductionRealm(publicProductionRealm); pointer.setRequiresCharacterSelection(requiresCharacterSelection); pointer.setStateScope(StateScope.SHARED); pointer.setCharacterCreationPolicy(CharacterCreationPolicy.ALLOW_NEW); diff --git a/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/data/GameplayAdmissionPointerBootstrapInitializer.java b/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/data/GameplayAdmissionPointerBootstrapInitializer.java index d71a6d4518..7366638efa 100644 --- a/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/data/GameplayAdmissionPointerBootstrapInitializer.java +++ b/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/data/GameplayAdmissionPointerBootstrapInitializer.java @@ -1,19 +1,24 @@ package net.firedevops.firemud.gamesession.data; +import java.util.HashMap; +import java.util.HashSet; +import java.util.List; +import java.util.Locale; +import java.util.Map; +import java.util.Set; import lombok.RequiredArgsConstructor; import net.firedevops.firemud.gamesession.config.GameplayAdmissionPointerBootstrapProperties; import net.firedevops.firemud.gamesession.repository.GameplayAdmissionPointerRepository; -import net.firedevops.firemud.gamesession.service.GameplayAdmissionPointerAuthorityService; -import net.firedevops.firemud.gamesession.service.GameplayAdmissionPointerMutation; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; import org.springframework.boot.ApplicationArguments; import org.springframework.boot.ApplicationRunner; import org.springframework.boot.autoconfigure.condition.ConditionalOnProperty; import org.springframework.stereotype.Component; -import org.springframework.transaction.annotation.Transactional; /** - * Bootstraps the persisted gameplay admission-pointer authority from configuration only when the - * authority store is empty. + * Validates configured admission-pointer seeds while keeping an empty authority store closed until + * owner-validated World lifecycle proof is available. */ @Component @RequiredArgsConstructor @@ -23,72 +28,88 @@ havingValue = "true", matchIfMissing = true) public class GameplayAdmissionPointerBootstrapInitializer implements ApplicationRunner { + private static final Logger LOGGER = + LoggerFactory.getLogger(GameplayAdmissionPointerBootstrapInitializer.class); + private final GameplayAdmissionPointerRepository pointerRepository; - private final GameplayAdmissionPointerAuthorityService authorityService; private final GameplayAdmissionPointerBootstrapProperties bootstrapProperties; @Override - @Transactional public void run(ApplicationArguments args) { if (pointerRepository.count() > 0) { return; } - if (bootstrapProperties.getPointers() == null) { - return; + List pointers = + bootstrapProperties.getPointers(); + validateSeeds(pointers); + LOGGER.warn( + "Skipping configured gameplay admission pointer bootstrap because owner-validated " + + "World ACTIVE lifecycle and epoch proof is unavailable; admission remains closed"); + } + + private static void validateSeeds( + List pointers) { + if (pointers == null || pointers.isEmpty()) { + throw new IllegalArgumentException("Gameplay admission pointer bootstrap seeds are required"); } - for (GameplayAdmissionPointerBootstrapProperties.PointerSeed pointer : - bootstrapProperties.getPointers()) { - if (pointer == null - || pointer.getWorldSlug() == null - || pointer.getWorldSlug().isBlank() - || pointer.getRealmSlug() == null - || pointer.getRealmSlug().isBlank()) { - continue; + + Set worldRealmKeys = new HashSet<>(); + Set runtimeTargetKeys = new HashSet<>(); + Map publicRealmCounts = new HashMap<>(); + Set tenantIds = new HashSet<>(); + for (int index = 0; index < pointers.size(); index++) { + GameplayAdmissionPointerBootstrapProperties.PointerSeed pointer = pointers.get(index); + if (pointer == null) { + throw invalidSeed(index, "must not be null"); + } + requireText(pointer.getWorldSlug(), index, "world slug"); + requireText(pointer.getWorldDisplayName(), index, "world display name"); + requireText(pointer.getRealmSlug(), index, "realm slug"); + requireText(pointer.getRealmDisplayName(), index, "realm display name"); + if (pointer.getTenantId() <= 0) { + throw invalidSeed(index, "tenant ID must be positive"); + } + if (pointer.getGameInstanceId() <= 0) { + throw invalidSeed(index, "game instance ID must be positive"); + } + + tenantIds.add(pointer.getTenantId()); + String worldRealmKey = + pointer.getTenantId() + + ":" + + pointer.getWorldSlug().trim().toLowerCase(Locale.ROOT) + + ":" + + pointer.getRealmSlug().trim().toLowerCase(Locale.ROOT); + if (!worldRealmKeys.add(worldRealmKey)) { + throw invalidSeed(index, "duplicates a tenant world and realm selector"); + } + String runtimeTargetKey = pointer.getTenantId() + ":" + pointer.getGameInstanceId(); + if (!runtimeTargetKeys.add(runtimeTargetKey)) { + throw invalidSeed(index, "duplicates a tenant runtime target"); + } + if (pointer.isVisible() && pointer.isPublicProductionRealm()) { + publicRealmCounts.merge(pointer.getTenantId(), 1L, Long::sum); + } + } + + for (long tenantId : tenantIds) { + if (publicRealmCounts.getOrDefault(tenantId, 0L) != 1L) { + throw new IllegalArgumentException( + "Gameplay admission pointer bootstrap must define exactly one visible public " + + "production realm for tenant " + + tenantId); } - authorityService.upsertPointer( - new GameplayAdmissionPointerMutation( - pointer.getWorldSlug(), - pointer.getWorldDisplayName(), - pointer.getRealmSlug(), - pointer.getRealmDisplayName(), - pointer.getTenantId(), - pointer.getGameInstanceId(), - pointer.isVisible(), - pointer.isPublicProductionRealm(), - pointer.isRequiresCharacterSelection(), - stateScopeName(pointer), - characterCreationPolicyName(pointer), - "system/bootstrap", - "Initial gameplay pointer bootstrap", - "bootstrap:" - + pointer.getTenantId() - + ":" - + pointer.getGameInstanceId() - + ":" - + pointer.getWorldSlug() - + ":" - + pointer.getRealmSlug(), - null, - null)); } } - private static String stateScopeName( - GameplayAdmissionPointerBootstrapProperties.PointerSeed pointer) { - GameplayAdmissionPointerBootstrapProperties.StateScope stateScope = pointer.getStateScope(); - return (stateScope != null - ? stateScope - : GameplayAdmissionPointerBootstrapProperties.StateScope.SHARED) - .name(); + private static void requireText(String value, int index, String field) { + if (value == null || value.isBlank()) { + throw invalidSeed(index, field + " is required"); + } } - private static String characterCreationPolicyName( - GameplayAdmissionPointerBootstrapProperties.PointerSeed pointer) { - GameplayAdmissionPointerBootstrapProperties.CharacterCreationPolicy policy = - pointer.getCharacterCreationPolicy(); - return (policy != null - ? policy - : GameplayAdmissionPointerBootstrapProperties.CharacterCreationPolicy.ALLOW_NEW) - .name(); + private static IllegalArgumentException invalidSeed(int index, String reason) { + return new IllegalArgumentException( + "Invalid gameplay admission pointer bootstrap seed at index " + index + ": " + reason); } } diff --git a/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/entity/GameplayAdmissionPointer.java b/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/entity/GameplayAdmissionPointer.java index 235349c833..27163a0068 100644 --- a/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/entity/GameplayAdmissionPointer.java +++ b/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/entity/GameplayAdmissionPointer.java @@ -1,6 +1,7 @@ package net.firedevops.firemud.gamesession.entity; import java.time.Instant; +import java.util.UUID; import lombok.Data; @Data @@ -13,6 +14,9 @@ public class GameplayAdmissionPointer { private Long tenantId; private Long gameInstanceId; private Long pointerVersion; + private Long catalogRevision; + private UUID realmId; + private UUID playableStateNamespaceId; private boolean visible; private boolean publicProductionRealm; private boolean requiresCharacterSelection; diff --git a/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/entity/GameplayAdmissionPointerEvent.java b/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/entity/GameplayAdmissionPointerEvent.java index 45ff8daf90..9656c1b7cf 100644 --- a/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/entity/GameplayAdmissionPointerEvent.java +++ b/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/entity/GameplayAdmissionPointerEvent.java @@ -1,6 +1,7 @@ package net.firedevops.firemud.gamesession.entity; import java.time.Instant; +import java.util.UUID; import lombok.Data; @Data @@ -13,6 +14,9 @@ public class GameplayAdmissionPointerEvent { private Long tenantId; private Long gameInstanceId; private Long pointerVersion; + private Long catalogRevision; + private UUID realmId; + private UUID playableStateNamespaceId; private boolean visible; private boolean publicProductionRealm; private boolean requiresCharacterSelection; diff --git a/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/entity/InitialAdmissionBindAttempt.java b/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/entity/InitialAdmissionBindAttempt.java new file mode 100644 index 0000000000..1b3f1221d9 --- /dev/null +++ b/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/entity/InitialAdmissionBindAttempt.java @@ -0,0 +1,33 @@ +package net.firedevops.firemud.gamesession.entity; + +import java.time.Instant; +import java.util.UUID; + +/** Durable GS owner ledger row; the attempt UUID is the stable owner-proof identity. */ +public record InitialAdmissionBindAttempt( + UUID attemptId, + long tenantId, + String initialAdmissionRequestId, + String requestDigest, + UUID realmId, + UUID playableStateNamespaceId, + String playableStateScope, + boolean expectedNoPriorPointer, + long catalogRevision, + long gameInstanceId, + long versionId, + long activeLifecycleEpoch, + UUID holdId, + UUID holdFence, + Status status, + Long pointerId, + Long auditEventId, + Instant createdAt, + Instant updatedAt, + Instant terminalAt) { + public enum Status { + PENDING, + COMMITTED, + ABORTED + } +} diff --git a/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/entity/InitialAdmissionBindCatalog.java b/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/entity/InitialAdmissionBindCatalog.java new file mode 100644 index 0000000000..207f31d78e --- /dev/null +++ b/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/entity/InitialAdmissionBindCatalog.java @@ -0,0 +1,22 @@ +package net.firedevops.firemud.gamesession.entity; + +import java.time.Instant; +import java.util.UUID; + +/** Persisted, immutable revision-one public catalog identity used by an initial pointer bind. */ +public record InitialAdmissionBindCatalog( + UUID realmId, + long tenantId, + long gameTemplateId, + String worldSlug, + String worldDisplayName, + String realmSlug, + String realmDisplayName, + long catalogRevision, + UUID playableStateNamespaceId, + boolean visible, + boolean publicProductionRealm, + boolean requiresCharacterSelection, + String stateScope, + String characterCreationPolicy, + Instant createdAt) {} diff --git a/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/repository/GameplayAdmissionPointerEventRepository.java b/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/repository/GameplayAdmissionPointerEventRepository.java index 1acf68a0f3..276817318a 100644 --- a/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/repository/GameplayAdmissionPointerEventRepository.java +++ b/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/repository/GameplayAdmissionPointerEventRepository.java @@ -69,6 +69,11 @@ public GameplayAdmissionPointerEvent save(GameplayAdmissionPointerEvent entity) .set(GAMEPLAY_ADMISSION_POINTER_EVENT.TENANT_ID, entity.getTenantId()) .set(GAMEPLAY_ADMISSION_POINTER_EVENT.GAME_INSTANCE_ID, entity.getGameInstanceId()) .set(GAMEPLAY_ADMISSION_POINTER_EVENT.POINTER_VERSION, entity.getPointerVersion()) + .set(GAMEPLAY_ADMISSION_POINTER_EVENT.CATALOG_REVISION, entity.getCatalogRevision()) + .set(GAMEPLAY_ADMISSION_POINTER_EVENT.REALM_ID, entity.getRealmId()) + .set( + GAMEPLAY_ADMISSION_POINTER_EVENT.PLAYABLE_STATE_NAMESPACE_ID, + entity.getPlayableStateNamespaceId()) .set(GAMEPLAY_ADMISSION_POINTER_EVENT.VISIBLE, entity.isVisible()) .set( GAMEPLAY_ADMISSION_POINTER_EVENT.PUBLIC_PRODUCTION_REALM, @@ -120,6 +125,9 @@ private void populate( record.setTenantId(entity.getTenantId()); record.setGameInstanceId(entity.getGameInstanceId()); record.setPointerVersion(entity.getPointerVersion()); + record.setCatalogRevision(entity.getCatalogRevision()); + record.setRealmId(entity.getRealmId()); + record.setPlayableStateNamespaceId(entity.getPlayableStateNamespaceId()); record.setVisible(entity.isVisible()); record.setPublicProductionRealm(entity.isPublicProductionRealm()); record.setRequiresCharacterSelection(entity.isRequiresCharacterSelection()); @@ -142,6 +150,10 @@ private GameplayAdmissionPointerEvent toEntity(Record record) { entity.setTenantId(record.get(GAMEPLAY_ADMISSION_POINTER_EVENT.TENANT_ID)); entity.setGameInstanceId(record.get(GAMEPLAY_ADMISSION_POINTER_EVENT.GAME_INSTANCE_ID)); entity.setPointerVersion(record.get(GAMEPLAY_ADMISSION_POINTER_EVENT.POINTER_VERSION)); + entity.setCatalogRevision(record.get(GAMEPLAY_ADMISSION_POINTER_EVENT.CATALOG_REVISION)); + entity.setRealmId(record.get(GAMEPLAY_ADMISSION_POINTER_EVENT.REALM_ID)); + entity.setPlayableStateNamespaceId( + record.get(GAMEPLAY_ADMISSION_POINTER_EVENT.PLAYABLE_STATE_NAMESPACE_ID)); entity.setVisible(Boolean.TRUE.equals(record.get(GAMEPLAY_ADMISSION_POINTER_EVENT.VISIBLE))); entity.setPublicProductionRealm( Boolean.TRUE.equals(record.get(GAMEPLAY_ADMISSION_POINTER_EVENT.PUBLIC_PRODUCTION_REALM))); diff --git a/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/repository/GameplayAdmissionPointerRepository.java b/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/repository/GameplayAdmissionPointerRepository.java index a01611bf45..60748667ed 100644 --- a/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/repository/GameplayAdmissionPointerRepository.java +++ b/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/repository/GameplayAdmissionPointerRepository.java @@ -3,10 +3,13 @@ import static net.firedevops.firemud.common.persistence.jooq.JooqPersistenceSupport.toInstant; import static net.firedevops.firemud.common.persistence.jooq.JooqPersistenceSupport.toLocalDateTime; import static net.firedevops.firemud.gamesession.jooq.tables.GameplayAdmissionPointer.GAMEPLAY_ADMISSION_POINTER; +import static net.firedevops.firemud.gamesession.jooq.tables.GameplayTenantSharedPlayableStateNamespace.GAMEPLAY_TENANT_SHARED_PLAYABLE_STATE_NAMESPACE; import edu.umd.cs.findbugs.annotations.SuppressFBWarnings; import java.util.List; +import java.util.Objects; import java.util.Optional; +import java.util.UUID; import java.util.stream.Stream; import net.firedevops.firemud.gamesession.entity.GameplayAdmissionPointer; import net.firedevops.firemud.gamesession.jooq.tables.records.GameplayAdmissionPointerRecord; @@ -73,11 +76,19 @@ public List findAllByOrderByWorldSlugAscRealmSlugAsc() public GameplayAdmissionPointer save(GameplayAdmissionPointer entity) { if (entity.getId() == null) { + if (!"SHARED".equals(entity.getStateScope()) && !"ISOLATED".equals(entity.getStateScope())) { + throw new IllegalArgumentException("state_scope must be SHARED or ISOLATED"); + } lockRuntimeTargetForCreation(entity); if (countByRuntimeTarget(entity.getTenantId(), entity.getGameInstanceId()) != 0) { throw new IllegalStateException( "Admission pointer creation conflicted with another route for the runtime target"); } + entity.setRealmId(UUID.randomUUID()); + entity.setPlayableStateNamespaceId( + "SHARED".equals(entity.getStateScope()) + ? getOrCreateTenantSharedNamespace(entity.getTenantId()) + : UUID.randomUUID()); GameplayAdmissionPointerRecord record = dsl.newRecord(GAMEPLAY_ADMISSION_POINTER); populate(record, entity); try { @@ -88,8 +99,8 @@ public GameplayAdmissionPointer save(GameplayAdmissionPointer entity) { } return findById(record.getId()).orElseThrow(); } - if (entity.getPointerVersion() == null || entity.getPointerVersion() <= 1L) { - throw new IllegalArgumentException("Existing admission pointer must advance its version"); + if (entity.getPointerVersion() == null || entity.getPointerVersion() <= 0L) { + throw new IllegalArgumentException("Existing admission pointer must have a positive version"); } GameplayAdmissionPointer current = findByIdForUpdate(entity.getId()) @@ -104,9 +115,35 @@ public GameplayAdmissionPointer save(GameplayAdmissionPointer entity) { () -> new AdmissionPointerVersionMismatchException( "Admission pointer no longer exists: id=" + entity.getId())); - if (!Long.valueOf(entity.getPointerVersion() - 1L).equals(current.getPointerVersion())) { + if (current.getPointerVersion() == null + || current.getCatalogRevision() == null + || entity.getCatalogRevision() == null + || entity.getCatalogRevision() <= 0L) { + throw new IllegalStateException( + "Admission pointer version and catalog revision must be present and positive"); + } + if (!Objects.equals(entity.getRealmId(), current.getRealmId()) + || !Objects.equals( + entity.getPlayableStateNamespaceId(), current.getPlayableStateNamespaceId())) { + throw new IllegalStateException( + "Admission pointer update cannot replace durable realm or playable-state identity"); + } + boolean runtimeTargetChanged = + !Objects.equals(entity.getGameInstanceId(), current.getGameInstanceId()); + boolean catalogChanged = !catalogPolicyMatches(current, entity); + long expectedPointerVersion = + runtimeTargetChanged + ? Math.addExact(current.getPointerVersion(), 1L) + : current.getPointerVersion(); + long expectedCatalogRevision = + catalogChanged + ? Math.addExact(current.getCatalogRevision(), 1L) + : current.getCatalogRevision(); + if (entity.getPointerVersion() != expectedPointerVersion + || entity.getCatalogRevision() != expectedCatalogRevision) { throw new AdmissionPointerVersionMismatchException( - "Admission pointer changed before the requested version could be committed: id=" + "Admission pointer version or catalog revision changed before the requested update could" + + " be committed: id=" + entity.getId()); } long destinationCount = @@ -127,6 +164,7 @@ public GameplayAdmissionPointer save(GameplayAdmissionPointer entity) { .set(GAMEPLAY_ADMISSION_POINTER.TENANT_ID, entity.getTenantId()) .set(GAMEPLAY_ADMISSION_POINTER.GAME_INSTANCE_ID, entity.getGameInstanceId()) .set(GAMEPLAY_ADMISSION_POINTER.POINTER_VERSION, entity.getPointerVersion()) + .set(GAMEPLAY_ADMISSION_POINTER.CATALOG_REVISION, entity.getCatalogRevision()) .set(GAMEPLAY_ADMISSION_POINTER.VISIBLE, entity.isVisible()) .set( GAMEPLAY_ADMISSION_POINTER.PUBLIC_PRODUCTION_REALM, @@ -148,7 +186,10 @@ public GameplayAdmissionPointer save(GameplayAdmissionPointer entity) { .eq(entity.getId()) .and( GAMEPLAY_ADMISSION_POINTER.POINTER_VERSION.eq( - entity.getPointerVersion() - 1L))) + current.getPointerVersion())) + .and( + GAMEPLAY_ADMISSION_POINTER.CATALOG_REVISION.eq( + current.getCatalogRevision()))) .execute(); } catch (IntegrityConstraintViolationException ex) { throw new IllegalStateException( @@ -228,6 +269,33 @@ private void lockRuntimeTargetForCreation(GameplayAdmissionPointer entity) { lockRuntimeTarget(runtimeTargetLockKey(entity.getTenantId(), entity.getGameInstanceId())); } + private UUID getOrCreateTenantSharedNamespace(Long tenantId) { + lockRuntimeTarget("tenant-shared-playable-state:" + tenantId); + var table = GAMEPLAY_TENANT_SHARED_PLAYABLE_STATE_NAMESPACE; + UUID namespace = + dsl.select(table.PLAYABLE_STATE_NAMESPACE_ID) + .from(table) + .where(table.TENANT_ID.eq(tenantId)) + .fetchOne(table.PLAYABLE_STATE_NAMESPACE_ID); + if (namespace != null) { + return namespace; + } + dsl.insertInto(table) + .set(table.TENANT_ID, tenantId) + .set(table.PLAYABLE_STATE_NAMESPACE_ID, UUID.randomUUID()) + .onDuplicateKeyIgnore() + .execute(); + UUID allocated = + dsl.select(table.PLAYABLE_STATE_NAMESPACE_ID) + .from(table) + .where(table.TENANT_ID.eq(tenantId)) + .fetchOne(table.PLAYABLE_STATE_NAMESPACE_ID); + if (allocated == null) { + throw new IllegalStateException("Tenant shared playable-state namespace allocation failed"); + } + return allocated; + } + private void populate(GameplayAdmissionPointerRecord record, GameplayAdmissionPointer entity) { record.setWorldSlug(entity.getWorldSlug()); record.setWorldDisplayName(entity.getWorldDisplayName()); @@ -236,6 +304,9 @@ private void populate(GameplayAdmissionPointerRecord record, GameplayAdmissionPo record.setTenantId(entity.getTenantId()); record.setGameInstanceId(entity.getGameInstanceId()); record.setPointerVersion(entity.getPointerVersion()); + record.setCatalogRevision(entity.getCatalogRevision()); + record.setRealmId(entity.getRealmId()); + record.setPlayableStateNamespaceId(entity.getPlayableStateNamespaceId()); record.setVisible(entity.isVisible()); record.setPublicProductionRealm(entity.isPublicProductionRealm()); record.setRequiresCharacterSelection(entity.isRequiresCharacterSelection()); @@ -247,6 +318,20 @@ private void populate(GameplayAdmissionPointerRecord record, GameplayAdmissionPo record.setUpdatedAt(toLocalDateTime(entity.getUpdatedAt())); } + private boolean catalogPolicyMatches( + GameplayAdmissionPointer current, GameplayAdmissionPointer requested) { + return Objects.equals(current.getWorldSlug(), requested.getWorldSlug()) + && Objects.equals(current.getWorldDisplayName(), requested.getWorldDisplayName()) + && Objects.equals(current.getRealmSlug(), requested.getRealmSlug()) + && Objects.equals(current.getRealmDisplayName(), requested.getRealmDisplayName()) + && current.isVisible() == requested.isVisible() + && current.isPublicProductionRealm() == requested.isPublicProductionRealm() + && current.isRequiresCharacterSelection() == requested.isRequiresCharacterSelection() + && Objects.equals(current.getStateScope(), requested.getStateScope()) + && Objects.equals( + current.getCharacterCreationPolicy(), requested.getCharacterCreationPolicy()); + } + private GameplayAdmissionPointer toEntity(Record record) { GameplayAdmissionPointer entity = new GameplayAdmissionPointer(); entity.setId(record.get(GAMEPLAY_ADMISSION_POINTER.ID)); @@ -257,6 +342,10 @@ private GameplayAdmissionPointer toEntity(Record record) { entity.setTenantId(record.get(GAMEPLAY_ADMISSION_POINTER.TENANT_ID)); entity.setGameInstanceId(record.get(GAMEPLAY_ADMISSION_POINTER.GAME_INSTANCE_ID)); entity.setPointerVersion(record.get(GAMEPLAY_ADMISSION_POINTER.POINTER_VERSION)); + entity.setCatalogRevision(record.get(GAMEPLAY_ADMISSION_POINTER.CATALOG_REVISION)); + entity.setRealmId(record.get(GAMEPLAY_ADMISSION_POINTER.REALM_ID)); + entity.setPlayableStateNamespaceId( + record.get(GAMEPLAY_ADMISSION_POINTER.PLAYABLE_STATE_NAMESPACE_ID)); entity.setVisible(Boolean.TRUE.equals(record.get(GAMEPLAY_ADMISSION_POINTER.VISIBLE))); entity.setPublicProductionRealm( Boolean.TRUE.equals(record.get(GAMEPLAY_ADMISSION_POINTER.PUBLIC_PRODUCTION_REALM))); diff --git a/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/repository/InitialAdmissionBindAttemptRepository.java b/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/repository/InitialAdmissionBindAttemptRepository.java new file mode 100644 index 0000000000..d7175c4f69 --- /dev/null +++ b/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/repository/InitialAdmissionBindAttemptRepository.java @@ -0,0 +1,298 @@ +package net.firedevops.firemud.gamesession.repository; + +import static net.firedevops.firemud.common.persistence.jooq.JooqPersistenceSupport.toInstant; +import static net.firedevops.firemud.common.persistence.jooq.JooqPersistenceSupport.toLocalDateTime; +import static net.firedevops.firemud.gamesession.jooq.tables.GameplayAdmissionPointer.GAMEPLAY_ADMISSION_POINTER; +import static net.firedevops.firemud.gamesession.jooq.tables.GameplayInitialAdmissionBindAttempt.GAMEPLAY_INITIAL_ADMISSION_BIND_ATTEMPT; + +import edu.umd.cs.findbugs.annotations.SuppressFBWarnings; +import java.time.Instant; +import java.util.List; +import java.util.Optional; +import java.util.UUID; +import net.firedevops.firemud.gamesession.entity.GameplayAdmissionPointer; +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.jooq.tables.records.GameplayAdmissionPointerRecord; +import net.firedevops.firemud.gamesession.jooq.tables.records.GameplayInitialAdmissionBindAttemptRecord; +import org.jooq.DSLContext; +import org.jooq.Record; +import org.jooq.SQLDialect; +import org.springframework.stereotype.Repository; + +@Repository +@SuppressFBWarnings( + value = "EI_EXPOSE_REP2", + justification = "Injected DSLContext is an internal Spring collaborator.") +public class InitialAdmissionBindAttemptRepository { + private static final String ATTEMPT_LOCK_PREFIX = "initial-admission-bind-attempt:"; + private static final String REALM_LOCK_PREFIX = "initial-admission-bind-realm:"; + + private final DSLContext dsl; + + public InitialAdmissionBindAttemptRepository(DSLContext dsl) { + this.dsl = dsl; + } + + public void lockAttemptAndRealm(long tenantId, String requestId, UUID realmId) { + if (dsl.dialect().family() != SQLDialect.POSTGRES) { + return; + } + List.of( + ATTEMPT_LOCK_PREFIX + tenantId + ":" + requestId, + REALM_LOCK_PREFIX + tenantId + ":" + realmId) + .stream() + .sorted() + .forEach(this::lock); + } + + public Optional findByTenantAndRequestId( + long tenantId, String requestId) { + return dsl.selectFrom(GAMEPLAY_INITIAL_ADMISSION_BIND_ATTEMPT) + .where( + GAMEPLAY_INITIAL_ADMISSION_BIND_ATTEMPT + .TENANT_ID + .eq(tenantId) + .and( + GAMEPLAY_INITIAL_ADMISSION_BIND_ATTEMPT.INITIAL_ADMISSION_REQUEST_ID.eq( + requestId))) + .fetchOptional(this::toEntity); + } + + public Optional findByTenantAndRequestIdForUpdate( + long tenantId, String requestId) { + return dsl.selectFrom(GAMEPLAY_INITIAL_ADMISSION_BIND_ATTEMPT) + .where( + GAMEPLAY_INITIAL_ADMISSION_BIND_ATTEMPT + .TENANT_ID + .eq(tenantId) + .and( + GAMEPLAY_INITIAL_ADMISSION_BIND_ATTEMPT.INITIAL_ADMISSION_REQUEST_ID.eq( + requestId))) + .forUpdate() + .fetchOptional(this::toEntity); + } + + public Optional findPendingByTenantAndRealmForUpdate( + long tenantId, UUID realmId) { + return dsl.selectFrom(GAMEPLAY_INITIAL_ADMISSION_BIND_ATTEMPT) + .where( + GAMEPLAY_INITIAL_ADMISSION_BIND_ATTEMPT + .TENANT_ID + .eq(tenantId) + .and(GAMEPLAY_INITIAL_ADMISSION_BIND_ATTEMPT.REALM_ID.eq(realmId)) + .and(GAMEPLAY_INITIAL_ADMISSION_BIND_ATTEMPT.STATUS.eq(Status.PENDING.name()))) + .forUpdate() + .fetchOptional(this::toEntity); + } + + public InitialAdmissionBindAttempt insertPending(InitialAdmissionBindAttempt attempt) { + GameplayInitialAdmissionBindAttemptRecord record = + dsl.newRecord(GAMEPLAY_INITIAL_ADMISSION_BIND_ATTEMPT); + record.setAttemptId(attempt.attemptId()); + record.setTenantId(attempt.tenantId()); + record.setInitialAdmissionRequestId(attempt.initialAdmissionRequestId()); + record.setRequestDigest(attempt.requestDigest()); + record.setRealmId(attempt.realmId()); + record.setPlayableStateNamespaceId(attempt.playableStateNamespaceId()); + record.setPlayableStateScope(attempt.playableStateScope()); + record.setExpectedNoPriorPointer(true); + record.setCatalogRevision(attempt.catalogRevision()); + record.setGameInstanceId(attempt.gameInstanceId()); + record.setVersionId(attempt.versionId()); + record.setActiveLifecycleEpoch(attempt.activeLifecycleEpoch()); + record.setStatus(Status.PENDING.name()); + record.setCreatedAt(toLocalDateTime(attempt.createdAt())); + record.setUpdatedAt(toLocalDateTime(attempt.updatedAt())); + record.setTerminalAt(null); + record.store(); + return findByTenantAndRequestId(attempt.tenantId(), attempt.initialAdmissionRequestId()) + .orElseThrow(); + } + + public InitialAdmissionBindAttempt attachHold( + InitialAdmissionBindAttempt attempt, UUID holdId, UUID holdFence, Instant now) { + int updated = + dsl.update(GAMEPLAY_INITIAL_ADMISSION_BIND_ATTEMPT) + .set(GAMEPLAY_INITIAL_ADMISSION_BIND_ATTEMPT.HOLD_ID, holdId) + .set(GAMEPLAY_INITIAL_ADMISSION_BIND_ATTEMPT.HOLD_FENCE, holdFence) + .set(GAMEPLAY_INITIAL_ADMISSION_BIND_ATTEMPT.UPDATED_AT, toLocalDateTime(now)) + .where(GAMEPLAY_INITIAL_ADMISSION_BIND_ATTEMPT.ATTEMPT_ID.eq(attempt.attemptId())) + .execute(); + if (updated != 1) { + throw new IllegalStateException("Initial admission attempt disappeared while attaching hold"); + } + return findByTenantAndRequestId(attempt.tenantId(), attempt.initialAdmissionRequestId()) + .orElseThrow(); + } + + public InitialAdmissionBindAttempt markCommitted( + InitialAdmissionBindAttempt attempt, long pointerId, long auditEventId, Instant now) { + int updated = + dsl.update(GAMEPLAY_INITIAL_ADMISSION_BIND_ATTEMPT) + .set(GAMEPLAY_INITIAL_ADMISSION_BIND_ATTEMPT.STATUS, Status.COMMITTED.name()) + .set(GAMEPLAY_INITIAL_ADMISSION_BIND_ATTEMPT.POINTER_ID, pointerId) + .set(GAMEPLAY_INITIAL_ADMISSION_BIND_ATTEMPT.AUDIT_EVENT_ID, auditEventId) + .set(GAMEPLAY_INITIAL_ADMISSION_BIND_ATTEMPT.UPDATED_AT, toLocalDateTime(now)) + .set(GAMEPLAY_INITIAL_ADMISSION_BIND_ATTEMPT.TERMINAL_AT, toLocalDateTime(now)) + .where( + GAMEPLAY_INITIAL_ADMISSION_BIND_ATTEMPT + .ATTEMPT_ID + .eq(attempt.attemptId()) + .and(GAMEPLAY_INITIAL_ADMISSION_BIND_ATTEMPT.STATUS.eq(Status.PENDING.name()))) + .execute(); + if (updated != 1) { + throw new IllegalStateException("Initial admission attempt was not pending at commit"); + } + return findByTenantAndRequestId(attempt.tenantId(), attempt.initialAdmissionRequestId()) + .orElseThrow(); + } + + public InitialAdmissionBindAttempt markAborted(InitialAdmissionBindAttempt attempt, Instant now) { + int updated = + dsl.update(GAMEPLAY_INITIAL_ADMISSION_BIND_ATTEMPT) + .set(GAMEPLAY_INITIAL_ADMISSION_BIND_ATTEMPT.STATUS, Status.ABORTED.name()) + .set(GAMEPLAY_INITIAL_ADMISSION_BIND_ATTEMPT.UPDATED_AT, toLocalDateTime(now)) + .set(GAMEPLAY_INITIAL_ADMISSION_BIND_ATTEMPT.TERMINAL_AT, toLocalDateTime(now)) + .where( + GAMEPLAY_INITIAL_ADMISSION_BIND_ATTEMPT + .ATTEMPT_ID + .eq(attempt.attemptId()) + .and(GAMEPLAY_INITIAL_ADMISSION_BIND_ATTEMPT.STATUS.eq(Status.PENDING.name()))) + .execute(); + if (updated != 1) { + throw new IllegalStateException("Initial admission attempt was not pending at abort"); + } + return findByTenantAndRequestId(attempt.tenantId(), attempt.initialAdmissionRequestId()) + .orElseThrow(); + } + + public boolean hasPointerForCatalog(InitialAdmissionBindCatalog catalog) { + return dsl.fetchExists( + dsl.selectOne() + .from(GAMEPLAY_ADMISSION_POINTER) + .where( + GAMEPLAY_ADMISSION_POINTER + .TENANT_ID + .eq(catalog.tenantId()) + .and( + GAMEPLAY_ADMISSION_POINTER + .REALM_ID + .eq(catalog.realmId()) + .or( + GAMEPLAY_ADMISSION_POINTER + .WORLD_SLUG + .eq(catalog.worldSlug()) + .and( + GAMEPLAY_ADMISSION_POINTER.REALM_SLUG.eq( + catalog.realmSlug())))))); + } + + public boolean hasPointerForRuntimeTarget(long tenantId, long gameInstanceId) { + return dsl.fetchExists( + dsl.selectOne() + .from(GAMEPLAY_ADMISSION_POINTER) + .where( + GAMEPLAY_ADMISSION_POINTER + .TENANT_ID + .eq(tenantId) + .and(GAMEPLAY_ADMISSION_POINTER.GAME_INSTANCE_ID.eq(gameInstanceId)))); + } + + public GameplayAdmissionPointer insertPointer( + InitialAdmissionBindCatalog catalog, long gameInstanceId, Instant now) { + GameplayAdmissionPointerRecord record = dsl.newRecord(GAMEPLAY_ADMISSION_POINTER); + record.setWorldSlug(catalog.worldSlug()); + record.setWorldDisplayName(catalog.worldDisplayName()); + record.setRealmSlug(catalog.realmSlug()); + record.setRealmDisplayName(catalog.realmDisplayName()); + record.setTenantId(catalog.tenantId()); + record.setGameInstanceId(gameInstanceId); + record.setPointerVersion(1L); + record.setCatalogRevision(catalog.catalogRevision()); + record.setRealmId(catalog.realmId()); + record.setPlayableStateNamespaceId(catalog.playableStateNamespaceId()); + record.setVisible(true); + record.setPublicProductionRealm(true); + record.setRequiresCharacterSelection(catalog.requiresCharacterSelection()); + record.setStateScope("SHARED"); + record.setCharacterCreationPolicy("ALLOW_NEW"); + record.setLastUpdatedBy("game-session-initial-admission-bind"); + record.setLastUpdateReason("initial admission pointer bind"); + record.setCreatedAt(toLocalDateTime(now)); + record.setUpdatedAt(toLocalDateTime(now)); + record.store(); + return findPointerById(record.getId()).orElseThrow(); + } + + public Optional findPointerById(long pointerId) { + return dsl.selectFrom(GAMEPLAY_ADMISSION_POINTER) + .where(GAMEPLAY_ADMISSION_POINTER.ID.eq(pointerId)) + .fetchOptional(this::toPointer); + } + + private Optional findPointerById(Long pointerId) { + return dsl.selectFrom(GAMEPLAY_ADMISSION_POINTER) + .where(GAMEPLAY_ADMISSION_POINTER.ID.eq(pointerId)) + .fetchOptional(this::toPointer); + } + + private void lock(String key) { + dsl.fetch("select pg_advisory_xact_lock(hashtextextended(cast(? as text), 0))", key); + } + + private InitialAdmissionBindAttempt toEntity(Record record) { + return new InitialAdmissionBindAttempt( + record.get(GAMEPLAY_INITIAL_ADMISSION_BIND_ATTEMPT.ATTEMPT_ID), + record.get(GAMEPLAY_INITIAL_ADMISSION_BIND_ATTEMPT.TENANT_ID), + record.get(GAMEPLAY_INITIAL_ADMISSION_BIND_ATTEMPT.INITIAL_ADMISSION_REQUEST_ID), + record.get(GAMEPLAY_INITIAL_ADMISSION_BIND_ATTEMPT.REQUEST_DIGEST), + record.get(GAMEPLAY_INITIAL_ADMISSION_BIND_ATTEMPT.REALM_ID), + record.get(GAMEPLAY_INITIAL_ADMISSION_BIND_ATTEMPT.PLAYABLE_STATE_NAMESPACE_ID), + record.get(GAMEPLAY_INITIAL_ADMISSION_BIND_ATTEMPT.PLAYABLE_STATE_SCOPE), + Boolean.TRUE.equals( + record.get(GAMEPLAY_INITIAL_ADMISSION_BIND_ATTEMPT.EXPECTED_NO_PRIOR_POINTER)), + record.get(GAMEPLAY_INITIAL_ADMISSION_BIND_ATTEMPT.CATALOG_REVISION), + record.get(GAMEPLAY_INITIAL_ADMISSION_BIND_ATTEMPT.GAME_INSTANCE_ID), + record.get(GAMEPLAY_INITIAL_ADMISSION_BIND_ATTEMPT.VERSION_ID), + record.get(GAMEPLAY_INITIAL_ADMISSION_BIND_ATTEMPT.ACTIVE_LIFECYCLE_EPOCH), + record.get(GAMEPLAY_INITIAL_ADMISSION_BIND_ATTEMPT.HOLD_ID), + record.get(GAMEPLAY_INITIAL_ADMISSION_BIND_ATTEMPT.HOLD_FENCE), + Status.valueOf(record.get(GAMEPLAY_INITIAL_ADMISSION_BIND_ATTEMPT.STATUS)), + record.get(GAMEPLAY_INITIAL_ADMISSION_BIND_ATTEMPT.POINTER_ID), + record.get(GAMEPLAY_INITIAL_ADMISSION_BIND_ATTEMPT.AUDIT_EVENT_ID), + toInstant(record.get(GAMEPLAY_INITIAL_ADMISSION_BIND_ATTEMPT.CREATED_AT)), + toInstant(record.get(GAMEPLAY_INITIAL_ADMISSION_BIND_ATTEMPT.UPDATED_AT)), + toInstant(record.get(GAMEPLAY_INITIAL_ADMISSION_BIND_ATTEMPT.TERMINAL_AT))); + } + + private GameplayAdmissionPointer toPointer(Record record) { + GameplayAdmissionPointer pointer = new GameplayAdmissionPointer(); + pointer.setId(record.get(GAMEPLAY_ADMISSION_POINTER.ID)); + pointer.setWorldSlug(record.get(GAMEPLAY_ADMISSION_POINTER.WORLD_SLUG)); + pointer.setWorldDisplayName(record.get(GAMEPLAY_ADMISSION_POINTER.WORLD_DISPLAY_NAME)); + pointer.setRealmSlug(record.get(GAMEPLAY_ADMISSION_POINTER.REALM_SLUG)); + pointer.setRealmDisplayName(record.get(GAMEPLAY_ADMISSION_POINTER.REALM_DISPLAY_NAME)); + pointer.setTenantId(record.get(GAMEPLAY_ADMISSION_POINTER.TENANT_ID)); + pointer.setGameInstanceId(record.get(GAMEPLAY_ADMISSION_POINTER.GAME_INSTANCE_ID)); + pointer.setPointerVersion(record.get(GAMEPLAY_ADMISSION_POINTER.POINTER_VERSION)); + pointer.setCatalogRevision(record.get(GAMEPLAY_ADMISSION_POINTER.CATALOG_REVISION)); + pointer.setRealmId(record.get(GAMEPLAY_ADMISSION_POINTER.REALM_ID)); + pointer.setPlayableStateNamespaceId( + record.get(GAMEPLAY_ADMISSION_POINTER.PLAYABLE_STATE_NAMESPACE_ID)); + pointer.setVisible(Boolean.TRUE.equals(record.get(GAMEPLAY_ADMISSION_POINTER.VISIBLE))); + pointer.setPublicProductionRealm( + Boolean.TRUE.equals(record.get(GAMEPLAY_ADMISSION_POINTER.PUBLIC_PRODUCTION_REALM))); + pointer.setRequiresCharacterSelection( + Boolean.TRUE.equals(record.get(GAMEPLAY_ADMISSION_POINTER.REQUIRES_CHARACTER_SELECTION))); + pointer.setStateScope(record.get(GAMEPLAY_ADMISSION_POINTER.STATE_SCOPE)); + pointer.setCharacterCreationPolicy( + record.get(GAMEPLAY_ADMISSION_POINTER.CHARACTER_CREATION_POLICY)); + pointer.setLastUpdatedBy(record.get(GAMEPLAY_ADMISSION_POINTER.LAST_UPDATED_BY)); + pointer.setLastUpdateReason(record.get(GAMEPLAY_ADMISSION_POINTER.LAST_UPDATE_REASON)); + pointer.setCreatedAt(toInstant(record.get(GAMEPLAY_ADMISSION_POINTER.CREATED_AT))); + pointer.setUpdatedAt(toInstant(record.get(GAMEPLAY_ADMISSION_POINTER.UPDATED_AT))); + return pointer; + } +} diff --git a/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/repository/InitialAdmissionBindCatalogRepository.java b/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/repository/InitialAdmissionBindCatalogRepository.java new file mode 100644 index 0000000000..2a91bfc498 --- /dev/null +++ b/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/repository/InitialAdmissionBindCatalogRepository.java @@ -0,0 +1,133 @@ +package net.firedevops.firemud.gamesession.repository; + +import static net.firedevops.firemud.common.persistence.jooq.JooqPersistenceSupport.toInstant; +import static net.firedevops.firemud.common.persistence.jooq.JooqPersistenceSupport.toLocalDateTime; +import static net.firedevops.firemud.gamesession.jooq.tables.GameplayInitialAdmissionBindCatalog.GAMEPLAY_INITIAL_ADMISSION_BIND_CATALOG; +import static net.firedevops.firemud.gamesession.jooq.tables.GameplayTenantSharedPlayableStateNamespace.GAMEPLAY_TENANT_SHARED_PLAYABLE_STATE_NAMESPACE; + +import edu.umd.cs.findbugs.annotations.SuppressFBWarnings; +import java.time.Instant; +import java.util.Optional; +import java.util.UUID; +import net.firedevops.firemud.gamesession.entity.InitialAdmissionBindCatalog; +import net.firedevops.firemud.gamesession.service.InitialAdmissionBindCatalogDescriptor; +import org.jooq.DSLContext; +import org.jooq.Record; +import org.jooq.SQLDialect; +import org.springframework.stereotype.Repository; + +@Repository +@SuppressFBWarnings( + value = "EI_EXPOSE_REP2", + justification = "Injected DSLContext is an internal Spring collaborator.") +public class InitialAdmissionBindCatalogRepository { + private static final String TENANT_CATALOG_LOCK_PREFIX = "initial-admission-bind-catalog:"; + private static final String SHARED_NAMESPACE_LOCK_PREFIX = "tenant-shared-playable-state:"; + + private final DSLContext dsl; + + public InitialAdmissionBindCatalogRepository(DSLContext dsl) { + this.dsl = dsl; + } + + public Optional findByTenantId(long tenantId) { + return dsl.selectFrom(GAMEPLAY_INITIAL_ADMISSION_BIND_CATALOG) + .where(GAMEPLAY_INITIAL_ADMISSION_BIND_CATALOG.TENANT_ID.eq(tenantId)) + .fetchOptional(this::toEntity); + } + + public Optional findByTenantIdAndSelectors( + long tenantId, String worldSlug, String realmSlug) { + return dsl.selectFrom(GAMEPLAY_INITIAL_ADMISSION_BIND_CATALOG) + .where( + GAMEPLAY_INITIAL_ADMISSION_BIND_CATALOG + .TENANT_ID + .eq(tenantId) + .and(GAMEPLAY_INITIAL_ADMISSION_BIND_CATALOG.WORLD_SLUG.eq(worldSlug)) + .and(GAMEPLAY_INITIAL_ADMISSION_BIND_CATALOG.REALM_SLUG.eq(realmSlug))) + .fetchOptional(this::toEntity); + } + + public void lockTenantCatalogAndSharedNamespace(long tenantId) { + if (dsl.dialect().family() != SQLDialect.POSTGRES) { + return; + } + lock(TENANT_CATALOG_LOCK_PREFIX + tenantId); + lock(SHARED_NAMESPACE_LOCK_PREFIX + tenantId); + } + + public UUID getOrCreateTenantSharedNamespace(long tenantId) { + var table = GAMEPLAY_TENANT_SHARED_PLAYABLE_STATE_NAMESPACE; + UUID existing = + dsl.select(table.PLAYABLE_STATE_NAMESPACE_ID) + .from(table) + .where(table.TENANT_ID.eq(tenantId)) + .fetchOne(table.PLAYABLE_STATE_NAMESPACE_ID); + if (existing != null) { + return existing; + } + UUID candidate = UUID.randomUUID(); + dsl.insertInto(table) + .set(table.TENANT_ID, tenantId) + .set(table.PLAYABLE_STATE_NAMESPACE_ID, candidate) + .set(table.ALLOCATED_AT, toLocalDateTime(Instant.now())) + .execute(); + return candidate; + } + + public InitialAdmissionBindCatalog insert( + InitialAdmissionBindCatalogDescriptor descriptor, + UUID realmId, + UUID playableStateNamespaceId) { + dsl.insertInto(GAMEPLAY_INITIAL_ADMISSION_BIND_CATALOG) + .set(GAMEPLAY_INITIAL_ADMISSION_BIND_CATALOG.REALM_ID, realmId) + .set(GAMEPLAY_INITIAL_ADMISSION_BIND_CATALOG.TENANT_ID, descriptor.tenantId()) + .set(GAMEPLAY_INITIAL_ADMISSION_BIND_CATALOG.GAME_TEMPLATE_ID, descriptor.gameTemplateId()) + .set(GAMEPLAY_INITIAL_ADMISSION_BIND_CATALOG.WORLD_SLUG, descriptor.worldSlug()) + .set( + GAMEPLAY_INITIAL_ADMISSION_BIND_CATALOG.WORLD_DISPLAY_NAME, + descriptor.worldDisplayName()) + .set(GAMEPLAY_INITIAL_ADMISSION_BIND_CATALOG.REALM_SLUG, descriptor.realmSlug()) + .set( + GAMEPLAY_INITIAL_ADMISSION_BIND_CATALOG.REALM_DISPLAY_NAME, + descriptor.realmDisplayName()) + .set(GAMEPLAY_INITIAL_ADMISSION_BIND_CATALOG.CATALOG_REVISION, 1L) + .set( + GAMEPLAY_INITIAL_ADMISSION_BIND_CATALOG.PLAYABLE_STATE_NAMESPACE_ID, + playableStateNamespaceId) + .set(GAMEPLAY_INITIAL_ADMISSION_BIND_CATALOG.VISIBLE, true) + .set(GAMEPLAY_INITIAL_ADMISSION_BIND_CATALOG.PUBLIC_PRODUCTION_REALM, true) + .set( + GAMEPLAY_INITIAL_ADMISSION_BIND_CATALOG.REQUIRES_CHARACTER_SELECTION, + descriptor.requiresCharacterSelection()) + .set(GAMEPLAY_INITIAL_ADMISSION_BIND_CATALOG.STATE_SCOPE, "SHARED") + .set(GAMEPLAY_INITIAL_ADMISSION_BIND_CATALOG.CHARACTER_CREATION_POLICY, "ALLOW_NEW") + .execute(); + return findByTenantId(descriptor.tenantId()).orElseThrow(); + } + + private void lock(String key) { + dsl.fetch("select pg_advisory_xact_lock(hashtextextended(cast(? as text), 0))", key); + } + + private InitialAdmissionBindCatalog toEntity(Record record) { + return new InitialAdmissionBindCatalog( + record.get(GAMEPLAY_INITIAL_ADMISSION_BIND_CATALOG.REALM_ID), + record.get(GAMEPLAY_INITIAL_ADMISSION_BIND_CATALOG.TENANT_ID), + record.get(GAMEPLAY_INITIAL_ADMISSION_BIND_CATALOG.GAME_TEMPLATE_ID), + record.get(GAMEPLAY_INITIAL_ADMISSION_BIND_CATALOG.WORLD_SLUG), + record.get(GAMEPLAY_INITIAL_ADMISSION_BIND_CATALOG.WORLD_DISPLAY_NAME), + record.get(GAMEPLAY_INITIAL_ADMISSION_BIND_CATALOG.REALM_SLUG), + record.get(GAMEPLAY_INITIAL_ADMISSION_BIND_CATALOG.REALM_DISPLAY_NAME), + record.get(GAMEPLAY_INITIAL_ADMISSION_BIND_CATALOG.CATALOG_REVISION), + record.get(GAMEPLAY_INITIAL_ADMISSION_BIND_CATALOG.PLAYABLE_STATE_NAMESPACE_ID), + Boolean.TRUE.equals(record.get(GAMEPLAY_INITIAL_ADMISSION_BIND_CATALOG.VISIBLE)), + Boolean.TRUE.equals( + record.get(GAMEPLAY_INITIAL_ADMISSION_BIND_CATALOG.PUBLIC_PRODUCTION_REALM)), + Boolean.TRUE.equals( + record.get(GAMEPLAY_INITIAL_ADMISSION_BIND_CATALOG.REQUIRES_CHARACTER_SELECTION)), + record.get(GAMEPLAY_INITIAL_ADMISSION_BIND_CATALOG.STATE_SCOPE), + record.get(GAMEPLAY_INITIAL_ADMISSION_BIND_CATALOG.CHARACTER_CREATION_POLICY), + toInstant(record.get(GAMEPLAY_INITIAL_ADMISSION_BIND_CATALOG.CREATED_AT))); + } +} diff --git a/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/service/GameplayAdmissionPointerSnapshot.java b/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/service/GameplayAdmissionPointerSnapshot.java index 91fa8e464f..5b0a879615 100644 --- a/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/service/GameplayAdmissionPointerSnapshot.java +++ b/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/service/GameplayAdmissionPointerSnapshot.java @@ -1,5 +1,7 @@ package net.firedevops.firemud.gamesession.service; +import java.util.UUID; + public record GameplayAdmissionPointerSnapshot( String worldSlug, String worldDisplayName, @@ -12,4 +14,70 @@ public record GameplayAdmissionPointerSnapshot( boolean publicProductionRealm, boolean requiresCharacterSelection, String stateScope, - String characterCreationPolicy) {} + String characterCreationPolicy, + long catalogRevision, + UUID realmId, + UUID playableStateNamespaceId) { + /** Creates a synthetic snapshot without catalog identity/revision authority. */ + public GameplayAdmissionPointerSnapshot( + String worldSlug, + String worldDisplayName, + String realmSlug, + String realmDisplayName, + long tenantId, + long gameInstanceId, + long pointerVersion, + boolean visible, + boolean publicProductionRealm, + boolean requiresCharacterSelection, + String stateScope, + String characterCreationPolicy, + long catalogRevision) { + this( + worldSlug, + worldDisplayName, + realmSlug, + realmDisplayName, + tenantId, + gameInstanceId, + pointerVersion, + visible, + publicProductionRealm, + requiresCharacterSelection, + stateScope, + characterCreationPolicy, + catalogRevision, + null, + null); + } + + /** Creates a synthetic snapshot without catalog authority for legacy test fixtures. */ + public GameplayAdmissionPointerSnapshot( + String worldSlug, + String worldDisplayName, + String realmSlug, + String realmDisplayName, + long tenantId, + long gameInstanceId, + long pointerVersion, + boolean visible, + boolean publicProductionRealm, + boolean requiresCharacterSelection, + String stateScope, + String characterCreationPolicy) { + this( + worldSlug, + worldDisplayName, + realmSlug, + realmDisplayName, + tenantId, + gameInstanceId, + pointerVersion, + visible, + publicProductionRealm, + requiresCharacterSelection, + stateScope, + characterCreationPolicy, + 0L); + } +} diff --git a/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/service/InitialAdmissionBindCatalogDescriptor.java b/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/service/InitialAdmissionBindCatalogDescriptor.java new file mode 100644 index 0000000000..c1472d91a2 --- /dev/null +++ b/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/service/InitialAdmissionBindCatalogDescriptor.java @@ -0,0 +1,16 @@ +package net.firedevops.firemud.gamesession.service; + +/** + * Selector and display metadata for the one visible public shared demo catalog per tenant. + * + *

This is an internal fixture-owner input, not an external catalog mutation API. The fixture + * coordinator must call it only after resolving the exact real Game Design tenant/template. + */ +public record InitialAdmissionBindCatalogDescriptor( + long tenantId, + long gameTemplateId, + String worldSlug, + String worldDisplayName, + String realmSlug, + String realmDisplayName, + boolean requiresCharacterSelection) {} diff --git a/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/service/InitialAdmissionBindHoldBinding.java b/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/service/InitialAdmissionBindHoldBinding.java new file mode 100644 index 0000000000..24d80c20f7 --- /dev/null +++ b/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/service/InitialAdmissionBindHoldBinding.java @@ -0,0 +1,17 @@ +package net.firedevops.firemud.gamesession.service; + +/** Exact World-issued hold identity and immutable request tuple passed to GS owner operations. */ +public record InitialAdmissionBindHoldBinding( + String holdId, + String holdFence, + long tenantId, + String realmUuid, + String playableStateNamespaceUuid, + String playableStateScope, + long gameInstanceId, + long versionId, + long activeLifecycleEpoch, + String initialAdmissionRequestId, + String requestDigest, + boolean expectedNoPriorPointer, + long expectedCatalogRevision) {} diff --git a/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/service/InitialAdmissionBindOwnerProof.java b/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/service/InitialAdmissionBindOwnerProof.java new file mode 100644 index 0000000000..a60244eae8 --- /dev/null +++ b/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/service/InitialAdmissionBindOwnerProof.java @@ -0,0 +1,32 @@ +package net.firedevops.firemud.gamesession.service; + +/** Durable local owner readback for one exact World initial-admission hold. */ +public record InitialAdmissionBindOwnerProof( + Outcome outcome, + String holdId, + String holdFence, + long tenantId, + String realmUuid, + String playableStateNamespaceUuid, + String playableStateScope, + long gameInstanceId, + long versionId, + long activeLifecycleEpoch, + String initialAdmissionRequestId, + String requestDigest, + boolean expectedNoPriorPointer, + long expectedCatalogRevision, + String ownerProofId, + String pointerAuditId, + long pointerVersion, + String pointerAuditRequestDigest, + boolean futureCommitPrevented) { + public enum Outcome { + COMMITTED, + ABORTED, + NOT_FOUND, + PENDING, + UNAVAILABLE, + ERROR + } +} diff --git a/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/service/InitialAdmissionBindOwnerProofReader.java b/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/service/InitialAdmissionBindOwnerProofReader.java new file mode 100644 index 0000000000..dc286a7eb3 --- /dev/null +++ b/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/service/InitialAdmissionBindOwnerProofReader.java @@ -0,0 +1,6 @@ +package net.firedevops.firemud.gamesession.service; + +/** Read-only, authenticated-adapter-facing port for reconciling a World hold against GS state. */ +public interface InitialAdmissionBindOwnerProofReader { + InitialAdmissionBindOwnerProof read(InitialAdmissionBindHoldBinding binding); +} diff --git a/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/service/InitialAdmissionBindOwnerService.java b/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/service/InitialAdmissionBindOwnerService.java new file mode 100644 index 0000000000..8bc90a4c31 --- /dev/null +++ b/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/service/InitialAdmissionBindOwnerService.java @@ -0,0 +1,18 @@ +package net.firedevops.firemud.gamesession.service; + +import net.firedevops.firemud.gamesession.entity.InitialAdmissionBindAttempt; +import net.firedevops.firemud.gamesession.entity.InitialAdmissionBindCatalog; + +/** Internal GS owner operations for durable first-pointer binding and reconciliation. */ +public interface InitialAdmissionBindOwnerService extends InitialAdmissionBindOwnerProofReader { + InitialAdmissionBindCatalog registerPublicSharedFixtureCatalog( + InitialAdmissionBindCatalogDescriptor descriptor); + + InitialAdmissionBindAttempt beginIntent(InitialAdmissionBindRequest request); + + InitialAdmissionBindAttempt attachHold(InitialAdmissionBindHoldBinding binding); + + InitialAdmissionBindOwnerProof commit(InitialAdmissionBindHoldBinding binding); + + InitialAdmissionBindOwnerProof abort(InitialAdmissionBindHoldBinding binding); +} diff --git a/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/service/InitialAdmissionBindRequest.java b/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/service/InitialAdmissionBindRequest.java new file mode 100644 index 0000000000..a3c17fc381 --- /dev/null +++ b/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/service/InitialAdmissionBindRequest.java @@ -0,0 +1,12 @@ +package net.firedevops.firemud.gamesession.service; + +/** Runtime-bound GS intent persisted before the coordinator contacts the World hold owner. */ +public record InitialAdmissionBindRequest( + long tenantId, + String worldSlug, + String realmSlug, + String initialAdmissionRequestId, + String requestDigest, + long gameInstanceId, + long versionId, + long activeLifecycleEpoch) {} diff --git a/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/service/impl/DatabaseGameplayAdmissionPointerAuthorityService.java b/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/service/impl/DatabaseGameplayAdmissionPointerAuthorityService.java index baa71c65e1..e3a7b9d134 100644 --- a/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/service/impl/DatabaseGameplayAdmissionPointerAuthorityService.java +++ b/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/service/impl/DatabaseGameplayAdmissionPointerAuthorityService.java @@ -78,9 +78,24 @@ public GameplayAdmissionPointerSnapshot upsertPointer(GameplayAdmissionPointerMu && pointer.getTenantId() != mutation.tenantId()) { throw new IllegalArgumentException("tenant_id does not own admission pointer"); } + if (pointer.getId() != null + && !Objects.equals(pointer.getStateScope(), mutation.stateScope())) { + throw new IllegalArgumentException( + "state_scope changes require a new playable-state lifecycle"); + } enforceExpectedPointerVersion(pointer, mutation.expectedPointerVersion()); + if (pointer.getId() != null + && runtimeTargetMatches(pointer, mutation) + && catalogPolicyMatches(pointer, mutation)) { + return toSnapshot(pointer); + } + boolean runtimeTargetChanged = + pointer.getId() == null || !runtimeTargetMatches(pointer, mutation); long nextPointerVersion = - pointer.getId() == null ? 1L : Math.max(pointer.getPointerVersion() + 1L, 1L); + pointer.getId() == null || runtimeTargetChanged + ? pointer.getId() == null ? 1L : Math.addExact(pointer.getPointerVersion(), 1L) + : pointer.getPointerVersion(); + long nextCatalogRevision = nextCatalogRevision(pointer, mutation); pointer.setWorldSlug(mutation.worldSlug()); pointer.setWorldDisplayName(mutation.worldDisplayName()); pointer.setRealmSlug(mutation.realmSlug()); @@ -88,6 +103,7 @@ public GameplayAdmissionPointerSnapshot upsertPointer(GameplayAdmissionPointerMu pointer.setTenantId(mutation.tenantId()); pointer.setGameInstanceId(mutation.gameInstanceId()); pointer.setPointerVersion(nextPointerVersion); + pointer.setCatalogRevision(nextCatalogRevision); pointer.setVisible(mutation.visible()); pointer.setPublicProductionRealm(mutation.publicProductionRealm()); pointer.setRequiresCharacterSelection(mutation.requiresCharacterSelection()); @@ -109,6 +125,9 @@ public GameplayAdmissionPointerSnapshot upsertPointer(GameplayAdmissionPointerMu event.setTenantId(saved.getTenantId()); event.setGameInstanceId(saved.getGameInstanceId()); event.setPointerVersion(saved.getPointerVersion()); + event.setCatalogRevision(saved.getCatalogRevision()); + event.setRealmId(saved.getRealmId()); + event.setPlayableStateNamespaceId(saved.getPlayableStateNamespaceId()); event.setVisible(saved.isVisible()); event.setPublicProductionRealm(saved.isPublicProductionRealm()); event.setRequiresCharacterSelection(saved.isRequiresCharacterSelection()); @@ -167,7 +186,43 @@ private GameplayAdmissionPointerSnapshot toSnapshot(GameplayAdmissionPointer poi pointer.isPublicProductionRealm(), pointer.isRequiresCharacterSelection(), pointer.getStateScope(), - pointer.getCharacterCreationPolicy()); + pointer.getCharacterCreationPolicy(), + pointer.getCatalogRevision() == null ? 0L : pointer.getCatalogRevision(), + pointer.getRealmId(), + pointer.getPlayableStateNamespaceId()); + } + + private long nextCatalogRevision( + GameplayAdmissionPointer pointer, GameplayAdmissionPointerMutation mutation) { + if (pointer.getId() == null) { + return 1L; + } + Long currentRevision = pointer.getCatalogRevision(); + if (currentRevision == null || currentRevision <= 0L) { + throw new IllegalStateException("Admission pointer catalog revision is missing or invalid"); + } + if (!catalogPolicyMatches(pointer, mutation)) { + return Math.addExact(currentRevision, 1L); + } + return currentRevision; + } + + private boolean catalogPolicyMatches( + GameplayAdmissionPointer pointer, GameplayAdmissionPointerMutation mutation) { + return Objects.equals(pointer.getWorldSlug(), mutation.worldSlug()) + && Objects.equals(pointer.getWorldDisplayName(), mutation.worldDisplayName()) + && Objects.equals(pointer.getRealmSlug(), mutation.realmSlug()) + && Objects.equals(pointer.getRealmDisplayName(), mutation.realmDisplayName()) + && pointer.isVisible() == mutation.visible() + && pointer.isPublicProductionRealm() == mutation.publicProductionRealm() + && pointer.isRequiresCharacterSelection() == mutation.requiresCharacterSelection() + && Objects.equals(pointer.getStateScope(), mutation.stateScope()) + && Objects.equals(pointer.getCharacterCreationPolicy(), mutation.characterCreationPolicy()); + } + + private boolean runtimeTargetMatches( + GameplayAdmissionPointer pointer, GameplayAdmissionPointerMutation mutation) { + return Objects.equals(pointer.getGameInstanceId(), mutation.gameInstanceId()); } private void validateMutation(GameplayAdmissionPointerMutation mutation) { diff --git a/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/service/impl/DatabaseInitialAdmissionBindOwnerService.java b/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/service/impl/DatabaseInitialAdmissionBindOwnerService.java new file mode 100644 index 0000000000..81526a7066 --- /dev/null +++ b/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/service/impl/DatabaseInitialAdmissionBindOwnerService.java @@ -0,0 +1,654 @@ +package net.firedevops.firemud.gamesession.service.impl; + +import edu.umd.cs.findbugs.annotations.SuppressFBWarnings; +import java.time.Instant; +import java.util.Objects; +import java.util.Optional; +import java.util.UUID; +import java.util.regex.Pattern; +import net.firedevops.firemud.gamesession.entity.GameInstance; +import net.firedevops.firemud.gamesession.entity.GameplayAdmissionPointer; +import net.firedevops.firemud.gamesession.entity.GameplayAdmissionPointerEvent; +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.repository.GameInstanceRepository; +import net.firedevops.firemud.gamesession.repository.GameplayAdmissionPointerEventRepository; +import net.firedevops.firemud.gamesession.repository.InitialAdmissionBindAttemptRepository; +import net.firedevops.firemud.gamesession.repository.InitialAdmissionBindCatalogRepository; +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 org.springframework.stereotype.Service; +import org.springframework.transaction.annotation.Transactional; + +@Service +@SuppressFBWarnings( + value = "CT_CONSTRUCTOR_THROW", + justification = + "Constructor validation fails fast for Spring-managed collaborators without exposing a" + + " partially initialized owner service.") +public class DatabaseInitialAdmissionBindOwnerService implements InitialAdmissionBindOwnerService { + private static final Pattern SHA_256 = Pattern.compile("[0-9a-f]{64}"); + private static final Pattern SLUG = Pattern.compile("[a-z0-9]+(?:-[a-z0-9]+)*"); + private static final String STATE_SCOPE = "SHARED"; + private static final String CHARACTER_CREATION_POLICY = "ALLOW_NEW"; + private static final String AUDIT_ACTOR = "game-session-initial-admission-bind"; + private static final String AUDIT_REASON = "initial admission pointer bind"; + + private final InitialAdmissionBindCatalogRepository catalogRepository; + private final InitialAdmissionBindAttemptRepository attemptRepository; + private final GameplayAdmissionPointerEventRepository eventRepository; + private final GameInstanceRepository gameInstanceRepository; + + public DatabaseInitialAdmissionBindOwnerService( + InitialAdmissionBindCatalogRepository catalogRepository, + InitialAdmissionBindAttemptRepository attemptRepository, + GameplayAdmissionPointerEventRepository eventRepository, + GameInstanceRepository gameInstanceRepository) { + this.catalogRepository = + Objects.requireNonNull(catalogRepository, "catalogRepository must not be null"); + this.attemptRepository = + Objects.requireNonNull(attemptRepository, "attemptRepository must not be null"); + this.eventRepository = + Objects.requireNonNull(eventRepository, "eventRepository must not be null"); + this.gameInstanceRepository = + Objects.requireNonNull(gameInstanceRepository, "gameInstanceRepository must not be null"); + } + + /** + * Persists the immutable visible public shared demo catalog row without creating an admission + * pointer. The run-owned fixture coordinator must first resolve the real tenant/template through + * Game Design; no startup configuration or external request is an authority source here. + */ + @Override + @Transactional + public InitialAdmissionBindCatalog registerPublicSharedFixtureCatalog( + InitialAdmissionBindCatalogDescriptor descriptor) { + validateCatalogDescriptor(descriptor); + catalogRepository.lockTenantCatalogAndSharedNamespace(descriptor.tenantId()); + Optional existing = + catalogRepository.findByTenantId(descriptor.tenantId()); + if (existing.isPresent()) { + requireSameCatalog(existing.get(), descriptor); + return existing.get(); + } + + UUID sharedNamespaceId = + catalogRepository.getOrCreateTenantSharedNamespace(descriptor.tenantId()); + return catalogRepository.insert(descriptor, UUID.randomUUID(), sharedNamespaceId); + } + + /** Persists the attempt before any coordinator call to the separate World hold owner. */ + @Override + @Transactional + public InitialAdmissionBindAttempt beginIntent(InitialAdmissionBindRequest request) { + validateRequest(request); + InitialAdmissionBindCatalog catalog = + catalogRepository + .findByTenantIdAndSelectors( + request.tenantId(), request.worldSlug(), request.realmSlug()) + .orElseThrow( + () -> + new IllegalArgumentException( + "INITIAL_ADMISSION_CATALOG_NOT_FOUND: owner catalog row is missing")); + attemptRepository.lockAttemptAndRealm( + request.tenantId(), request.initialAdmissionRequestId(), catalog.realmId()); + + Optional existing = + attemptRepository.findByTenantAndRequestIdForUpdate( + request.tenantId(), request.initialAdmissionRequestId()); + if (existing.isPresent()) { + requireSameRequest(existing.get(), request, catalog); + return existing.get(); + } + + requireTargetMatchesCatalogAndRequest(catalog, request); + if (attemptRepository.hasPointerForCatalog(catalog)) { + throw new IllegalStateException( + "INITIAL_ADMISSION_ALREADY_BOUND: catalog realm already has an admission pointer"); + } + if (attemptRepository.hasPointerForRuntimeTarget( + request.tenantId(), request.gameInstanceId())) { + throw new IllegalStateException( + "INITIAL_ADMISSION_RUNTIME_ALREADY_ROUTED: runtime target already has an admission pointer"); + } + Optional pending = + attemptRepository.findPendingByTenantAndRealmForUpdate( + request.tenantId(), catalog.realmId()); + if (pending.isPresent()) { + throw new IllegalStateException( + "INITIAL_ADMISSION_ATTEMPT_PENDING: another durable attempt owns this realm"); + } + + Instant now = Instant.now(); + return attemptRepository.insertPending( + new InitialAdmissionBindAttempt( + UUID.randomUUID(), + request.tenantId(), + request.initialAdmissionRequestId(), + request.requestDigest(), + catalog.realmId(), + catalog.playableStateNamespaceId(), + catalog.stateScope(), + true, + catalog.catalogRevision(), + request.gameInstanceId(), + request.versionId(), + request.activeLifecycleEpoch(), + null, + null, + Status.PENDING, + null, + null, + now, + now, + null)); + } + + @Override + @Transactional + public InitialAdmissionBindAttempt attachHold(InitialAdmissionBindHoldBinding binding) { + validateBinding(binding); + UUID realmId = UUID.fromString(binding.realmUuid()); + attemptRepository.lockAttemptAndRealm( + binding.tenantId(), binding.initialAdmissionRequestId(), realmId); + InitialAdmissionBindAttempt attempt = + requireAttemptForUpdate(binding.tenantId(), binding.initialAdmissionRequestId()); + requireSameBinding(attempt, binding); + return attachHoldIfNeeded(attempt, binding, Instant.now()); + } + + @Override + @Transactional + public InitialAdmissionBindOwnerProof commit(InitialAdmissionBindHoldBinding binding) { + validateBinding(binding); + UUID realmId = UUID.fromString(binding.realmUuid()); + attemptRepository.lockAttemptAndRealm( + binding.tenantId(), binding.initialAdmissionRequestId(), realmId); + InitialAdmissionBindAttempt attempt = + requireAttemptForUpdate(binding.tenantId(), binding.initialAdmissionRequestId()); + requireSameBinding(attempt, binding); + requireAttachedHold(attempt, binding); + + if (attempt.status() != Status.PENDING) { + return read(binding); + } + + InitialAdmissionBindCatalog catalog; + try { + catalog = requireCatalogForAttempt(attempt); + } catch (IllegalStateException exception) { + return proof(binding, Outcome.ERROR, null, null, 0L, null, false); + } + requireTargetMatchesCatalogAndRequest( + catalog, + new InitialAdmissionBindRequest( + attempt.tenantId(), + catalog.worldSlug(), + catalog.realmSlug(), + attempt.initialAdmissionRequestId(), + attempt.requestDigest(), + attempt.gameInstanceId(), + attempt.versionId(), + attempt.activeLifecycleEpoch())); + if (attemptRepository.hasPointerForCatalog(catalog) + || attemptRepository.hasPointerForRuntimeTarget( + attempt.tenantId(), attempt.gameInstanceId())) { + throw new IllegalStateException( + "INITIAL_ADMISSION_NO_PRIOR_POINTER_FAILED: a pointer exists before initial bind"); + } + + Instant now = Instant.now(); + GameplayAdmissionPointer pointer = + attemptRepository.insertPointer(catalog, attempt.gameInstanceId(), now); + GameplayAdmissionPointerEvent auditEvent = new GameplayAdmissionPointerEvent(); + auditEvent.setWorldSlug(pointer.getWorldSlug()); + auditEvent.setRealmSlug(pointer.getRealmSlug()); + auditEvent.setWorldDisplayName(pointer.getWorldDisplayName()); + auditEvent.setRealmDisplayName(pointer.getRealmDisplayName()); + auditEvent.setTenantId(pointer.getTenantId()); + auditEvent.setGameInstanceId(pointer.getGameInstanceId()); + auditEvent.setPointerVersion(pointer.getPointerVersion()); + auditEvent.setCatalogRevision(pointer.getCatalogRevision()); + auditEvent.setRealmId(pointer.getRealmId()); + auditEvent.setPlayableStateNamespaceId(pointer.getPlayableStateNamespaceId()); + auditEvent.setVisible(pointer.isVisible()); + auditEvent.setPublicProductionRealm(pointer.isPublicProductionRealm()); + auditEvent.setRequiresCharacterSelection(pointer.isRequiresCharacterSelection()); + auditEvent.setStateScope(pointer.getStateScope()); + auditEvent.setCharacterCreationPolicy(pointer.getCharacterCreationPolicy()); + auditEvent.setActorPrincipal(AUDIT_ACTOR); + auditEvent.setReason(AUDIT_REASON); + auditEvent.setControlPlaneRequestId(attempt.initialAdmissionRequestId()); + auditEvent.setOccurredAt(now); + GameplayAdmissionPointerEvent savedAuditEvent = eventRepository.save(auditEvent); + + attemptRepository.markCommitted(attempt, pointer.getId(), savedAuditEvent.getId(), now); + InitialAdmissionBindOwnerProof proof = read(binding); + if (proof.outcome() != Outcome.COMMITTED) { + throw new IllegalStateException( + "INITIAL_ADMISSION_COMMIT_READBACK_INVALID: pointer, audit, and ledger did not agree"); + } + return proof; + } + + @Override + @Transactional + public InitialAdmissionBindOwnerProof abort(InitialAdmissionBindHoldBinding binding) { + validateBinding(binding); + UUID realmId = UUID.fromString(binding.realmUuid()); + attemptRepository.lockAttemptAndRealm( + binding.tenantId(), binding.initialAdmissionRequestId(), realmId); + InitialAdmissionBindAttempt attempt = + requireAttemptForUpdate(binding.tenantId(), binding.initialAdmissionRequestId()); + requireSameBinding(attempt, binding); + + if (attempt.status() == Status.COMMITTED) { + return read(binding); + } + if (attempt.status() == Status.ABORTED) { + requireAttachedHold(attempt, binding); + return read(binding); + } + + attempt = attachHoldIfNeeded(attempt, binding, Instant.now()); + attemptRepository.markAborted(attempt, Instant.now()); + InitialAdmissionBindOwnerProof proof = read(binding); + if (proof.outcome() != Outcome.ABORTED || !proof.futureCommitPrevented()) { + throw new IllegalStateException( + "INITIAL_ADMISSION_ABORT_READBACK_INVALID: durable abort tombstone was not proven"); + } + return proof; + } + + @Override + @Transactional(readOnly = true) + public InitialAdmissionBindOwnerProof read(InitialAdmissionBindHoldBinding binding) { + if (!isValidBinding(binding)) { + return proof(binding, Outcome.ERROR, null, null, 0L, null, false); + } + Optional maybeAttempt = + attemptRepository.findByTenantAndRequestId( + binding.tenantId(), binding.initialAdmissionRequestId()); + if (maybeAttempt.isEmpty()) { + return proof(binding, Outcome.NOT_FOUND, null, null, 0L, null, false); + } + InitialAdmissionBindAttempt attempt = maybeAttempt.get(); + if (!sameBindingTuple(attempt, binding)) { + return proof(binding, Outcome.ERROR, null, null, 0L, null, false); + } + if (attempt.holdId() == null || attempt.holdFence() == null) { + if (attempt.status() == Status.PENDING) { + return proof( + binding, Outcome.PENDING, attempt.attemptId().toString(), null, 0L, null, false); + } + return proof(binding, Outcome.ERROR, null, null, 0L, null, false); + } + if (!attempt.holdId().toString().equals(binding.holdId()) + || !attempt.holdFence().toString().equals(binding.holdFence())) { + return proof(binding, Outcome.ERROR, null, null, 0L, null, false); + } + + return switch (attempt.status()) { + case PENDING -> + proof(binding, Outcome.PENDING, attempt.attemptId().toString(), null, 0L, null, false); + case COMMITTED -> readCommittedProof(attempt, binding); + case ABORTED -> readAbortedProof(attempt, binding); + }; + } + + private InitialAdmissionBindOwnerProof readCommittedProof( + InitialAdmissionBindAttempt attempt, InitialAdmissionBindHoldBinding binding) { + if (attempt.pointerId() == null + || attempt.auditEventId() == null + || attempt.terminalAt() == null) { + return proof(binding, Outcome.ERROR, null, null, 0L, null, false); + } + InitialAdmissionBindCatalog catalog; + try { + catalog = requireCatalogForAttempt(attempt); + } catch (IllegalStateException exception) { + return proof(binding, Outcome.ERROR, null, null, 0L, null, false); + } + Optional maybePointer = + attemptRepository.findPointerById(attempt.pointerId()); + if (maybePointer.isEmpty()) { + return proof(binding, Outcome.ERROR, null, null, 0L, null, false); + } + GameplayAdmissionPointer pointer = maybePointer.get(); + Optional maybeAudit = + eventRepository + .findByTenantIdAndWorldSlugAndRealmSlugOrderByOccurredAtDesc( + attempt.tenantId(), catalog.worldSlug(), catalog.realmSlug()) + .stream() + .filter(event -> Objects.equals(event.getId(), attempt.auditEventId())) + .findFirst(); + if (maybeAudit.isEmpty() + || !matchesCommittedEvidence(attempt, catalog, pointer, maybeAudit.get())) { + return proof(binding, Outcome.ERROR, null, null, 0L, null, false); + } + GameplayAdmissionPointerEvent audit = maybeAudit.get(); + return proof( + binding, + Outcome.COMMITTED, + attempt.attemptId().toString(), + Long.toString(audit.getId()), + audit.getPointerVersion(), + attempt.requestDigest(), + false); + } + + private InitialAdmissionBindOwnerProof readAbortedProof( + InitialAdmissionBindAttempt attempt, InitialAdmissionBindHoldBinding binding) { + if (attempt.pointerId() != null + || attempt.auditEventId() != null + || attempt.terminalAt() == null) { + return proof(binding, Outcome.ERROR, null, null, 0L, null, false); + } + return proof(binding, Outcome.ABORTED, attempt.attemptId().toString(), null, 0L, null, true); + } + + private boolean matchesCommittedEvidence( + InitialAdmissionBindAttempt attempt, + InitialAdmissionBindCatalog catalog, + GameplayAdmissionPointer pointer, + GameplayAdmissionPointerEvent audit) { + return pointer.getId().equals(attempt.pointerId()) + && Objects.equals(pointer.getTenantId(), attempt.tenantId()) + && Objects.equals(pointer.getWorldSlug(), catalog.worldSlug()) + && Objects.equals(pointer.getRealmSlug(), catalog.realmSlug()) + && Objects.equals(pointer.getRealmId(), attempt.realmId()) + && Objects.equals(pointer.getPlayableStateNamespaceId(), attempt.playableStateNamespaceId()) + && pointer.getPointerVersion() != null + && pointer.getPointerVersion() >= 1L + && Objects.equals(audit.getId(), attempt.auditEventId()) + && Objects.equals(audit.getTenantId(), attempt.tenantId()) + && Objects.equals(audit.getWorldSlug(), catalog.worldSlug()) + && Objects.equals(audit.getRealmSlug(), catalog.realmSlug()) + && Objects.equals(audit.getWorldDisplayName(), catalog.worldDisplayName()) + && Objects.equals(audit.getRealmDisplayName(), catalog.realmDisplayName()) + && Objects.equals(audit.getGameInstanceId(), attempt.gameInstanceId()) + && Objects.equals(audit.getPointerVersion(), 1L) + && Objects.equals(audit.getCatalogRevision(), attempt.catalogRevision()) + && Objects.equals(audit.getRealmId(), attempt.realmId()) + && Objects.equals(audit.getPlayableStateNamespaceId(), attempt.playableStateNamespaceId()) + && audit.isVisible() + && audit.isPublicProductionRealm() + && audit.isRequiresCharacterSelection() == catalog.requiresCharacterSelection() + && Objects.equals(audit.getStateScope(), STATE_SCOPE) + && Objects.equals(audit.getCharacterCreationPolicy(), CHARACTER_CREATION_POLICY) + && Objects.equals(audit.getControlPlaneRequestId(), attempt.initialAdmissionRequestId()) + && Objects.equals(audit.getActorPrincipal(), AUDIT_ACTOR) + && Objects.equals(audit.getReason(), AUDIT_REASON) + && audit.getOccurredAt() != null; + } + + private InitialAdmissionBindCatalog requireCatalogForAttempt( + InitialAdmissionBindAttempt attempt) { + InitialAdmissionBindCatalog catalog = + catalogRepository + .findByTenantId(attempt.tenantId()) + .orElseThrow( + () -> + new IllegalStateException( + "INITIAL_ADMISSION_CATALOG_MISSING: durable attempt lost its owner catalog")); + if (!catalog.realmId().equals(attempt.realmId()) + || !catalog.playableStateNamespaceId().equals(attempt.playableStateNamespaceId()) + || catalog.catalogRevision() != attempt.catalogRevision() + || !catalog.stateScope().equals(attempt.playableStateScope())) { + throw new IllegalStateException( + "INITIAL_ADMISSION_CATALOG_MISMATCH: attempt no longer matches its owner catalog"); + } + return catalog; + } + + private InitialAdmissionBindAttempt attachHoldIfNeeded( + InitialAdmissionBindAttempt attempt, InitialAdmissionBindHoldBinding binding, Instant now) { + if (attempt.holdId() != null || attempt.holdFence() != null) { + requireAttachedHold(attempt, binding); + return attempt; + } + return attemptRepository.attachHold( + attempt, UUID.fromString(binding.holdId()), UUID.fromString(binding.holdFence()), now); + } + + private void requireAttachedHold( + InitialAdmissionBindAttempt attempt, InitialAdmissionBindHoldBinding binding) { + if (attempt.holdId() == null + || attempt.holdFence() == null + || !attempt.holdId().toString().equals(binding.holdId()) + || !attempt.holdFence().toString().equals(binding.holdFence())) { + throw new IllegalArgumentException( + "IDEMPOTENCY_CONFLICT: initial admission hold identity changed or was not attached"); + } + } + + private InitialAdmissionBindAttempt requireAttemptForUpdate(long tenantId, String requestId) { + return attemptRepository + .findByTenantAndRequestIdForUpdate(tenantId, requestId) + .orElseThrow( + () -> + new IllegalStateException( + "INITIAL_ADMISSION_INTENT_NOT_FOUND: durable GS intent is required first")); + } + + private void requireSameCatalog( + InitialAdmissionBindCatalog catalog, InitialAdmissionBindCatalogDescriptor descriptor) { + if (catalog.tenantId() != descriptor.tenantId() + || catalog.gameTemplateId() != descriptor.gameTemplateId() + || !catalog.worldSlug().equals(descriptor.worldSlug()) + || !catalog.worldDisplayName().equals(descriptor.worldDisplayName()) + || !catalog.realmSlug().equals(descriptor.realmSlug()) + || !catalog.realmDisplayName().equals(descriptor.realmDisplayName()) + || catalog.requiresCharacterSelection() != descriptor.requiresCharacterSelection()) { + throw new IllegalArgumentException( + "IDEMPOTENCY_CONFLICT: initial admission catalog metadata changed for tenant"); + } + } + + private void requireSameRequest( + InitialAdmissionBindAttempt attempt, + InitialAdmissionBindRequest request, + InitialAdmissionBindCatalog catalog) { + if (attempt.tenantId() != request.tenantId() + || !attempt.initialAdmissionRequestId().equals(request.initialAdmissionRequestId()) + || !attempt.requestDigest().equals(request.requestDigest()) + || !attempt.realmId().equals(catalog.realmId()) + || !attempt.playableStateNamespaceId().equals(catalog.playableStateNamespaceId()) + || !attempt.playableStateScope().equals(catalog.stateScope()) + || !attempt.expectedNoPriorPointer() + || attempt.catalogRevision() != catalog.catalogRevision() + || attempt.gameInstanceId() != request.gameInstanceId() + || attempt.versionId() != request.versionId() + || attempt.activeLifecycleEpoch() != request.activeLifecycleEpoch()) { + throw new IllegalArgumentException( + "IDEMPOTENCY_CONFLICT: initial admission request identity changed"); + } + } + + private void requireSameBinding( + InitialAdmissionBindAttempt attempt, InitialAdmissionBindHoldBinding binding) { + if (!sameBindingTuple(attempt, binding)) { + throw new IllegalArgumentException( + "IDEMPOTENCY_CONFLICT: initial admission hold tuple does not match durable intent"); + } + } + + private boolean sameBindingTuple( + InitialAdmissionBindAttempt attempt, InitialAdmissionBindHoldBinding binding) { + return attempt.tenantId() == binding.tenantId() + && attempt.realmId().toString().equals(binding.realmUuid()) + && attempt + .playableStateNamespaceId() + .toString() + .equals(binding.playableStateNamespaceUuid()) + && attempt.playableStateScope().equals(binding.playableStateScope()) + && attempt.gameInstanceId() == binding.gameInstanceId() + && attempt.versionId() == binding.versionId() + && attempt.activeLifecycleEpoch() == binding.activeLifecycleEpoch() + && attempt.initialAdmissionRequestId().equals(binding.initialAdmissionRequestId()) + && attempt.requestDigest().equals(binding.requestDigest()) + && attempt.expectedNoPriorPointer() == binding.expectedNoPriorPointer() + && attempt.catalogRevision() == binding.expectedCatalogRevision(); + } + + private void requireTargetMatchesCatalogAndRequest( + InitialAdmissionBindCatalog catalog, InitialAdmissionBindRequest request) { + GameInstance gameInstance = + gameInstanceRepository + .findByTenantIdAndGameInstanceIdForUpdate(request.tenantId(), request.gameInstanceId()) + .orElseThrow( + () -> + new IllegalArgumentException( + "GAME_INSTANCE_NOT_FOUND: initial admission target is not GS-owned")); + if (!Objects.equals(gameInstance.getGameTemplateId(), catalog.gameTemplateId()) + || !Objects.equals(gameInstance.getVersionId(), request.versionId())) { + throw new IllegalArgumentException( + "INITIAL_ADMISSION_TARGET_MISMATCH: target does not match persisted tenant/template/version"); + } + } + + private void validateCatalogDescriptor(InitialAdmissionBindCatalogDescriptor descriptor) { + if (descriptor == null || descriptor.tenantId() <= 0L || descriptor.gameTemplateId() <= 0L) { + throw new IllegalArgumentException( + "INVALID_ARGUMENT: public shared fixture catalog requires positive tenant and template IDs"); + } + requireSlug(descriptor.worldSlug(), "worldSlug"); + requireText(descriptor.worldDisplayName(), "worldDisplayName", 200); + requireSlug(descriptor.realmSlug(), "realmSlug"); + requireText(descriptor.realmDisplayName(), "realmDisplayName", 200); + } + + private void validateRequest(InitialAdmissionBindRequest request) { + if (request == null + || request.tenantId() <= 0L + || request.gameInstanceId() <= 0L + || request.versionId() <= 0L + || request.activeLifecycleEpoch() <= 0L) { + throw new IllegalArgumentException( + "INVALID_ARGUMENT: initial admission request requires positive tenant, target, version, and lifecycle epoch"); + } + requireText(request.initialAdmissionRequestId(), "initialAdmissionRequestId", 128); + if (request.requestDigest() == null || !SHA_256.matcher(request.requestDigest()).matches()) { + throw new IllegalArgumentException( + "INVALID_ARGUMENT: requestDigest must be lowercase SHA-256 hex"); + } + requireSlug(request.worldSlug(), "worldSlug"); + requireSlug(request.realmSlug(), "realmSlug"); + } + + private void validateBinding(InitialAdmissionBindHoldBinding binding) { + if (!isValidBinding(binding)) { + throw new IllegalArgumentException( + "INVALID_ARGUMENT: initial admission hold binding is incomplete or unsupported"); + } + } + + private boolean isValidBinding(InitialAdmissionBindHoldBinding binding) { + if (binding == null + || binding.tenantId() <= 0L + || binding.gameInstanceId() <= 0L + || binding.versionId() <= 0L + || binding.activeLifecycleEpoch() <= 0L + || binding.expectedCatalogRevision() <= 0L + || !binding.expectedNoPriorPointer() + || !STATE_SCOPE.equals(binding.playableStateScope()) + || binding.requestDigest() == null + || !SHA_256.matcher(binding.requestDigest()).matches()) { + return false; + } + try { + requireText(binding.initialAdmissionRequestId(), "initialAdmissionRequestId", 128); + return isCanonicalUuid(binding.holdId()) + && isCanonicalUuid(binding.holdFence()) + && isCanonicalUuid(binding.realmUuid()) + && isCanonicalUuid(binding.playableStateNamespaceUuid()); + } catch (IllegalArgumentException exception) { + return false; + } + } + + private boolean isCanonicalUuid(String value) { + if (value == null) { + return false; + } + try { + return UUID.fromString(value).toString().equals(value); + } catch (IllegalArgumentException exception) { + return false; + } + } + + private InitialAdmissionBindOwnerProof proof( + InitialAdmissionBindHoldBinding binding, + Outcome outcome, + String ownerProofId, + String pointerAuditId, + long pointerVersion, + String pointerAuditRequestDigest, + boolean futureCommitPrevented) { + if (binding == null) { + return new InitialAdmissionBindOwnerProof( + outcome, + null, + null, + 0L, + null, + null, + null, + 0L, + 0L, + 0L, + null, + null, + false, + 0L, + ownerProofId, + pointerAuditId, + pointerVersion, + pointerAuditRequestDigest, + 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(), + ownerProofId, + pointerAuditId, + pointerVersion, + pointerAuditRequestDigest, + futureCommitPrevented); + } + + private static void requireSlug(String value, String name) { + if (value == null || value.length() > 120 || !SLUG.matcher(value).matches()) { + throw new IllegalArgumentException("INVALID_ARGUMENT: " + name + " is not a canonical slug"); + } + } + + private static void requireText(String value, String name, int maxLength) { + if (value == null + || value.isBlank() + || value.length() > maxLength + || !value.equals(value.trim()) + || value.indexOf('\n') >= 0 + || value.indexOf('\r') >= 0) { + throw new IllegalArgumentException("INVALID_ARGUMENT: " + name + " is invalid"); + } + } +} diff --git a/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/service/impl/GameSessionAdmissionPointerControlPlaneService.java b/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/service/impl/GameSessionAdmissionPointerControlPlaneService.java index 614b33e18c..42186f8832 100644 --- a/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/service/impl/GameSessionAdmissionPointerControlPlaneService.java +++ b/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/service/impl/GameSessionAdmissionPointerControlPlaneService.java @@ -20,6 +20,12 @@ @Service final class GameSessionAdmissionPointerControlPlaneService { + static final class AdmissionPointerMutationPreconditionException extends RuntimeException { + AdmissionPointerMutationPreconditionException(String message) { + super(message); + } + } + private final GameInstanceRepository gameInstanceRepository; private final GameplayAdmissionPointerAuthorityService gameplayAdmissionPointerAuthorityService; private final VersionUpgradePreparationService versionUpgradePreparationService; @@ -76,28 +82,18 @@ ListAdmissionPointerAuditResponse listAdmissionPointerAudit( SetAdmissionPointerResponse setAdmissionPointer( long tenantId, long targetGameInstanceId, SetAdmissionPointerRequest request) { - validatePreparedUpgradeForPointerChange(request, tenantId, targetGameInstanceId); - gameplayAdmissionPointerAuthorityService.upsertPointer( - new GameplayAdmissionPointerMutation( - request.getWorldSlug(), - request.getWorldDisplayName(), - request.getRealmSlug(), - request.getRealmDisplayName(), - tenantId, - targetGameInstanceId, - request.getVisible(), - request.getPublicProductionRealm(), - request.getRequiresCharacterSelection(), - request.getStateScope(), - request.getCharacterCreationPolicy(), - request.getActorPrincipal(), - request.getReason(), - request.getControlPlaneRequestId(), - request.hasExpectedPointerVersion() ? request.getExpectedPointerVersion() : null, - normalizeBlank(request.getPreparedVersionUpgradeId()))); - return SetAdmissionPointerResponse.newBuilder() - .setPointer(latestAuditEntry(tenantId, request.getWorldSlug(), request.getRealmSlug())) - .build(); + GameplayAdmissionPointerSnapshot currentPointer = + gameplayAdmissionPointerAuthorityService + .findPointer(tenantId, request.getWorldSlug(), request.getRealmSlug()) + .orElse(null); + if (currentPointer != null) { + throw new AdmissionPointerMutationPreconditionException( + "admission-pointer updates are temporarily disabled until catalog revision " + + "preconditions are supported"); + } + throw new AdmissionPointerMutationPreconditionException( + "admission-pointer creation is temporarily disabled until catalog revision and " + + "stable realm/namespace identity preconditions are supported"); } ExecutePreparedVersionCutoverResponse executePreparedVersionCutover( @@ -107,6 +103,7 @@ ExecutePreparedVersionCutoverResponse executePreparedVersionCutover( requireText(request.getPreparedVersionUpgradeId(), "prepared_version_upgrade_id is required"); requireText(request.getActorPrincipal(), "actor_principal is required"); requireText(request.getControlPlaneRequestId(), "control_plane_request_id is required"); + rejectPreparedCutoverUntilCatalogRevisionPreconditionsAreSupported(); GameplayAdmissionPointerSnapshot currentPointer = gameplayAdmissionPointerAuthorityService .findPointer(tenantId, request.getWorldSlug(), request.getRealmSlug()) @@ -197,21 +194,6 @@ private AdmissionPointerControlPlaneEntry toEntry(GameplayAdmissionPointerAuditE return builder.build(); } - private void validatePreparedUpgradeForPointerChange( - SetAdmissionPointerRequest request, long tenantId, long targetGameInstanceId) { - GameplayAdmissionPointerSnapshot currentPointer = - gameplayAdmissionPointerAuthorityService - .findPointer(tenantId, request.getWorldSlug(), request.getRealmSlug()) - .orElse(null); - validatePreparedUpgradeForPointerChange( - request.getWorldSlug(), - request.getRealmSlug(), - tenantId, - targetGameInstanceId, - request.getPreparedVersionUpgradeId(), - currentPointer); - } - private void validatePreparedUpgradeForPointerChange( String worldSlug, String realmSlug, @@ -287,6 +269,12 @@ private AdmissionPointerControlPlaneEntry currentExecutedCutoverEntryIfSameReque return entry; } + private void rejectPreparedCutoverUntilCatalogRevisionPreconditionsAreSupported() { + throw new AdmissionPointerMutationPreconditionException( + "prepared cutover is temporarily disabled until catalog revision preconditions " + + "are supported"); + } + private GameInstance getInstanceOrThrow(long gameInstanceId) { return gameInstanceRepository .findById(gameInstanceId) diff --git a/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/service/impl/GameSessionControlPlaneGrpcService.java b/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/service/impl/GameSessionControlPlaneGrpcService.java index 089849a521..a355e5def8 100644 --- a/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/service/impl/GameSessionControlPlaneGrpcService.java +++ b/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/service/impl/GameSessionControlPlaneGrpcService.java @@ -9,6 +9,7 @@ import net.firedevops.firemud.common.security.AdminRoleGuard; import net.firedevops.firemud.common.security.SessionContext; import net.firedevops.firemud.gamesession.service.AdmissionPointerVersionMismatchException; +import net.firedevops.firemud.gamesession.service.impl.GameSessionAdmissionPointerControlPlaneService.AdmissionPointerMutationPreconditionException; import net.firedevops.firemud.gamesession.v1.EnqueueAutomationCommandIfAbsentRequest; import net.firedevops.firemud.gamesession.v1.EnqueueAutomationCommandIfAbsentResponse; import net.firedevops.firemud.gamesession.v1.ExecutePreparedVersionCutoverRequest; @@ -600,6 +601,13 @@ public void setAdmissionPointer( .build(); responseObserver.onNext(response); responseObserver.onCompleted(); + } catch (AdmissionPointerMutationPreconditionException ex) { + SetAdmissionPointerResponse response = + SetAdmissionPointerResponse.newBuilder() + .setError(GrpcAppErrors.error(meterRegistry, "FAILED_PRECONDITION", ex.getMessage())) + .build(); + responseObserver.onNext(response); + responseObserver.onCompleted(); } catch (AdmissionPointerVersionMismatchException ex) { SetAdmissionPointerResponse response = SetAdmissionPointerResponse.newBuilder() @@ -655,6 +663,13 @@ public void executePreparedVersionCutover( .build(); responseObserver.onNext(response); responseObserver.onCompleted(); + } catch (AdmissionPointerMutationPreconditionException ex) { + ExecutePreparedVersionCutoverResponse response = + ExecutePreparedVersionCutoverResponse.newBuilder() + .setError(GrpcAppErrors.error(meterRegistry, "FAILED_PRECONDITION", ex.getMessage())) + .build(); + responseObserver.onNext(response); + responseObserver.onCompleted(); } catch (AdmissionPointerVersionMismatchException ex) { ExecutePreparedVersionCutoverResponse response = ExecutePreparedVersionCutoverResponse.newBuilder() diff --git a/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/service/impl/GameSessionGrpcService.java b/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/service/impl/GameSessionGrpcService.java index f39849a79b..a79bca4ebe 100644 --- a/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/service/impl/GameSessionGrpcService.java +++ b/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/service/impl/GameSessionGrpcService.java @@ -519,20 +519,38 @@ public void queryAccountPresence( public void listGameplayWorlds( ListGameplayWorldsRequest request, StreamObserver responseObserver) { - ListGameplayWorldsResponse response = - ListGameplayWorldsResponse.newBuilder() - .addAllWorlds( - gameplayWorldCatalog.visibleWorlds().stream() - .map( - world -> - net.firedevops.firemud.gamesession.v1.GameplayWorld.newBuilder() - .setWorldSlug(world.slug()) - .setDisplayName(world.displayName()) - .build()) - .toList()) - .build(); - responseObserver.onNext(response); - responseObserver.onCompleted(); + try { + ListGameplayWorldsResponse response = + ListGameplayWorldsResponse.newBuilder() + .addAllWorlds( + gameplayWorldCatalog.visibleWorldsFromAuthoritySnapshot().stream() + .map( + world -> + net.firedevops.firemud.gamesession.v1.GameplayWorld.newBuilder() + .setWorldSlug(world.slug()) + .setDisplayName(world.displayName()) + .build()) + .toList()) + .build(); + responseObserver.onNext(response); + responseObserver.onCompleted(); + } catch (GameplayWorldCatalog.AuthorityPointerUnavailableException ex) { + ListGameplayWorldsResponse response = + ListGameplayWorldsResponse.newBuilder() + .setError( + GrpcAppErrors.error( + meterRegistry, "ADMISSION_POINTER_UNAVAILABLE", ex.getMessage())) + .build(); + responseObserver.onNext(response); + responseObserver.onCompleted(); + } catch (Exception ex) { + ListGameplayWorldsResponse response = + ListGameplayWorldsResponse.newBuilder() + .setError(GrpcAppErrors.internal(meterRegistry, LOG, "ListGameplayWorlds", ex)) + .build(); + responseObserver.onNext(response); + responseObserver.onCompleted(); + } } @Override @@ -543,14 +561,23 @@ public void listGameplayRealms( try { WorldView world = gameplayWorldCatalog - .resolveWorld(request.getWorldSlug()) + .resolveWorldFromAuthoritySnapshot(request.getWorldSlug()) .orElseThrow(() -> new IllegalArgumentException("Unknown gameplay world selection")); + List realms = + gameplayWorldCatalog.visibleRealms(world).stream() + .map(realm -> toGameplayRealm(world.slug(), realm)) + .toList(); + ListGameplayRealmsResponse response = + ListGameplayRealmsResponse.newBuilder().addAllRealms(realms).build(); + responseObserver.onNext(response); + responseObserver.onCompleted(); + } catch (AuthorityProjectionUnavailableException + | GameplayWorldCatalog.AuthorityPointerUnavailableException ex) { ListGameplayRealmsResponse response = ListGameplayRealmsResponse.newBuilder() - .addAllRealms( - gameplayWorldCatalog.visibleRealms(world).stream() - .map(realm -> toGameplayRealm(world.slug(), realm)) - .toList()) + .setError( + GrpcAppErrors.error( + meterRegistry, "ADMISSION_POINTER_UNAVAILABLE", ex.getMessage())) .build(); responseObserver.onNext(response); responseObserver.onCompleted(); @@ -561,6 +588,13 @@ public void listGameplayRealms( .build(); responseObserver.onNext(response); responseObserver.onCompleted(); + } catch (Exception ex) { + ListGameplayRealmsResponse response = + ListGameplayRealmsResponse.newBuilder() + .setError(GrpcAppErrors.internal(meterRegistry, LOG, "ListGameplayRealms", ex)) + .build(); + responseObserver.onNext(response); + responseObserver.onCompleted(); } } @@ -576,6 +610,9 @@ public void getAdmissionPointer( gameplayAdmissionPointerAuthorityService .findPointer(tenantId, request.getWorldSlug(), request.getRealmSlug()) .orElseThrow(() -> new IllegalArgumentException("Unknown gameplay realm selection")); + if (realm.visible() && realm.publicProductionRealm()) { + gameplayWorldCatalog.requireUniqueVisiblePublicProductionRealm(realm); + } GetAdmissionPointerResponse response = GetAdmissionPointerResponse.newBuilder() .setAdmissionPointer( @@ -592,10 +629,25 @@ public void getAdmissionPointer( .setPublicProductionRealm(realm.publicProductionRealm()) .setStateScope(realm.stateScope()) .setCharacterCreationPolicy(realm.characterCreationPolicy()) + .setCatalogRevision(requireCatalogRevision(realm.catalogRevision())) + .setRealmId(requireIdentity(realm.realmId(), "realmId")) + .setPlayableStateNamespaceId( + requireIdentity( + realm.playableStateNamespaceId(), "playableStateNamespaceId")) .build()) .build(); responseObserver.onNext(response); responseObserver.onCompleted(); + } catch (AuthorityProjectionUnavailableException + | GameplayWorldCatalog.AuthorityPointerUnavailableException ex) { + GetAdmissionPointerResponse response = + GetAdmissionPointerResponse.newBuilder() + .setError( + GrpcAppErrors.error( + meterRegistry, "ADMISSION_POINTER_UNAVAILABLE", ex.getMessage())) + .build(); + responseObserver.onNext(response); + responseObserver.onCompleted(); } catch (IllegalArgumentException ex) { GetAdmissionPointerResponse response = GetAdmissionPointerResponse.newBuilder() @@ -778,9 +830,35 @@ private net.firedevops.firemud.gamesession.v1.GameplayRealm toGameplayRealm( .setPublicProductionRealm(realm.publicProductionRealm()) .setStateScope(realm.stateScope()) .setCharacterCreationPolicy(realm.characterCreationPolicy()) + .setCatalogRevision(requireCatalogRevision(realm.catalogRevision())) + .setRealmId(requireIdentity(realm.realmId(), "realmId")) + .setPlayableStateNamespaceId( + requireIdentity(realm.playableStateNamespaceId(), "playableStateNamespaceId")) .build(); } + private static String requireIdentity(java.util.UUID identity, String fieldName) { + if (identity == null) { + throw new AuthorityProjectionUnavailableException( + "Authoritative gameplay " + fieldName + " is missing"); + } + return identity.toString(); + } + + private static long requireCatalogRevision(long catalogRevision) { + if (catalogRevision <= 0L) { + throw new AuthorityProjectionUnavailableException( + "Authoritative gameplay catalog revision is missing or invalid"); + } + return catalogRevision; + } + + private static final class AuthorityProjectionUnavailableException extends RuntimeException { + private AuthorityProjectionUnavailableException(String message) { + super(message); + } + } + private static final class AuthorizationException extends RuntimeException { private AuthorizationException(String message) { super(message); diff --git a/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/service/impl/GameSessionRuntimeControlPlaneReadService.java b/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/service/impl/GameSessionRuntimeControlPlaneReadService.java index b00b85390d..a9392253b3 100644 --- a/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/service/impl/GameSessionRuntimeControlPlaneReadService.java +++ b/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/service/impl/GameSessionRuntimeControlPlaneReadService.java @@ -373,20 +373,31 @@ private GameplayRoutingBundle toGameplayRoutingBundle(GameplayAdmissionPointerSn private AdmissionPointerControlPlaneEntry toControlPlaneEntry( GameplayAdmissionPointerSnapshot pointer) { - return AdmissionPointerControlPlaneEntry.newBuilder() - .setWorldSlug(normalizeBlank(pointer.worldSlug())) - .setWorldDisplayName(normalizeBlank(pointer.worldDisplayName())) - .setRealmSlug(normalizeBlank(pointer.realmSlug())) - .setRealmDisplayName(normalizeBlank(pointer.realmDisplayName())) - .setTenantId(Long.toString(pointer.tenantId())) - .setGameInstanceId(Long.toString(pointer.gameInstanceId())) - .setPointerVersion(pointer.pointerVersion()) - .setVisible(pointer.visible()) - .setRequiresCharacterSelection(pointer.requiresCharacterSelection()) - .setStateScope(normalizeBlank(pointer.stateScope())) - .setCharacterCreationPolicy(normalizeBlank(pointer.characterCreationPolicy())) - .setPublicProductionRealm(pointer.publicProductionRealm()) - .build(); + if (pointer.catalogRevision() <= 0L + || pointer.realmId() == null + || pointer.playableStateNamespaceId() == null) { + throw new RuntimeStateException( + "ADMISSION_POINTER_AUTHORITY_UNAVAILABLE", + "current admission pointer durable identity or catalog revision is unavailable"); + } + AdmissionPointerControlPlaneEntry.Builder builder = + AdmissionPointerControlPlaneEntry.newBuilder() + .setWorldSlug(normalizeBlank(pointer.worldSlug())) + .setWorldDisplayName(normalizeBlank(pointer.worldDisplayName())) + .setRealmSlug(normalizeBlank(pointer.realmSlug())) + .setRealmDisplayName(normalizeBlank(pointer.realmDisplayName())) + .setTenantId(Long.toString(pointer.tenantId())) + .setGameInstanceId(Long.toString(pointer.gameInstanceId())) + .setPointerVersion(pointer.pointerVersion()) + .setVisible(pointer.visible()) + .setRequiresCharacterSelection(pointer.requiresCharacterSelection()) + .setStateScope(normalizeBlank(pointer.stateScope())) + .setCharacterCreationPolicy(normalizeBlank(pointer.characterCreationPolicy())) + .setPublicProductionRealm(pointer.publicProductionRealm()) + .setRealmId(pointer.realmId().toString()) + .setPlayableStateNamespaceId(pointer.playableStateNamespaceId().toString()) + .setCatalogRevision(pointer.catalogRevision()); + return builder.build(); } private ScriptPatchPublicationLink scriptPatchPublicationLink( diff --git a/services/game-session-service/src/main/resources/application.yml b/services/game-session-service/src/main/resources/application.yml index c3e79dbb18..3591f95ac9 100644 --- a/services/game-session-service/src/main/resources/application.yml +++ b/services/game-session-service/src/main/resources/application.yml @@ -78,7 +78,7 @@ firemud: tenant-id: ${FIREMUD_BOOTSTRAP_SANDBOX_TENANT_ID:1} game-instance-id: ${FIREMUD_BOOTSTRAP_SANDBOX_GAME_INSTANCE_ID:2} visible: true - public-production-realm: true + public-production-realm: false requires-character-selection: true state-scope: SHARED character-creation-policy: ALLOW_NEW diff --git a/services/game-session-service/src/main/resources/db/migration/V5__separate_gameplay_catalog_revision.sql b/services/game-session-service/src/main/resources/db/migration/V5__separate_gameplay_catalog_revision.sql new file mode 100644 index 0000000000..63e5cd1ce1 --- /dev/null +++ b/services/game-session-service/src/main/resources/db/migration/V5__separate_gameplay_catalog_revision.sql @@ -0,0 +1,4 @@ +ALTER TABLE gameplay_admission_pointer + ADD COLUMN catalog_revision bigint NOT NULL DEFAULT 1, + ADD CONSTRAINT gameplay_admission_pointer_catalog_revision_positive + CHECK (catalog_revision > 0); diff --git a/services/game-session-service/src/main/resources/db/migration/V6__persist_gameplay_realm_identity.sql b/services/game-session-service/src/main/resources/db/migration/V6__persist_gameplay_realm_identity.sql new file mode 100644 index 0000000000..41effca0d0 --- /dev/null +++ b/services/game-session-service/src/main/resources/db/migration/V6__persist_gameplay_realm_identity.sql @@ -0,0 +1,74 @@ +-- A tenant's shared playable-state namespace is allocated once and reused by every +-- SHARED realm. Isolated realms receive independent namespace UUIDs. +CREATE TABLE gameplay_tenant_shared_playable_state_namespace ( + tenant_id bigint PRIMARY KEY, + playable_state_namespace_id uuid NOT NULL UNIQUE, + allocated_at timestamp without time zone NOT NULL DEFAULT CURRENT_TIMESTAMP +); + +INSERT INTO gameplay_tenant_shared_playable_state_namespace ( + tenant_id, + playable_state_namespace_id +) +SELECT shared_tenants.tenant_id, gen_random_uuid() +FROM ( + SELECT DISTINCT pointer.tenant_id + FROM gameplay_admission_pointer pointer + WHERE pointer.state_scope = 'SHARED' +) shared_tenants; + +ALTER TABLE gameplay_admission_pointer + ADD COLUMN realm_id uuid, + ADD COLUMN playable_state_namespace_id uuid; + +-- Retained rows with an exact known state scope can be classified without using +-- the replaceable game_instance_id as identity. Unknown legacy values remain +-- explicitly unresolved below. +UPDATE gameplay_admission_pointer +SET realm_id = gen_random_uuid(), + playable_state_namespace_id = ( + SELECT shared_namespace.playable_state_namespace_id + FROM gameplay_tenant_shared_playable_state_namespace shared_namespace + WHERE shared_namespace.tenant_id = gameplay_admission_pointer.tenant_id + ) +WHERE state_scope = 'SHARED'; + +UPDATE gameplay_admission_pointer +SET realm_id = gen_random_uuid(), + playable_state_namespace_id = gen_random_uuid() +WHERE state_scope = 'ISOLATED'; + +CREATE TABLE gameplay_admission_pointer_identity_backfill_issue ( + pointer_id bigint PRIMARY KEY, + tenant_id bigint NOT NULL, + world_slug character varying(120) NOT NULL, + realm_slug character varying(120) NOT NULL, + prior_state_scope character varying(32), + issue_code character varying(64) NOT NULL, + recorded_at timestamp without time zone NOT NULL DEFAULT CURRENT_TIMESTAMP +); + +INSERT INTO gameplay_admission_pointer_identity_backfill_issue ( + pointer_id, + tenant_id, + world_slug, + realm_slug, + prior_state_scope, + issue_code +) +SELECT id, + tenant_id, + world_slug, + realm_slug, + state_scope, + 'UNKNOWN_PLAYABLE_STATE_SCOPE' +FROM gameplay_admission_pointer +WHERE state_scope IS NULL OR state_scope NOT IN ('SHARED', 'ISOLATED'); + +ALTER TABLE gameplay_admission_pointer + ADD CONSTRAINT gameplay_admission_pointer_identity_pair_complete + CHECK ((realm_id IS NULL) = (playable_state_namespace_id IS NULL)); + +CREATE UNIQUE INDEX uq_gameplay_admission_pointer_realm_id + ON gameplay_admission_pointer (realm_id) + WHERE realm_id IS NOT NULL; diff --git a/services/game-session-service/src/main/resources/db/migration/V7__audit_gameplay_catalog_revision.sql b/services/game-session-service/src/main/resources/db/migration/V7__audit_gameplay_catalog_revision.sql new file mode 100644 index 0000000000..f310583acc --- /dev/null +++ b/services/game-session-service/src/main/resources/db/migration/V7__audit_gameplay_catalog_revision.sql @@ -0,0 +1,8 @@ +ALTER TABLE gameplay_admission_pointer_event + ADD COLUMN catalog_revision bigint, + ADD COLUMN realm_id uuid, + ADD COLUMN playable_state_namespace_id uuid, + ADD CONSTRAINT gameplay_admission_pointer_event_catalog_revision_positive + CHECK (catalog_revision IS NULL OR catalog_revision > 0), + ADD CONSTRAINT gameplay_admission_pointer_event_identity_pair_complete + CHECK ((realm_id IS NULL) = (playable_state_namespace_id IS NULL)); diff --git a/services/game-session-service/src/main/resources/db/migration/V8__initial_admission_bind_owner_ledger.sql b/services/game-session-service/src/main/resources/db/migration/V8__initial_admission_bind_owner_ledger.sql new file mode 100644 index 0000000000..073668a35e --- /dev/null +++ b/services/game-session-service/src/main/resources/db/migration/V8__initial_admission_bind_owner_ledger.sql @@ -0,0 +1,103 @@ +ALTER TABLE gameplay_admission_pointer_event + ALTER COLUMN control_plane_request_id TYPE character varying(128); + +CREATE TABLE gameplay_initial_admission_bind_catalog ( + realm_id uuid PRIMARY KEY, + tenant_id bigint NOT NULL, + game_template_id bigint NOT NULL, + world_slug character varying(120) NOT NULL, + world_display_name character varying(200) NOT NULL, + realm_slug character varying(120) NOT NULL, + realm_display_name character varying(200) NOT NULL, + catalog_revision bigint NOT NULL DEFAULT 1, + playable_state_namespace_id uuid NOT NULL, + visible boolean NOT NULL DEFAULT true, + public_production_realm boolean NOT NULL DEFAULT true, + requires_character_selection boolean NOT NULL, + state_scope character varying(32) NOT NULL DEFAULT 'SHARED', + character_creation_policy character varying(32) NOT NULL DEFAULT 'ALLOW_NEW', + created_at timestamp without time zone NOT NULL DEFAULT CURRENT_TIMESTAMP, + CONSTRAINT gameplay_initial_admission_bind_catalog_tenant_positive + CHECK (tenant_id > 0), + CONSTRAINT gameplay_initial_admission_bind_catalog_template_positive + CHECK (game_template_id > 0), + CONSTRAINT gameplay_initial_admission_bind_catalog_revision_one + CHECK (catalog_revision = 1), + CONSTRAINT gameplay_initial_admission_bind_catalog_public_shared + CHECK (visible AND public_production_realm AND state_scope = 'SHARED' + AND character_creation_policy = 'ALLOW_NEW'), + CONSTRAINT gameplay_initial_admission_bind_catalog_selector_unique + UNIQUE (tenant_id, world_slug, realm_slug), + CONSTRAINT gameplay_initial_admission_bind_catalog_template_unique + UNIQUE (tenant_id, game_template_id), + CONSTRAINT gameplay_initial_admission_bind_catalog_attempt_identity_unique + UNIQUE (tenant_id, realm_id, playable_state_namespace_id, catalog_revision) +); + +CREATE UNIQUE INDEX uq_gameplay_initial_admission_bind_public_realm_per_tenant + ON gameplay_initial_admission_bind_catalog (tenant_id) + WHERE visible AND public_production_realm; + +CREATE TABLE gameplay_initial_admission_bind_attempt ( + attempt_id uuid PRIMARY KEY DEFAULT gen_random_uuid(), + tenant_id bigint NOT NULL, + initial_admission_request_id character varying(128) NOT NULL, + request_digest character varying(64) NOT NULL, + realm_id uuid NOT NULL, + playable_state_namespace_id uuid NOT NULL, + playable_state_scope character varying(32) NOT NULL, + expected_no_prior_pointer boolean NOT NULL DEFAULT true, + catalog_revision bigint NOT NULL, + game_instance_id bigint NOT NULL, + version_id bigint NOT NULL, + active_lifecycle_epoch bigint NOT NULL, + hold_id uuid, + hold_fence uuid, + status character varying(16) NOT NULL DEFAULT 'PENDING', + pointer_id bigint, + audit_event_id bigint, + created_at timestamp without time zone NOT NULL DEFAULT CURRENT_TIMESTAMP, + updated_at timestamp without time zone NOT NULL DEFAULT CURRENT_TIMESTAMP, + terminal_at timestamp without time zone, + CONSTRAINT gameplay_initial_admission_bind_attempt_request_unique + UNIQUE (tenant_id, initial_admission_request_id), + CONSTRAINT gameplay_initial_admission_bind_attempt_catalog_fk + FOREIGN KEY (tenant_id, realm_id, playable_state_namespace_id, catalog_revision) + REFERENCES gameplay_initial_admission_bind_catalog + (tenant_id, realm_id, playable_state_namespace_id, catalog_revision), + CONSTRAINT gameplay_initial_admission_bind_attempt_pointer_fk + FOREIGN KEY (pointer_id) REFERENCES gameplay_admission_pointer (id), + CONSTRAINT gameplay_initial_admission_bind_attempt_audit_fk + FOREIGN KEY (audit_event_id) REFERENCES gameplay_admission_pointer_event (id), + CONSTRAINT gameplay_initial_admission_bind_attempt_digest_sha256 + CHECK (request_digest ~ '^[0-9a-f]{64}$'), + CONSTRAINT gameplay_initial_admission_bind_attempt_positive_tuple + CHECK (tenant_id > 0 AND catalog_revision > 0 AND game_instance_id > 0 + AND version_id > 0 AND active_lifecycle_epoch > 0), + CONSTRAINT gameplay_initial_admission_bind_attempt_shared_scope + CHECK (playable_state_scope = 'SHARED' AND expected_no_prior_pointer), + CONSTRAINT gameplay_initial_admission_bind_attempt_status + CHECK (status IN ('PENDING', 'COMMITTED', 'ABORTED')), + CONSTRAINT gameplay_initial_admission_bind_attempt_hold_pair + CHECK ((hold_id IS NULL) = (hold_fence IS NULL)), + CONSTRAINT gameplay_initial_admission_bind_attempt_result_pair + CHECK ((pointer_id IS NULL) = (audit_event_id IS NULL)), + CONSTRAINT gameplay_initial_admission_bind_attempt_terminal_shape + CHECK ((status = 'PENDING' AND terminal_at IS NULL AND pointer_id IS NULL) + OR (status = 'COMMITTED' AND terminal_at IS NOT NULL AND pointer_id IS NOT NULL + AND hold_id IS NOT NULL) + OR (status = 'ABORTED' AND terminal_at IS NOT NULL AND pointer_id IS NULL)) +); + +CREATE UNIQUE INDEX uq_gameplay_initial_admission_bind_attempt_hold_id + ON gameplay_initial_admission_bind_attempt (hold_id) + WHERE hold_id IS NOT NULL; +CREATE UNIQUE INDEX uq_gameplay_initial_admission_bind_attempt_pointer_id + ON gameplay_initial_admission_bind_attempt (pointer_id) + WHERE pointer_id IS NOT NULL; +CREATE UNIQUE INDEX uq_gameplay_initial_admission_bind_attempt_audit_event_id + ON gameplay_initial_admission_bind_attempt (audit_event_id) + WHERE audit_event_id IS NOT NULL; +CREATE UNIQUE INDEX uq_gameplay_initial_admission_bind_pending_realm + ON gameplay_initial_admission_bind_attempt (tenant_id, realm_id) + WHERE status = 'PENDING'; diff --git a/services/game-session-service/src/test/java/integration/net/firedevops/firemud/gamesession/repository/GameplayAdmissionPointerMigrationIntegrationTest.java b/services/game-session-service/src/test/java/integration/net/firedevops/firemud/gamesession/repository/GameplayAdmissionPointerMigrationIntegrationTest.java new file mode 100644 index 0000000000..eba788f5c6 --- /dev/null +++ b/services/game-session-service/src/test/java/integration/net/firedevops/firemud/gamesession/repository/GameplayAdmissionPointerMigrationIntegrationTest.java @@ -0,0 +1,326 @@ +package net.firedevops.firemud.gamesession.repository; + +import static org.assertj.core.api.Assertions.assertThat; +import static org.assertj.core.api.Assertions.assertThatThrownBy; + +import java.nio.file.Path; +import java.util.ArrayList; +import java.util.Arrays; +import java.util.LinkedHashMap; +import java.util.List; +import java.util.Map; +import java.util.UUID; +import net.firedevops.firemud.gamesession.command.text.GameplayWorldCatalog; +import org.flywaydb.core.Flyway; +import org.flywaydb.core.api.MigrationVersion; +import org.jooq.DSLContext; +import org.jooq.Record; +import org.jooq.SQLDialect; +import org.jooq.exception.DataAccessException; +import org.jooq.impl.DSL; +import org.junit.jupiter.api.Test; +import org.springframework.jdbc.datasource.DriverManagerDataSource; +import org.testcontainers.containers.PostgreSQLContainer; +import org.testcontainers.junit.jupiter.Container; +import org.testcontainers.junit.jupiter.Testcontainers; + +@Testcontainers(disabledWithoutDocker = true) +@SuppressWarnings("resource") +class GameplayAdmissionPointerMigrationIntegrationTest { + private static final String MIGRATION_LOCATION = + "filesystem:" + Path.of("src/main/resources/db/migration").toAbsolutePath().normalize(); + + @Container + static PostgreSQLContainer postgres = new PostgreSQLContainer<>("postgres:16-alpine"); + + @Test + void migrationsV1ThroughV7BackfillPointerIdentityAndKeepHistoricalAuditUnknown() { + DriverManagerDataSource dataSource = dataSource(); + Flyway.configure() + .dataSource(dataSource) + .locations(MIGRATION_LOCATION) + .target(MigrationVersion.fromVersion("5")) + .load() + .migrate(); + DSLContext dsl = DSL.using(dataSource, SQLDialect.POSTGRES); + + insertPointer(dsl, 1L, 10L, "demo", "live", 101L, true, true, "SHARED"); + insertPointer(dsl, 2L, 10L, "demo", "private", 102L, false, true, "SHARED"); + insertPointer(dsl, 3L, 10L, "lab", "playtest", 103L, true, false, "ISOLATED"); + insertPointer(dsl, 4L, 11L, "demo", "live", 104L, true, true, "SHARED"); + insertPointer(dsl, 5L, 12L, "legacy", "unresolved", 105L, false, false, "UNKNOWN"); + + Flyway flyway = + Flyway.configure() + .dataSource(dataSource) + .locations(MIGRATION_LOCATION) + .target(MigrationVersion.fromVersion("6")) + .load(); + flyway.migrate(); + + insertPointerEvent(dsl, 9001L, 1L, 101L); + + assertThat( + Arrays.stream(flyway.info().applied()) + .map(migration -> migration.getVersion().getVersion()) + .toList()) + .contains("1", "2", "3", "4", "5", "6"); + + UUID sharedRealmId = realmId(dsl, 1L); + UUID sharedNamespaceId = namespaceId(dsl, 1L); + assertThat(sharedRealmId).isNotNull(); + assertThat(namespaceId(dsl, 2L)).isEqualTo(sharedNamespaceId); + assertThat(realmId(dsl, 2L)).isNotEqualTo(sharedRealmId); + assertThat(namespaceId(dsl, 3L)).isNotEqualTo(sharedNamespaceId); + assertThat(namespaceId(dsl, 4L)).isNotEqualTo(sharedNamespaceId); + assertThat(realmId(dsl, 5L)).isNull(); + assertThat(namespaceId(dsl, 5L)).isNull(); + assertThat( + dsl.fetchValue( + "SELECT issue_code FROM gameplay_admission_pointer_identity_backfill_issue " + + "WHERE pointer_id = 5", + String.class)) + .isEqualTo("UNKNOWN_PLAYABLE_STATE_SCOPE"); + assertThat( + dsl.fetchValue( + "SELECT catalog_revision FROM gameplay_admission_pointer WHERE id = 1", Long.class)) + .isEqualTo(1L); + + dsl.execute( + "UPDATE gameplay_admission_pointer SET game_instance_id = 111, pointer_version = 5 " + + "WHERE id = 1"); + assertThat(realmId(dsl, 1L)).isEqualTo(sharedRealmId); + assertThat(namespaceId(dsl, 1L)).isEqualTo(sharedNamespaceId); + assertThat( + dsl.fetchValue( + "SELECT catalog_revision FROM gameplay_admission_pointer WHERE id = 1", Long.class)) + .isEqualTo(1L); + + GameplayWorldCatalog catalog = GameplayWorldCatalog.forWorldViews(worldViewsFromDatabase(dsl)); + assertThat(catalog.publicProductionRealmCardinality(10L)) + .isEqualTo(GameplayWorldCatalog.PublicProductionRealmCardinality.EXACTLY_ONE); + assertThat(catalog.publicProductionRealmCardinality(11L)) + .isEqualTo(GameplayWorldCatalog.PublicProductionRealmCardinality.EXACTLY_ONE); + assertThat(catalog.publicProductionRealmCardinality(12L)) + .isEqualTo(GameplayWorldCatalog.PublicProductionRealmCardinality.ZERO); + + assertThatThrownBy( + () -> insertPointer(dsl, 6L, 10L, "demo", "live", 106L, true, false, "SHARED")) + .isInstanceOf(DataAccessException.class) + .hasMessageContaining("uq_gameplay_admission_pointer_tenant_world_realm"); + assertThatThrownBy( + () -> insertPointer(dsl, 6L, 10L, "demo", "alternate", 111L, true, false, "SHARED")) + .isInstanceOf(DataAccessException.class) + .hasMessageContaining("uq_gameplay_admission_pointer_runtime_target"); + assertThatThrownBy( + () -> + dsl.execute( + "UPDATE gameplay_admission_pointer SET realm_id = ? WHERE id = 3", + sharedRealmId)) + .isInstanceOf(DataAccessException.class) + .hasMessageContaining("uq_gameplay_admission_pointer_realm_id"); + assertThatThrownBy( + () -> + dsl.execute( + "UPDATE gameplay_admission_pointer SET playable_state_namespace_id = NULL " + + "WHERE id = 1")) + .isInstanceOf(DataAccessException.class) + .hasMessageContaining("gameplay_admission_pointer_identity_pair_complete"); + assertThatThrownBy( + () -> + dsl.execute( + "UPDATE gameplay_admission_pointer SET catalog_revision = 0 WHERE id = 1")) + .isInstanceOf(DataAccessException.class) + .hasMessageContaining("gameplay_admission_pointer_catalog_revision_positive"); + + Flyway auditFlyway = + Flyway.configure() + .dataSource(dataSource) + .locations(MIGRATION_LOCATION) + .target(MigrationVersion.fromVersion("7")) + .load(); + auditFlyway.migrate(); + + assertThat( + Arrays.stream(auditFlyway.info().applied()) + .map(migration -> migration.getVersion().getVersion()) + .toList()) + .contains("7"); + assertThat( + dsl.fetchValue( + "SELECT catalog_revision FROM gameplay_admission_pointer_event WHERE id = 9001", + Long.class)) + .isNull(); + assertThat( + dsl.fetchValue( + "SELECT realm_id FROM gameplay_admission_pointer_event WHERE id = 9001", + UUID.class)) + .isNull(); + assertThat( + dsl.fetchValue( + "SELECT playable_state_namespace_id FROM gameplay_admission_pointer_event " + + "WHERE id = 9001", + UUID.class)) + .isNull(); + + UUID eventRealmId = realmId(dsl, 1L); + UUID eventNamespaceId = namespaceId(dsl, 1L); + insertBoundPointerEvent(dsl, 9002L, 1L, 101L, 1L, eventRealmId, eventNamespaceId); + Record boundEvent = + dsl.fetchOne("SELECT * FROM gameplay_admission_pointer_event WHERE id = 9002"); + assertThat(boundEvent.get("catalog_revision", Long.class)).isEqualTo(1L); + assertThat(boundEvent.get("realm_id", UUID.class)).isEqualTo(eventRealmId); + assertThat(boundEvent.get("playable_state_namespace_id", UUID.class)) + .isEqualTo(eventNamespaceId); + assertThatThrownBy( + () -> + dsl.execute( + "UPDATE gameplay_admission_pointer_event SET catalog_revision = 0 " + + "WHERE id = 9002")) + .isInstanceOf(DataAccessException.class) + .hasMessageContaining("gameplay_admission_pointer_event_catalog_revision_positive"); + assertThatThrownBy( + () -> + dsl.execute( + "UPDATE gameplay_admission_pointer_event SET playable_state_namespace_id = NULL " + + "WHERE id = 9002")) + .isInstanceOf(DataAccessException.class) + .hasMessageContaining("gameplay_admission_pointer_event_identity_pair_complete"); + } + + private static void insertPointerEvent( + DSLContext dsl, long eventId, long tenantId, long gameInstanceId) { + dsl.execute( + "INSERT INTO gameplay_admission_pointer_event (" + + "id, world_slug, realm_slug, world_display_name, realm_display_name, tenant_id, " + + "game_instance_id, pointer_version, visible, requires_character_selection, " + + "state_scope, character_creation_policy, actor_principal, reason, " + + "control_plane_request_id, occurred_at, public_production_realm) " + + "VALUES (?, 'demo', 'live', 'Demo World', 'Live Realm', ?, ?, 1, true, false, " + + "'SHARED', 'ALLOW_NEW', 'migration-test', 'retained history', 'event-9001', " + + "CURRENT_TIMESTAMP, true)", + eventId, + tenantId, + gameInstanceId); + } + + private static void insertBoundPointerEvent( + DSLContext dsl, + long eventId, + long tenantId, + long gameInstanceId, + long catalogRevision, + UUID realmId, + UUID namespaceId) { + dsl.execute( + "INSERT INTO gameplay_admission_pointer_event (" + + "id, world_slug, realm_slug, world_display_name, realm_display_name, tenant_id, " + + "game_instance_id, pointer_version, catalog_revision, realm_id, " + + "playable_state_namespace_id, visible, requires_character_selection, state_scope, " + + "character_creation_policy, actor_principal, reason, control_plane_request_id, " + + "occurred_at, public_production_realm) " + + "VALUES (?, 'demo', 'live', 'Demo World', 'Live Realm', ?, ?, 1, ?, ?, ?, true, " + + "false, 'SHARED', 'ALLOW_NEW', 'migration-test', 'bound event', 'event-9002', " + + "CURRENT_TIMESTAMP, true)", + eventId, + tenantId, + gameInstanceId, + catalogRevision, + realmId, + namespaceId); + } + + private static void insertPointer( + DSLContext dsl, + long id, + long tenantId, + String worldSlug, + String realmSlug, + long gameInstanceId, + boolean visible, + boolean publicProduction, + String stateScope) { + dsl.execute( + "INSERT INTO gameplay_admission_pointer (" + + "id, world_slug, world_display_name, realm_slug, realm_display_name, tenant_id, " + + "game_instance_id, pointer_version, visible, requires_character_selection, " + + "state_scope, character_creation_policy, last_updated_by, last_update_reason, " + + "public_production_realm) VALUES (?, ?, ?, ?, ?, ?, ?, 1, ?, false, ?, " + + "'ALLOW_NEW', 'migration-test', 'migration fixture', ?)", + id, + worldSlug, + worldSlug + " World", + realmSlug, + realmSlug + " Realm", + tenantId, + gameInstanceId, + visible, + stateScope, + publicProduction); + } + + private static UUID realmId(DSLContext dsl, long pointerId) { + return pointerRecord(dsl, pointerId).get("realm_id", UUID.class); + } + + private static UUID namespaceId(DSLContext dsl, long pointerId) { + return pointerRecord(dsl, pointerId).get("playable_state_namespace_id", UUID.class); + } + + private static Record pointerRecord(DSLContext dsl, long pointerId) { + Record pointer = + dsl.fetchOne("SELECT * FROM gameplay_admission_pointer WHERE id = ?", pointerId); + if (pointer == null) { + throw new IllegalStateException( + "Expected gameplay admission pointer row to exist: id=" + pointerId); + } + return pointer; + } + + private static List worldViewsFromDatabase(DSLContext dsl) { + Map displayNamesByWorld = new LinkedHashMap<>(); + Map> realmsByWorld = new LinkedHashMap<>(); + for (Record row : + dsl.fetch( + "SELECT world_slug, world_display_name, realm_slug, realm_display_name, tenant_id, " + + "game_instance_id, pointer_version, visible, public_production_realm, " + + "requires_character_selection, state_scope, character_creation_policy, " + + "catalog_revision, realm_id, playable_state_namespace_id " + + "FROM gameplay_admission_pointer ORDER BY id")) { + String worldSlug = row.get("world_slug", String.class); + displayNamesByWorld.putIfAbsent(worldSlug, row.get("world_display_name", String.class)); + realmsByWorld + .computeIfAbsent(worldSlug, ignored -> new ArrayList<>()) + .add( + new GameplayWorldCatalog.RealmView( + row.get("realm_slug", String.class), + row.get("realm_display_name", String.class), + row.get("tenant_id", Long.class), + row.get("game_instance_id", Long.class), + row.get("pointer_version", Long.class), + row.get("visible", Boolean.class), + row.get("public_production_realm", Boolean.class), + row.get("requires_character_selection", Boolean.class), + row.get("state_scope", String.class), + row.get("character_creation_policy", String.class), + row.get("catalog_revision", Long.class), + row.get("realm_id", UUID.class), + row.get("playable_state_namespace_id", UUID.class))); + } + return realmsByWorld.entrySet().stream() + .map( + entry -> + new GameplayWorldCatalog.WorldView( + entry.getKey(), displayNamesByWorld.get(entry.getKey()), entry.getValue())) + .toList(); + } + + private static DriverManagerDataSource dataSource() { + DriverManagerDataSource dataSource = new DriverManagerDataSource(); + dataSource.setDriverClassName(postgres.getDriverClassName()); + dataSource.setUrl(postgres.getJdbcUrl()); + dataSource.setUsername(postgres.getUsername()); + dataSource.setPassword(postgres.getPassword()); + return dataSource; + } +} diff --git a/services/game-session-service/src/test/java/integration/net/firedevops/firemud/gamesession/service/InitialAdmissionBindPostgresIntegrationTest.java b/services/game-session-service/src/test/java/integration/net/firedevops/firemud/gamesession/service/InitialAdmissionBindPostgresIntegrationTest.java new file mode 100644 index 0000000000..4b7c3fe997 --- /dev/null +++ b/services/game-session-service/src/test/java/integration/net/firedevops/firemud/gamesession/service/InitialAdmissionBindPostgresIntegrationTest.java @@ -0,0 +1,170 @@ +package net.firedevops.firemud.gamesession.service; + +import static org.assertj.core.api.Assertions.assertThat; +import static org.assertj.core.api.Assertions.assertThatThrownBy; + +import java.nio.file.Path; +import net.firedevops.firemud.gamesession.entity.GameInstance; +import net.firedevops.firemud.gamesession.repository.GameInstanceRepository; +import net.firedevops.firemud.gamesession.repository.GameplayAdmissionPointerEventRepository; +import net.firedevops.firemud.gamesession.repository.InitialAdmissionBindAttemptRepository; +import net.firedevops.firemud.gamesession.repository.InitialAdmissionBindCatalogRepository; +import net.firedevops.firemud.gamesession.service.impl.DatabaseInitialAdmissionBindOwnerService; +import org.flywaydb.core.Flyway; +import org.jooq.DSLContext; +import org.jooq.SQLDialect; +import org.jooq.impl.DSL; +import org.junit.jupiter.api.Test; +import org.springframework.jdbc.datasource.DataSourceTransactionManager; +import org.springframework.jdbc.datasource.DriverManagerDataSource; +import org.springframework.jdbc.datasource.TransactionAwareDataSourceProxy; +import org.springframework.transaction.support.TransactionTemplate; +import org.testcontainers.containers.PostgreSQLContainer; +import org.testcontainers.junit.jupiter.Container; +import org.testcontainers.junit.jupiter.Testcontainers; + +@Testcontainers(disabledWithoutDocker = true) +@SuppressWarnings("resource") +class InitialAdmissionBindPostgresIntegrationTest { + private static final String MIGRATION_LOCATION = + "filesystem:" + Path.of("src/main/resources/db/migration").toAbsolutePath().normalize(); + + @Container + static PostgreSQLContainer postgres = new PostgreSQLContainer<>("postgres:16-alpine"); + + @Test + void v8LedgerCommitsPointerAuditAndAttemptTogetherAndReadbackFailsClosed() { + DriverManagerDataSource dataSource = dataSource(); + Flyway.configure().dataSource(dataSource).locations(MIGRATION_LOCATION).load().migrate(); + DSLContext dsl = + DSL.using(new TransactionAwareDataSourceProxy(dataSource), SQLDialect.POSTGRES); + TransactionTemplate transactionTemplate = + new TransactionTemplate(new DataSourceTransactionManager(dataSource)); + GameInstanceRepository gameInstanceRepository = new GameInstanceRepository(dsl); + GameInstance gameInstance = gameInstanceRepository.save(gameInstance()); + DatabaseInitialAdmissionBindOwnerService service = + new DatabaseInitialAdmissionBindOwnerService( + new InitialAdmissionBindCatalogRepository(dsl), + new InitialAdmissionBindAttemptRepository(dsl), + new GameplayAdmissionPointerEventRepository(dsl), + gameInstanceRepository); + + InitialAdmissionBindCatalogSnapshot catalog = + transactionTemplate.execute( + status -> + toSnapshot( + service.registerPublicSharedFixtureCatalog( + new InitialAdmissionBindCatalogDescriptor( + 41L, 810L, "smoke", "Smoke World", "production", "Live Realm", true)))); + var request = + new InitialAdmissionBindRequest( + 41L, + "smoke", + "production", + "pg-initial-bind-" + gameInstance.getId(), + "c".repeat(64), + gameInstance.getId(), + 902L, + 13L); + var attempt = transactionTemplate.execute(status -> service.beginIntent(request)); + var binding = + new InitialAdmissionBindHoldBinding( + "291787b2-ed31-4ae0-9d72-1f872931e7ed", + "ea29d3c4-bb4c-4ce5-8f81-8fd60d21b472", + 41L, + catalog.realmId(), + catalog.namespaceId(), + "SHARED", + gameInstance.getId(), + 902L, + 13L, + request.initialAdmissionRequestId(), + request.requestDigest(), + true, + 1L); + transactionTemplate.execute(status -> service.attachHold(binding)); + + dsl.execute( + "CREATE FUNCTION reject_initial_admission_audit() RETURNS trigger LANGUAGE plpgsql AS $$ " + + "BEGIN IF NEW.reason = 'initial admission pointer bind' THEN " + + "RAISE EXCEPTION 'forced initial admission audit failure'; END IF; RETURN NEW; END; $$"); + dsl.execute( + "CREATE TRIGGER reject_initial_admission_audit BEFORE INSERT ON " + + "gameplay_admission_pointer_event FOR EACH ROW EXECUTE FUNCTION " + + "reject_initial_admission_audit()"); + assertThatThrownBy(() -> transactionTemplate.execute(status -> service.commit(binding))) + .isInstanceOf(RuntimeException.class); + assertThat(dsl.fetchCount(DSL.table("gameplay_admission_pointer"))).isZero(); + assertThat(dsl.fetchCount(DSL.table("gameplay_admission_pointer_event"))).isZero(); + assertThat( + dsl.fetchValue( + "SELECT status FROM gameplay_initial_admission_bind_attempt WHERE attempt_id = ?", + String.class, + attempt.attemptId())) + .isEqualTo("PENDING"); + dsl.execute("DROP TRIGGER reject_initial_admission_audit ON gameplay_admission_pointer_event"); + dsl.execute("DROP FUNCTION reject_initial_admission_audit()"); + + var committed = transactionTemplate.execute(status -> service.commit(binding)); + assertThat(committed.outcome()).isEqualTo(InitialAdmissionBindOwnerProof.Outcome.COMMITTED); + assertThat(committed.ownerProofId()).isEqualTo(attempt.attemptId().toString()); + assertThat(committed.pointerAuditRequestDigest()).isEqualTo(request.requestDigest()); + assertThat(committed.pointerVersion()).isEqualTo(1L); + assertThat( + dsl.fetchOne( + "SELECT pointer.catalog_revision AS pointer_revision, " + + "event.catalog_revision AS event_revision, pointer.realm_id, " + + "event.realm_id AS event_realm_id, pointer.playable_state_namespace_id, " + + "event.playable_state_namespace_id AS event_namespace_id " + + "FROM gameplay_initial_admission_bind_attempt attempt " + + "JOIN gameplay_admission_pointer pointer ON pointer.id = attempt.pointer_id " + + "JOIN gameplay_admission_pointer_event event ON event.id = attempt.audit_event_id " + + "WHERE attempt.attempt_id = ?", + attempt.attemptId()) + .get("pointer_revision", Long.class)) + .isEqualTo(1L); + var evidence = + dsl.fetchOne( + "SELECT event.catalog_revision AS event_revision, event.realm_id AS event_realm_id, " + + "event.playable_state_namespace_id AS event_namespace_id " + + "FROM gameplay_initial_admission_bind_attempt attempt " + + "JOIN gameplay_admission_pointer_event event ON event.id = attempt.audit_event_id " + + "WHERE attempt.attempt_id = ?", + attempt.attemptId()); + assertThat(evidence.get("event_revision", Long.class)).isEqualTo(1L); + assertThat(evidence.get("event_realm_id", java.util.UUID.class).toString()) + .isEqualTo(catalog.realmId()); + assertThat(evidence.get("event_namespace_id", java.util.UUID.class).toString()) + .isEqualTo(catalog.namespaceId()); + assertThat(dsl.fetchCount(DSL.table("gameplay_admission_pointer"))).isEqualTo(1); + assertThat(dsl.fetchCount(DSL.table("gameplay_admission_pointer_event"))).isEqualTo(1); + } + + private static DriverManagerDataSource dataSource() { + DriverManagerDataSource dataSource = new DriverManagerDataSource(); + dataSource.setDriverClassName("org.postgresql.Driver"); + dataSource.setUrl(postgres.getJdbcUrl()); + dataSource.setUsername(postgres.getUsername()); + dataSource.setPassword(postgres.getPassword()); + return dataSource; + } + + private static GameInstance gameInstance() { + GameInstance gameInstance = new GameInstance(); + gameInstance.setTenantId(41L); + gameInstance.setRuntimeVersion("smoke-1"); + gameInstance.setOwnerAccountId(1001L); + gameInstance.setStatus("RUNNING"); + gameInstance.setGameTemplateId(810L); + gameInstance.setVersionId(902L); + return gameInstance; + } + + private static InitialAdmissionBindCatalogSnapshot toSnapshot( + net.firedevops.firemud.gamesession.entity.InitialAdmissionBindCatalog catalog) { + return new InitialAdmissionBindCatalogSnapshot( + catalog.realmId().toString(), catalog.playableStateNamespaceId().toString()); + } + + private record InitialAdmissionBindCatalogSnapshot(String realmId, String namespaceId) {} +} diff --git a/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/command/text/GameplayWorldCatalogTest.java b/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/command/text/GameplayWorldCatalogTest.java index f14c14301c..b72acabbe4 100644 --- a/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/command/text/GameplayWorldCatalogTest.java +++ b/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/command/text/GameplayWorldCatalogTest.java @@ -1,12 +1,20 @@ package net.firedevops.firemud.gamesession.command.text; import static org.assertj.core.api.Assertions.assertThat; +import static org.assertj.core.api.Assertions.assertThatThrownBy; import static org.mockito.Mockito.when; +import java.nio.charset.StandardCharsets; import java.util.List; +import java.util.UUID; +import java.util.concurrent.atomic.AtomicInteger; +import java.util.stream.Stream; import net.firedevops.firemud.gamesession.service.GameplayAdmissionPointerAuthorityService; import net.firedevops.firemud.gamesession.service.GameplayAdmissionPointerSnapshot; import org.junit.jupiter.api.Test; +import org.junit.jupiter.params.ParameterizedTest; +import org.junit.jupiter.params.provider.Arguments; +import org.junit.jupiter.params.provider.MethodSource; import org.mockito.Mockito; class GameplayWorldCatalogTest { @@ -76,6 +84,59 @@ void visibleWorldsDropIncompleteAuthorityPointers() { assertThat(catalog.resolveRuntimeTarget(1L, 11L)).isEmpty(); } + @Test + void authoritySnapshotRejectsPublicRealmsAcrossDifferentWorldsForOneTenant() { + when(authorityService.listPointers()) + .thenReturn( + List.of( + publicPointer("alpha", "Alpha World", 1L, 11L), + publicPointer("beta", "Beta World", 1L, 12L))); + GameplayWorldCatalog catalog = new GameplayWorldCatalog(authorityService); + + assertThatThrownBy(catalog::visibleWorldsFromAuthoritySnapshot) + .isInstanceOf(GameplayWorldCatalog.AuthorityPointerUnavailableException.class) + .hasMessageContaining("public-production realm count is invalid"); + } + + @Test + void authoritySnapshotRejectsTenantWithoutVisiblePublicRealm() { + when(authorityService.listPointers()) + .thenReturn( + List.of(pointer("demo", "Demo World", "private", "Private Realm", 1L, 11L, 7L))); + GameplayWorldCatalog catalog = new GameplayWorldCatalog(authorityService); + + assertThatThrownBy(catalog::visibleWorldsFromAuthoritySnapshot) + .isInstanceOf(GameplayWorldCatalog.AuthorityPointerUnavailableException.class) + .hasMessageContaining("public-production realm count is invalid"); + } + + @Test + void authoritySnapshotKeepsPrivateRealmsWhenTenantHasOneVisiblePublicRealm() { + when(authorityService.listPointers()) + .thenReturn( + List.of( + publicPointer("demo", "Demo World", 1L, 11L), + pointer("private", "Private World", "preview", "Preview", 1L, 12L, 1L), + publicPointer("hidden", "Hidden", 1L, 13L, false))); + GameplayWorldCatalog catalog = new GameplayWorldCatalog(authorityService); + + assertThat(catalog.visibleWorldsFromAuthoritySnapshot()) + .extracting(GameplayWorldCatalog.WorldView::slug) + .containsExactly("demo", "private"); + } + + @ParameterizedTest(name = "authority projection rejects {0}") + @MethodSource("incompleteAuthorityPointers") + void visibleWorldsDropPointersWithoutCompleteCatalogIdentity( + String reason, GameplayAdmissionPointerSnapshot pointer) { + when(authorityService.listPointers()).thenReturn(List.of(pointer)); + GameplayWorldCatalog catalog = new GameplayWorldCatalog(authorityService); + + assertThat(catalog.visibleWorlds()).isEmpty(); + assertThat(catalog.resolveWorld("demo")).isEmpty(); + assertThat(catalog.resolveRuntimeTarget(1L, 11L)).isEmpty(); + } + @Test void visibleWorldsDropPointersMissingCharacterCreationPolicy() { when(authorityService.listPointers()) @@ -167,6 +228,139 @@ void normalizeWorldsDropsRealmViewsWithoutSlugsBeforeAdmissionLookup() { assertThat(catalog.resolveRealmForAdmission(normalizedWorld, "invalid")).isEmpty(); } + @Test + void authoritativePointerIdentityAndCatalogRevisionReachRealmView() { + java.util.UUID realmId = java.util.UUID.fromString("8a1df0f1-1b57-465e-9c4b-bb34f8153d31"); + java.util.UUID playableStateNamespaceId = + java.util.UUID.fromString("2ea958e0-13a2-41d0-9c39-59a96cf31412"); + when(authorityService.listPointers()) + .thenReturn( + List.of( + new GameplayAdmissionPointerSnapshot( + "demo", + "Demo World", + "production", + "Live Realm", + 7L, + 11L, + 3L, + true, + true, + false, + "SHARED", + "ALLOW_NEW", + 29L, + realmId, + playableStateNamespaceId))); + GameplayWorldCatalog catalog = new GameplayWorldCatalog(authorityService); + + GameplayWorldCatalog.RealmView realm = + catalog + .resolveRealm(catalog.resolveWorld("demo").orElseThrow(), "production") + .orElseThrow(); + + assertThat(realm.catalogRevision()).isEqualTo(29L); + assertThat(realm.realmId()).isEqualTo(realmId); + assertThat(realm.playableStateNamespaceId()).isEqualTo(playableStateNamespaceId); + } + + @Test + void publicProductionCardinalityCountsExactlyOneAcrossTheTenantCatalogue() { + GameplayWorldCatalog catalog = + GameplayWorldCatalog.forWorldViews( + List.of( + worldWithRealm("demo", "production", 7L, true), + worldWithRealm("preview", "preview", 7L, false))); + + assertThat(catalog.publicProductionRealmCardinality(7L)) + .isEqualTo(GameplayWorldCatalog.PublicProductionRealmCardinality.EXACTLY_ONE); + assertThat(catalog.resolveDefaultRealm(catalog.resolveWorld("demo").orElseThrow())).isPresent(); + } + + @Test + void publicProductionCardinalityFailsClosedWhenTenantHasNoPublicRealm() { + GameplayWorldCatalog catalog = + GameplayWorldCatalog.forWorldViews( + List.of(worldWithRealm("preview", "preview", 7L, false))); + + assertThat(catalog.publicProductionRealmCardinality(7L)) + .isEqualTo(GameplayWorldCatalog.PublicProductionRealmCardinality.ZERO); + assertThat(catalog.resolveDefaultRealm(catalog.resolveWorld("preview").orElseThrow())) + .isEmpty(); + } + + @Test + void publicProductionCardinalityCountsSameTenantCandidatesAcrossWorlds() { + GameplayWorldCatalog catalog = + GameplayWorldCatalog.forWorldViews( + List.of( + worldWithRealm("demo", "production", 7L, true), + worldWithRealm("alternate", "production", 7L, true))); + + assertThat(catalog.publicProductionRealmCardinality(7L)) + .isEqualTo(GameplayWorldCatalog.PublicProductionRealmCardinality.MULTIPLE); + assertThat(catalog.resolveDefaultRealm(catalog.resolveWorld("demo").orElseThrow())).isEmpty(); + } + + @Test + void browseViewUsesOneWorldSnapshotForDefaultRealmAndCardinalityChecks() { + AtomicInteger supplierCalls = new AtomicInteger(); + GameplayWorldCatalog catalog = + GameplayWorldCatalog.forWorldSupplier( + () -> + supplierCalls.getAndIncrement() == 0 + ? List.of(worldWithRealm("demo", "production", 7L, true)) + : List.of(worldWithRealm("demo", "preview", 7L, false))); + + assertThat(catalog.browseView().worlds()) + .extracting( + net.firedevops.firemud.gamesession.presentation.WorldsViewOutput.WorldEntry::slug) + .containsExactly("demo"); + assertThat(supplierCalls).hasValue(1); + } + + @Test + void closedVisiblePublicRealmStillCountsAsTheTenantPublicRealm() { + GameplayWorldCatalog catalog = + GameplayWorldCatalog.forWorldViews( + List.of( + new GameplayWorldCatalog.WorldView( + "demo", + "Demo World", + List.of( + new GameplayWorldCatalog.RealmView( + "production", + "Live Realm", + 7L, + 0L, + 0L, + true, + true, + false, + "SHARED", + "ALLOW_NEW"))))); + + assertThat(catalog.publicProductionRealmCardinality(7L)) + .isEqualTo(GameplayWorldCatalog.PublicProductionRealmCardinality.EXACTLY_ONE); + assertThat(catalog.resolveDefaultRealm(catalog.resolveWorld("demo").orElseThrow())).isPresent(); + } + + @Test + void numericWorldSelectionUsesTheSameFilteredSetAsWorldBrowsePresentation() { + GameplayWorldCatalog catalog = + GameplayWorldCatalog.forWorldViews( + List.of( + worldWithRealm("invalid", "preview", 7L, false), + worldWithRealm("demo", "production", 8L, true))); + + assertThat(catalog.browseView().worlds()) + .extracting( + net.firedevops.firemud.gamesession.presentation.WorldsViewOutput.WorldEntry::slug) + .containsExactly("demo"); + assertThat(catalog.resolveWorld("1").orElseThrow().slug()).isEqualTo("demo"); + assertThat(catalog.resolveWorld("invalid")).isPresent(); + } + private static GameplayWorldCatalog.WorldView worldWithTargetRealm( String realmSlug, boolean visible) { return new GameplayWorldCatalog.WorldView( @@ -188,6 +382,25 @@ private static GameplayWorldCatalog.WorldView worldWithTargetRealm( "ALLOW_NEW"))); } + private static GameplayWorldCatalog.WorldView worldWithRealm( + String worldSlug, String realmSlug, long tenantId, boolean publicProduction) { + return new GameplayWorldCatalog.WorldView( + worldSlug, + worldSlug, + List.of( + new GameplayWorldCatalog.RealmView( + realmSlug, + realmSlug, + tenantId, + 11L, + 1L, + true, + publicProduction, + false, + "SHARED", + "ALLOW_NEW"))); + } + private static GameplayAdmissionPointerSnapshot pointer( String worldSlug, String worldDisplayName, @@ -216,6 +429,7 @@ private static GameplayAdmissionPointerSnapshot pointer( long gameInstanceId, long pointerVersion, boolean visible) { + UUID realmId = stableId("realm/" + tenantId + "/" + worldSlug + "/" + realmSlug); return new GameplayAdmissionPointerSnapshot( worldSlug, worldDisplayName, @@ -228,6 +442,136 @@ private static GameplayAdmissionPointerSnapshot pointer( "production".equals(realmSlug), false, "SHARED", - "ALLOW_NEW"); + "ALLOW_NEW", + 1L, + realmId, + stableId("namespace/" + realmId)); + } + + private static GameplayAdmissionPointerSnapshot publicPointer( + String worldSlug, String worldDisplayName, long tenantId, long gameInstanceId) { + return publicPointer(worldSlug, worldDisplayName, tenantId, gameInstanceId, true); + } + + private static GameplayAdmissionPointerSnapshot publicPointer( + String worldSlug, + String worldDisplayName, + long tenantId, + long gameInstanceId, + boolean visible) { + UUID realmId = stableId("realm/" + tenantId + "/" + worldSlug + "/public"); + return new GameplayAdmissionPointerSnapshot( + worldSlug, + worldDisplayName, + "live", + "Live Realm", + tenantId, + gameInstanceId, + 1L, + visible, + true, + false, + "SHARED", + "ALLOW_NEW", + 1L, + realmId, + stableId("namespace/" + realmId)); + } + + private static Stream incompleteAuthorityPointers() { + GameplayAdmissionPointerSnapshot complete = + new GameplayAdmissionPointerSnapshot( + "demo", + "Demo World", + "production", + "Live Realm", + 1L, + 11L, + 7L, + true, + true, + false, + "SHARED", + "ALLOW_NEW", + 1L, + stableId("realm/demo/production"), + stableId("namespace/demo/production")); + return Stream.of( + Arguments.of( + "non-positive catalog revision", + copyAuthorityPointer( + complete, + 0L, + complete.realmId(), + complete.playableStateNamespaceId(), + complete.stateScope())), + Arguments.of( + "negative catalog revision", + copyAuthorityPointer( + complete, + -1L, + complete.realmId(), + complete.playableStateNamespaceId(), + complete.stateScope())), + Arguments.of( + "missing realm identity", + copyAuthorityPointer( + complete, + complete.catalogRevision(), + null, + complete.playableStateNamespaceId(), + complete.stateScope())), + Arguments.of( + "missing playable-state namespace", + copyAuthorityPointer( + complete, + complete.catalogRevision(), + complete.realmId(), + null, + complete.stateScope())), + Arguments.of( + "unknown playable-state scope", + copyAuthorityPointer( + complete, + complete.catalogRevision(), + complete.realmId(), + complete.playableStateNamespaceId(), + "UNKNOWN")), + Arguments.of( + "non-canonical playable-state scope", + copyAuthorityPointer( + complete, + complete.catalogRevision(), + complete.realmId(), + complete.playableStateNamespaceId(), + "shared"))); + } + + private static GameplayAdmissionPointerSnapshot copyAuthorityPointer( + GameplayAdmissionPointerSnapshot pointer, + long catalogRevision, + UUID realmId, + UUID playableStateNamespaceId, + String stateScope) { + return new GameplayAdmissionPointerSnapshot( + pointer.worldSlug(), + pointer.worldDisplayName(), + pointer.realmSlug(), + pointer.realmDisplayName(), + pointer.tenantId(), + pointer.gameInstanceId(), + pointer.pointerVersion(), + pointer.visible(), + pointer.publicProductionRealm(), + pointer.requiresCharacterSelection(), + stateScope, + pointer.characterCreationPolicy(), + catalogRevision, + realmId, + playableStateNamespaceId); + } + + private static UUID stableId(String value) { + return UUID.nameUUIDFromBytes(value.getBytes(StandardCharsets.UTF_8)); } } diff --git a/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/data/GameplayAdmissionPointerBootstrapInitializerTest.java b/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/data/GameplayAdmissionPointerBootstrapInitializerTest.java index 732b5c72a5..e64deb86b0 100644 --- a/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/data/GameplayAdmissionPointerBootstrapInitializerTest.java +++ b/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/data/GameplayAdmissionPointerBootstrapInitializerTest.java @@ -1,28 +1,28 @@ package net.firedevops.firemud.gamesession.data; import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertFalse; +import static org.junit.jupiter.api.Assertions.assertThrows; import static org.junit.jupiter.api.Assertions.assertTrue; -import static org.mockito.Mockito.never; import static org.mockito.Mockito.verify; +import static org.mockito.Mockito.verifyNoMoreInteractions; import static org.mockito.Mockito.when; +import java.util.Arrays; import java.util.List; import net.firedevops.firemud.gamesession.config.GameplayAdmissionPointerBootstrapProperties; import net.firedevops.firemud.gamesession.repository.GameplayAdmissionPointerRepository; -import net.firedevops.firemud.gamesession.service.GameplayAdmissionPointerAuthorityService; -import net.firedevops.firemud.gamesession.service.GameplayAdmissionPointerMutation; import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.Test; import org.junit.jupiter.api.extension.ExtendWith; -import org.mockito.ArgumentCaptor; import org.mockito.Mock; import org.mockito.junit.jupiter.MockitoExtension; import org.springframework.boot.DefaultApplicationArguments; +import org.springframework.stereotype.Component; @ExtendWith(MockitoExtension.class) class GameplayAdmissionPointerBootstrapInitializerTest { @Mock private GameplayAdmissionPointerRepository pointerRepository; - @Mock private GameplayAdmissionPointerAuthorityService authorityService; private GameplayAdmissionPointerBootstrapProperties properties; private GameplayAdmissionPointerBootstrapInitializer initializer; @@ -30,85 +30,178 @@ class GameplayAdmissionPointerBootstrapInitializerTest { @BeforeEach void setUp() { properties = new GameplayAdmissionPointerBootstrapProperties(); - initializer = - new GameplayAdmissionPointerBootstrapInitializer( - pointerRepository, authorityService, properties); + initializer = new GameplayAdmissionPointerBootstrapInitializer(pointerRepository, properties); } @Test - void runSeedsBootstrapPointersWhenAuthorityStoreIsEmpty() throws Exception { + void runKeepsAdmissionClosedWithoutPointerWritesOrBootstrapLockWhenStoreIsEmpty() + throws Exception { when(pointerRepository.count()).thenReturn(0L); - properties.setPointers( - List.of( - pointerSeed("demo", "Demo World", "production", "Live Realm", 1L, 1L, false), - pointerSeed("sandbox", "Builder Sandbox", "production", "Live Realm", 1L, 2L, true))); initializer.run(new DefaultApplicationArguments(new String[] {})); - ArgumentCaptor mutationCaptor = - ArgumentCaptor.forClass(GameplayAdmissionPointerMutation.class); - verify(authorityService, org.mockito.Mockito.times(2)).upsertPointer(mutationCaptor.capture()); - List mutations = mutationCaptor.getAllValues(); - assertEquals(2, mutations.size()); - assertEquals("demo", mutations.get(0).worldSlug()); - assertEquals("Demo World", mutations.get(0).worldDisplayName()); - assertEquals("production", mutations.get(0).realmSlug()); - assertEquals("Live Realm", mutations.get(0).realmDisplayName()); - assertEquals(1L, mutations.get(0).tenantId()); - assertEquals(1L, mutations.get(0).gameInstanceId()); - assertEquals("SHARED", mutations.get(0).stateScope()); - assertEquals("ALLOW_NEW", mutations.get(0).characterCreationPolicy()); - assertEquals("system/bootstrap", mutations.get(0).actorPrincipal()); - assertEquals("Initial gameplay pointer bootstrap", mutations.get(0).reason()); - assertEquals("bootstrap:1:1:demo:production", mutations.get(0).controlPlaneRequestId()); - assertEquals("sandbox", mutations.get(1).worldSlug()); - assertTrue(mutations.get(1).requiresCharacterSelection()); - } - - @Test - void runDoesNothingWhenAuthorityStoreAlreadyHasPointers() throws Exception { + verify(pointerRepository).count(); + verifyNoMoreInteractions(pointerRepository); + } + + @Test + void defaultEffectiveBootstrapSeedsHaveOneVisiblePublicProductionRealmPerTenant() { + List pointers = + properties.getPointers(); + + assertEquals(2, pointers.size()); + assertEquals("demo", pointers.get(0).getWorldSlug()); + assertTrue(pointers.get(0).isVisible()); + assertTrue(pointers.get(0).isPublicProductionRealm()); + assertEquals("sandbox", pointers.get(1).getWorldSlug()); + assertTrue(pointers.get(1).isVisible()); + assertFalse(pointers.get(1).isPublicProductionRealm()); + } + + @Test + void runPreservesExistingPointerAuthorityOnRestart() throws Exception { when(pointerRepository.count()).thenReturn(3L); initializer.run(new DefaultApplicationArguments(new String[] {})); - verify(authorityService, never()).upsertPointer(org.mockito.ArgumentMatchers.any()); + verify(pointerRepository).count(); + verifyNoMoreInteractions(pointerRepository); } @Test - void runSkipsBlankBootstrapPointerSeeds() throws Exception { - when(pointerRepository.count()).thenReturn(0L); - properties.setPointers( - new java.util.ArrayList<>( - java.util.Arrays.asList( - pointerSeed("demo", "Demo World", "production", "Live Realm", 1L, 1L, false), - pointerSeed("", "Broken World", "production", "Live Realm", 1L, 2L, false), - pointerSeed("sandbox", "Builder Sandbox", "", "Live Realm", 1L, 3L, true), - null))); + void runRejectsMissingBootstrapPointerSeedsBeforeAnyMutation() throws Exception { + assertRejectedBeforeMutation( + List.of(), "Gameplay admission pointer bootstrap seeds are required"); + } - initializer.run(new DefaultApplicationArguments(new String[] {})); + @Test + void runRejectsNullBootstrapPointerSeedBeforeAnyMutation() throws Exception { + assertRejectedBeforeMutation( + Arrays.asList( + pointerSeed("demo", "Demo World", "production", "Live Realm", 1L, 1L, true, false), + null), + "Invalid gameplay admission pointer bootstrap seed at index 1: must not be null"); + } - ArgumentCaptor mutationCaptor = - ArgumentCaptor.forClass(GameplayAdmissionPointerMutation.class); - verify(authorityService).upsertPointer(mutationCaptor.capture()); - assertEquals("demo", mutationCaptor.getValue().worldSlug()); + @Test + void runRejectsBlankWorldSlugBeforeAnyMutation() throws Exception { + assertRejectedBeforeMutation( + List.of( + pointerSeed("demo", "Demo World", "production", "Live Realm", 1L, 1L, true, false), + pointerSeed(" ", "Broken World", "sandbox", "Sandbox Realm", 1L, 2L, false, true)), + "Invalid gameplay admission pointer bootstrap seed at index 1: world slug is required"); } @Test - void runDefaultsNullEnumFieldsDuringBootstrapMutation() throws Exception { + void runRejectsBlankWorldDisplayNameBeforeAnyMutation() throws Exception { + assertRejectedBeforeMutation( + List.of( + pointerSeed("demo", "Demo World", "production", "Live Realm", 1L, 1L, true, false), + pointerSeed("sandbox", " ", "sandbox", "Sandbox Realm", 1L, 2L, false, true)), + "Invalid gameplay admission pointer bootstrap seed at index 1: world display name is " + + "required"); + } + + @Test + void runRejectsBlankRealmSlugBeforeAnyMutation() throws Exception { + assertRejectedBeforeMutation( + List.of( + pointerSeed("demo", "Demo World", "production", "Live Realm", 1L, 1L, true, false), + pointerSeed("sandbox", "Sandbox World", "", "Sandbox Realm", 1L, 2L, false, true)), + "Invalid gameplay admission pointer bootstrap seed at index 1: realm slug is required"); + } + + @Test + void runRejectsBlankRealmDisplayNameBeforeAnyMutation() throws Exception { + assertRejectedBeforeMutation( + List.of( + pointerSeed("demo", "Demo World", "production", "Live Realm", 1L, 1L, true, false), + pointerSeed("sandbox", "Sandbox World", "sandbox", " ", 1L, 2L, false, true)), + "Invalid gameplay admission pointer bootstrap seed at index 1: realm display name is " + + "required"); + } + + @Test + void runRejectsNonPositiveTenantIdBeforeAnyMutation() throws Exception { + assertRejectedBeforeMutation( + List.of( + pointerSeed("demo", "Demo World", "production", "Live Realm", 1L, 1L, true, false), + pointerSeed( + "sandbox", "Sandbox World", "sandbox", "Sandbox Realm", 0L, 2L, false, true)), + "Invalid gameplay admission pointer bootstrap seed at index 1: tenant ID must be positive"); + } + + @Test + void runRejectsNonPositiveGameInstanceIdBeforeAnyMutation() throws Exception { + assertRejectedBeforeMutation( + List.of( + pointerSeed("demo", "Demo World", "production", "Live Realm", 1L, 1L, true, false), + pointerSeed( + "sandbox", "Sandbox World", "sandbox", "Sandbox Realm", 1L, 0L, false, true)), + "Invalid gameplay admission pointer bootstrap seed at index 1: game instance ID must be " + + "positive"); + } + + @Test + void runRejectsMultipleVisiblePublicProductionSeedsForTenantBeforeAnyMutation() throws Exception { + assertRejectedBeforeMutation( + List.of( + pointerSeed("demo", "Demo World", "production", "Live Realm", 1L, 1L, true, false), + pointerSeed( + "sandbox", "Builder Sandbox", "production", "Live Realm", 1L, 2L, true, true)), + "Gameplay admission pointer bootstrap must define exactly one visible public production " + + "realm for tenant 1"); + } + + @Test + void runRejectsNoVisiblePublicProductionSeedForTenantBeforeAnyMutation() throws Exception { + assertRejectedBeforeMutation( + List.of( + pointerSeed("demo", "Demo World", "production", "Live Realm", 1L, 1L, false, false)), + "Gameplay admission pointer bootstrap must define exactly one visible public production " + + "realm for tenant 1"); + } + + @Test + void runRejectsDuplicateWorldRealmSeedsBeforeAnyMutation() throws Exception { + assertRejectedBeforeMutation( + List.of( + pointerSeed("demo", "Demo World", "production", "Live Realm", 1L, 1L, true, false), + pointerSeed( + " DEMO ", "Duplicate World", "PRODUCTION", "Live Realm", 1L, 2L, false, true)), + "Invalid gameplay admission pointer bootstrap seed at index 1: duplicates a tenant world " + + "and realm selector"); + } + + @Test + void runRejectsDuplicateRuntimeTargetSeedsBeforeAnyMutation() throws Exception { + assertRejectedBeforeMutation( + List.of( + pointerSeed("demo", "Demo World", "production", "Live Realm", 1L, 1L, true, false), + pointerSeed( + "sandbox", "Sandbox World", "sandbox", "Sandbox Realm", 1L, 1L, false, true)), + "Invalid gameplay admission pointer bootstrap seed at index 1: duplicates a tenant runtime " + + "target"); + } + + @Test + void runKeepsAdmissionClosedForValidSeedsAcrossTenantsWithoutPointerWritesOrBootstrapLock() + throws Exception { when(pointerRepository.count()).thenReturn(0L); - GameplayAdmissionPointerBootstrapProperties.PointerSeed pointer = - pointerSeed("demo", "Demo World", "production", "Live Realm", 1L, 1L, false); - pointer.setStateScope(null); - pointer.setCharacterCreationPolicy(null); - properties.setPointers(List.of(pointer)); + properties.setPointers( + List.of( + pointerSeed("demo", "Demo World", "production", "Live Realm", 1L, 1L, true, false), + pointerSeed("demo", "Other Demo", "production", "Live Realm", 2L, 1L, true, true))); initializer.run(new DefaultApplicationArguments(new String[] {})); + verify(pointerRepository).count(); + verifyNoMoreInteractions(pointerRepository); + } - ArgumentCaptor mutationCaptor = - ArgumentCaptor.forClass(GameplayAdmissionPointerMutation.class); - verify(authorityService).upsertPointer(mutationCaptor.capture()); - assertEquals("SHARED", mutationCaptor.getValue().stateScope()); - assertEquals("ALLOW_NEW", mutationCaptor.getValue().characterCreationPolicy()); + @Test + void initializerIsRegisteredAsSpringComponent() { + assertTrue( + GameplayAdmissionPointerBootstrapInitializer.class.isAnnotationPresent(Component.class)); } private static GameplayAdmissionPointerBootstrapProperties.PointerSeed pointerSeed( @@ -118,6 +211,7 @@ private static GameplayAdmissionPointerBootstrapProperties.PointerSeed pointerSe String realmDisplayName, long tenantId, long gameInstanceId, + boolean publicProductionRealm, boolean requiresCharacterSelection) { GameplayAdmissionPointerBootstrapProperties.PointerSeed pointerSeed = new GameplayAdmissionPointerBootstrapProperties.PointerSeed(); @@ -128,11 +222,28 @@ private static GameplayAdmissionPointerBootstrapProperties.PointerSeed pointerSe pointerSeed.setTenantId(tenantId); pointerSeed.setGameInstanceId(gameInstanceId); pointerSeed.setVisible(true); - pointerSeed.setPublicProductionRealm(true); + pointerSeed.setPublicProductionRealm(publicProductionRealm); pointerSeed.setRequiresCharacterSelection(requiresCharacterSelection); pointerSeed.setStateScope(GameplayAdmissionPointerBootstrapProperties.StateScope.SHARED); pointerSeed.setCharacterCreationPolicy( GameplayAdmissionPointerBootstrapProperties.CharacterCreationPolicy.ALLOW_NEW); return pointerSeed; } + + private void assertRejectedBeforeMutation( + List pointers, + String expectedMessage) + throws Exception { + when(pointerRepository.count()).thenReturn(0L); + properties.setPointers(pointers); + + IllegalArgumentException error = + assertThrows( + IllegalArgumentException.class, + () -> initializer.run(new DefaultApplicationArguments(new String[] {}))); + + assertEquals(expectedMessage, error.getMessage()); + verify(pointerRepository).count(); + verifyNoMoreInteractions(pointerRepository); + } } diff --git a/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/repository/GameplayAdmissionPointerEventRepositoryTest.java b/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/repository/GameplayAdmissionPointerEventRepositoryTest.java new file mode 100644 index 0000000000..6636c2b259 --- /dev/null +++ b/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/repository/GameplayAdmissionPointerEventRepositoryTest.java @@ -0,0 +1,106 @@ +package net.firedevops.firemud.gamesession.repository; + +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertNull; + +import java.sql.Connection; +import java.sql.DriverManager; +import java.time.Instant; +import java.util.List; +import java.util.UUID; +import net.firedevops.firemud.gamesession.entity.GameplayAdmissionPointerEvent; +import org.jooq.DSLContext; +import org.jooq.SQLDialect; +import org.jooq.impl.DSL; +import org.junit.jupiter.api.Test; + +class GameplayAdmissionPointerEventRepositoryTest { + @Test + void savesCatalogRevisionAndStableIdentityAndKeepsUnknownValuesNull() throws Exception { + try (Connection connection = + DriverManager.getConnection( + "jdbc:h2:mem:gameplay-pointer-event-audit;MODE=PostgreSQL;DATABASE_TO_LOWER=TRUE;DB_CLOSE_DELAY=-1")) { + DSLContext dsl = DSL.using(connection, SQLDialect.H2); + createSchema(dsl); + GameplayAdmissionPointerEventRepository repository = + new GameplayAdmissionPointerEventRepository(dsl); + UUID realmId = UUID.fromString("c214a525-a48e-4734-8927-73eb17c44511"); + UUID namespaceId = UUID.fromString("3d89b194-e8f5-4ea2-9d80-04b8f71f28b6"); + + GameplayAdmissionPointerEvent current = event("2026-09-01T00:00:00Z"); + current.setCatalogRevision(12L); + current.setRealmId(realmId); + current.setPlayableStateNamespaceId(namespaceId); + repository.save(current); + + GameplayAdmissionPointerEvent historical = event("2026-08-31T00:00:00Z"); + repository.save(historical); + + List events = + repository.findByTenantIdAndWorldSlugAndRealmSlugOrderByOccurredAtDesc( + 9L, "demo", "production"); + + assertEquals(2, events.size()); + assertEquals(12L, events.get(0).getCatalogRevision()); + assertEquals(realmId, events.get(0).getRealmId()); + assertEquals(namespaceId, events.get(0).getPlayableStateNamespaceId()); + assertNull(events.get(1).getCatalogRevision()); + assertNull(events.get(1).getRealmId()); + assertNull(events.get(1).getPlayableStateNamespaceId()); + } + } + + private static GameplayAdmissionPointerEvent event(String occurredAt) { + GameplayAdmissionPointerEvent event = new GameplayAdmissionPointerEvent(); + event.setWorldSlug("demo"); + event.setRealmSlug("production"); + event.setWorldDisplayName("Demo World"); + event.setRealmDisplayName("Production Realm"); + event.setTenantId(9L); + event.setGameInstanceId(31L); + event.setPointerVersion(4L); + event.setVisible(true); + event.setPublicProductionRealm(true); + event.setRequiresCharacterSelection(false); + event.setStateScope("SHARED"); + event.setCharacterCreationPolicy("ALLOW_NEW"); + event.setActorPrincipal("operator"); + event.setReason("catalog update"); + event.setControlPlaneRequestId("request-" + occurredAt); + event.setOccurredAt(Instant.parse(occurredAt)); + return event; + } + + private static void createSchema(DSLContext dsl) { + dsl.execute( + """ + CREATE TABLE gameplay_admission_pointer_event ( + id BIGINT GENERATED BY DEFAULT AS IDENTITY PRIMARY KEY, + world_slug VARCHAR(120) NOT NULL, + realm_slug VARCHAR(120) NOT NULL, + world_display_name VARCHAR(200) NOT NULL, + realm_display_name VARCHAR(200) NOT NULL, + tenant_id BIGINT NOT NULL, + game_instance_id BIGINT NOT NULL, + pointer_version BIGINT NOT NULL, + catalog_revision BIGINT, + realm_id UUID, + playable_state_namespace_id UUID, + visible BOOLEAN NOT NULL, + public_production_realm BOOLEAN NOT NULL, + requires_character_selection BOOLEAN NOT NULL, + state_scope VARCHAR(32) NOT NULL, + character_creation_policy VARCHAR(32) NOT NULL, + actor_principal VARCHAR(200) NOT NULL, + reason VARCHAR(500) NOT NULL, + control_plane_request_id VARCHAR(120) NOT NULL, + prepared_version_upgrade_id VARCHAR(64), + occurred_at TIMESTAMP NOT NULL, + CONSTRAINT gameplay_admission_pointer_event_catalog_revision_positive + CHECK (catalog_revision IS NULL OR catalog_revision > 0), + CONSTRAINT gameplay_admission_pointer_event_identity_pair_complete + CHECK ((realm_id IS NULL) = (playable_state_namespace_id IS NULL)) + ) + """); + } +} diff --git a/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/repository/GameplayAdmissionPointerRepositoryTest.java b/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/repository/GameplayAdmissionPointerRepositoryTest.java new file mode 100644 index 0000000000..0d294032c0 --- /dev/null +++ b/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/repository/GameplayAdmissionPointerRepositoryTest.java @@ -0,0 +1,214 @@ +package net.firedevops.firemud.gamesession.repository; + +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertNotEquals; +import static org.junit.jupiter.api.Assertions.assertNotNull; +import static org.junit.jupiter.api.Assertions.assertThrows; + +import java.sql.Connection; +import java.sql.DriverManager; +import java.time.Instant; +import java.util.UUID; +import net.firedevops.firemud.gamesession.entity.GameplayAdmissionPointer; +import net.firedevops.firemud.gamesession.service.AdmissionPointerVersionMismatchException; +import org.jooq.DSLContext; +import org.jooq.SQLDialect; +import org.jooq.exception.DataAccessException; +import org.jooq.impl.DSL; +import org.junit.jupiter.api.Test; + +class GameplayAdmissionPointerRepositoryTest { + @Test + void stableRealmAndNamespaceIdentitySurviveRuntimeReplacement() throws Exception { + try (Connection connection = + DriverManager.getConnection( + "jdbc:h2:mem:gameplay-pointer-identity;MODE=PostgreSQL;DATABASE_TO_LOWER=TRUE;DB_CLOSE_DELAY=-1")) { + DSLContext dsl = DSL.using(connection, SQLDialect.H2); + createSchema(dsl); + GameplayAdmissionPointerRepository repository = new GameplayAdmissionPointerRepository(dsl); + + GameplayAdmissionPointer shared = pointer(7L, 44L, "SHARED", "production"); + GameplayAdmissionPointer createdShared = repository.save(shared); + UUID sharedRealmId = createdShared.getRealmId(); + UUID sharedNamespaceId = createdShared.getPlayableStateNamespaceId(); + GameplayAdmissionPointer sharedReadback = + repository.findByTenantIdAndWorldSlugAndRealmSlug(7L, "demo", "production").orElseThrow(); + + GameplayAdmissionPointer secondShared = + repository.save(pointer(7L, 45L, "SHARED", "seasonal")); + GameplayAdmissionPointer isolated = repository.save(pointer(7L, 46L, "ISOLATED", "playtest")); + + assertNotNull(sharedRealmId); + assertNotNull(sharedNamespaceId); + assertEquals(sharedRealmId, sharedReadback.getRealmId()); + assertEquals(sharedNamespaceId, sharedReadback.getPlayableStateNamespaceId()); + assertNotNull(secondShared.getRealmId()); + assertNotNull(isolated.getRealmId()); + assertEquals(sharedNamespaceId, secondShared.getPlayableStateNamespaceId()); + assertNotEquals(sharedRealmId, secondShared.getRealmId()); + assertNotEquals(sharedNamespaceId, isolated.getPlayableStateNamespaceId()); + + createdShared.setGameInstanceId(99L); + createdShared.setPointerVersion(2L); + createdShared.setCatalogRevision(1L); + GameplayAdmissionPointer replaced = repository.save(createdShared); + + assertEquals(99L, replaced.getGameInstanceId()); + assertEquals(sharedRealmId, replaced.getRealmId()); + assertEquals(sharedNamespaceId, replaced.getPlayableStateNamespaceId()); + } + } + + @Test + void repositoryRejectsAttemptToReplaceStableRealmIdentity() throws Exception { + try (Connection connection = + DriverManager.getConnection( + "jdbc:h2:mem:gameplay-pointer-identity-immutable;MODE=PostgreSQL;DATABASE_TO_LOWER=TRUE;DB_CLOSE_DELAY=-1")) { + DSLContext dsl = DSL.using(connection, SQLDialect.H2); + createSchema(dsl); + GameplayAdmissionPointerRepository repository = new GameplayAdmissionPointerRepository(dsl); + GameplayAdmissionPointer created = repository.save(pointer(7L, 44L, "ISOLATED", "fork")); + + created.setPointerVersion(2L); + created.setRealmId(UUID.randomUUID()); + + org.junit.jupiter.api.Assertions.assertThrows( + IllegalStateException.class, () -> repository.save(created)); + } + } + + @Test + void catalogOnlyUpdatePreservesPointerVersionAndFencesStaleCatalogRevision() throws Exception { + try (Connection connection = + DriverManager.getConnection( + "jdbc:h2:mem:gameplay-pointer-catalog-cas;MODE=PostgreSQL;DATABASE_TO_LOWER=TRUE;DB_CLOSE_DELAY=-1")) { + DSLContext dsl = DSL.using(connection, SQLDialect.H2); + createSchema(dsl); + GameplayAdmissionPointerRepository repository = new GameplayAdmissionPointerRepository(dsl); + repository.save(pointer(7L, 44L, "SHARED", "production")); + + GameplayAdmissionPointer stale = + repository.findByTenantIdAndWorldSlugAndRealmSlug(7L, "demo", "production").orElseThrow(); + GameplayAdmissionPointer catalogUpdate = + repository.findByTenantIdAndWorldSlugAndRealmSlug(7L, "demo", "production").orElseThrow(); + catalogUpdate.setWorldDisplayName("Renamed Demo World"); + catalogUpdate.setPointerVersion(1L); + catalogUpdate.setCatalogRevision(2L); + + GameplayAdmissionPointer updated = repository.save(catalogUpdate); + + assertEquals(1L, updated.getPointerVersion()); + assertEquals(2L, updated.getCatalogRevision()); + + stale.setRealmDisplayName("Stale Realm Display"); + stale.setPointerVersion(1L); + stale.setCatalogRevision(2L); + assertThrows(AdmissionPointerVersionMismatchException.class, () -> repository.save(stale)); + } + } + + @Test + void h2FixtureEnforcesProductionCatalogAndRealmIdentityConstraints() throws Exception { + try (Connection connection = + DriverManager.getConnection( + "jdbc:h2:mem:gameplay-pointer-production-constraints;MODE=PostgreSQL;DATABASE_TO_LOWER=TRUE;DB_CLOSE_DELAY=-1")) { + DSLContext dsl = DSL.using(connection, SQLDialect.H2); + createSchema(dsl); + GameplayAdmissionPointerRepository repository = new GameplayAdmissionPointerRepository(dsl); + GameplayAdmissionPointer production = + repository.save(pointer(7L, 44L, "SHARED", "production")); + GameplayAdmissionPointer seasonal = repository.save(pointer(7L, 45L, "ISOLATED", "seasonal")); + + assertThrows( + DataAccessException.class, + () -> + dsl.execute( + "UPDATE gameplay_admission_pointer SET catalog_revision = 0 WHERE id = ?", + production.getId())); + assertThrows( + DataAccessException.class, + () -> + dsl.execute( + "UPDATE gameplay_admission_pointer SET playable_state_namespace_id = NULL " + + "WHERE id = ?", + production.getId())); + assertThrows( + DataAccessException.class, + () -> + dsl.execute( + "UPDATE gameplay_admission_pointer SET realm_id = ? WHERE id = ?", + production.getRealmId(), + seasonal.getId())); + } + } + + private static GameplayAdmissionPointer pointer( + long tenantId, long gameInstanceId, String stateScope, String realmSlug) { + GameplayAdmissionPointer pointer = new GameplayAdmissionPointer(); + pointer.setWorldSlug("demo"); + pointer.setWorldDisplayName("Demo World"); + pointer.setRealmSlug(realmSlug); + pointer.setRealmDisplayName(realmSlug); + pointer.setTenantId(tenantId); + pointer.setGameInstanceId(gameInstanceId); + pointer.setPointerVersion(1L); + pointer.setCatalogRevision(1L); + pointer.setVisible(true); + pointer.setPublicProductionRealm("production".equals(realmSlug)); + pointer.setRequiresCharacterSelection(false); + pointer.setStateScope(stateScope); + pointer.setCharacterCreationPolicy("ALLOW_NEW"); + pointer.setLastUpdatedBy("test"); + pointer.setLastUpdateReason("test"); + pointer.setCreatedAt(Instant.parse("2026-09-24T00:00:00Z")); + pointer.setUpdatedAt(Instant.parse("2026-09-24T00:00:00Z")); + return pointer; + } + + private static void createSchema(DSLContext dsl) { + dsl.execute( + """ + CREATE TABLE gameplay_tenant_shared_playable_state_namespace ( + tenant_id BIGINT PRIMARY KEY, + playable_state_namespace_id UUID NOT NULL UNIQUE, + allocated_at TIMESTAMP NOT NULL DEFAULT CURRENT_TIMESTAMP + ) + """); + dsl.execute( + """ + CREATE TABLE gameplay_admission_pointer ( + id BIGINT GENERATED BY DEFAULT AS IDENTITY PRIMARY KEY, + world_slug VARCHAR(120) NOT NULL, + world_display_name VARCHAR(200) NOT NULL, + realm_slug VARCHAR(120) NOT NULL, + realm_display_name VARCHAR(200) NOT NULL, + tenant_id BIGINT NOT NULL, + game_instance_id BIGINT NOT NULL, + pointer_version BIGINT NOT NULL, + catalog_revision BIGINT NOT NULL, + realm_id UUID, + playable_state_namespace_id UUID, + visible BOOLEAN NOT NULL, + public_production_realm BOOLEAN NOT NULL, + requires_character_selection BOOLEAN NOT NULL, + state_scope VARCHAR(32) NOT NULL, + character_creation_policy VARCHAR(32) NOT NULL, + last_updated_by VARCHAR(200) NOT NULL, + last_update_reason VARCHAR(500) NOT NULL, + created_at TIMESTAMP NOT NULL, + updated_at TIMESTAMP NOT NULL, + CONSTRAINT uq_pointer_tenant_world_realm UNIQUE (tenant_id, world_slug, realm_slug), + CONSTRAINT uq_pointer_tenant_runtime UNIQUE (tenant_id, game_instance_id), + CONSTRAINT gameplay_admission_pointer_catalog_revision_positive + CHECK (catalog_revision > 0), + CONSTRAINT gameplay_admission_pointer_identity_pair_complete + CHECK ((realm_id IS NULL) = (playable_state_namespace_id IS NULL)) + ) + """); + // H2 cannot express this partial-index predicate; its nullable unique index exercises + // populated realm IDs, while the migration integration test proves the PostgreSQL index. + dsl.execute( + "CREATE UNIQUE INDEX uq_gameplay_admission_pointer_realm_id " + + "ON gameplay_admission_pointer (realm_id)"); + } +} diff --git a/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/service/impl/DatabaseGameplayAdmissionPointerAuthorityServiceTest.java b/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/service/impl/DatabaseGameplayAdmissionPointerAuthorityServiceTest.java index ae5d5933b0..e00918d460 100644 --- a/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/service/impl/DatabaseGameplayAdmissionPointerAuthorityServiceTest.java +++ b/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/service/impl/DatabaseGameplayAdmissionPointerAuthorityServiceTest.java @@ -3,10 +3,13 @@ import static org.junit.jupiter.api.Assertions.assertEquals; import static org.junit.jupiter.api.Assertions.assertThrows; import static org.mockito.ArgumentMatchers.any; +import static org.mockito.Mockito.never; import static org.mockito.Mockito.verify; +import static org.mockito.Mockito.verifyNoInteractions; import static org.mockito.Mockito.when; import java.util.Optional; +import java.util.UUID; import net.firedevops.firemud.gamesession.entity.GameplayAdmissionPointer; import net.firedevops.firemud.gamesession.entity.GameplayAdmissionPointerEvent; import net.firedevops.firemud.gamesession.repository.GameplayAdmissionPointerEventRepository; @@ -38,6 +41,7 @@ void upsertPointerRejectsMismatchedExpectedVersion() { GameplayAdmissionPointer existing = new GameplayAdmissionPointer(); existing.setId(11L); existing.setPointerVersion(3L); + existing.setStateScope("SHARED"); when(pointerRepository.findByTenantIdAndWorldSlugAndRealmSlug(1L, "demo", "production")) .thenReturn(Optional.of(existing)); @@ -131,6 +135,80 @@ void upsertPointerAllowsCreateWhenExpectedVersionIsZero() { verify(eventRepository).save(any(GameplayAdmissionPointerEvent.class)); } + @Test + void upsertPointerAdvancesCatalogRevisionWithoutAdvancingPointerVersion() { + GameplayAdmissionPointer existing = existingPointer(); + when(pointerRepository.findByTenantIdAndWorldSlugAndRealmSlug(1L, "demo", "production")) + .thenReturn(Optional.of(existing)); + when(pointerRepository.save(any(GameplayAdmissionPointer.class))) + .thenAnswer(invocation -> invocation.getArgument(0)); + + GameplayAdmissionPointerSnapshot snapshot = + service.upsertPointer( + new GameplayAdmissionPointerMutation( + "demo", + "Renamed Demo World", + "production", + "Live Realm", + 1L, + 7L, + true, + true, + false, + "SHARED", + "ALLOW_NEW", + "tester", + "display update", + "req-catalog-only", + 1L, + null)); + + assertEquals(1L, snapshot.pointerVersion()); + assertEquals(2L, snapshot.catalogRevision()); + verify(pointerRepository).save(any(GameplayAdmissionPointer.class)); + ArgumentCaptor eventCaptor = + ArgumentCaptor.forClass(GameplayAdmissionPointerEvent.class); + verify(eventRepository).save(eventCaptor.capture()); + assertEquals(1L, eventCaptor.getValue().getPointerVersion()); + assertEquals(2L, eventCaptor.getValue().getCatalogRevision()); + assertEquals(existing.getRealmId(), eventCaptor.getValue().getRealmId()); + assertEquals( + existing.getPlayableStateNamespaceId(), + eventCaptor.getValue().getPlayableStateNamespaceId()); + } + + @Test + void upsertPointerExactNoOpDoesNotAdvanceOrPersistVersions() { + GameplayAdmissionPointer existing = existingPointer(); + when(pointerRepository.findByTenantIdAndWorldSlugAndRealmSlug(1L, "demo", "production")) + .thenReturn(Optional.of(existing)); + + GameplayAdmissionPointerSnapshot snapshot = + service.upsertPointer( + new GameplayAdmissionPointerMutation( + "demo", + "Demo World", + "production", + "Live Realm", + 1L, + 7L, + true, + true, + false, + "SHARED", + "ALLOW_NEW", + "tester", + "repeat", + "req-no-op", + 1L, + null)); + + assertEquals(1L, snapshot.pointerVersion()); + assertEquals(1L, snapshot.catalogRevision()); + verify(pointerRepository, never()).save(any(GameplayAdmissionPointer.class)); + verifyNoInteractions(eventRepository); + } + @Test void findPointerByTenantAndRealmSlugDelegatesToRepository() { GameplayAdmissionPointer existing = new GameplayAdmissionPointer(); @@ -151,4 +229,25 @@ void findPointerByTenantAndRealmSlugDelegatesToRepository() { assertEquals(44L, snapshot.gameInstanceId()); verify(pointerRepository).findByTenantIdAndWorldSlugAndRealmSlug(7L, "demo", "production"); } + + private static GameplayAdmissionPointer existingPointer() { + GameplayAdmissionPointer pointer = new GameplayAdmissionPointer(); + pointer.setId(11L); + pointer.setWorldSlug("demo"); + pointer.setWorldDisplayName("Demo World"); + pointer.setRealmSlug("production"); + pointer.setRealmDisplayName("Live Realm"); + pointer.setTenantId(1L); + pointer.setGameInstanceId(7L); + pointer.setPointerVersion(1L); + pointer.setCatalogRevision(1L); + pointer.setRealmId(UUID.fromString("3ce19e6a-a63f-46f4-8e25-b105694c79e9")); + pointer.setPlayableStateNamespaceId(UUID.fromString("f673a1e6-648d-4ac3-8f3d-4b7cc4380f2a")); + pointer.setVisible(true); + pointer.setPublicProductionRealm(true); + pointer.setRequiresCharacterSelection(false); + pointer.setStateScope("SHARED"); + pointer.setCharacterCreationPolicy("ALLOW_NEW"); + return pointer; + } } diff --git a/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/service/impl/GameSessionControlPlaneGrpcServiceTest.java b/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/service/impl/GameSessionControlPlaneGrpcServiceTest.java index 5cd84fdb95..37d3c99eed 100644 --- a/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/service/impl/GameSessionControlPlaneGrpcServiceTest.java +++ b/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/service/impl/GameSessionControlPlaneGrpcServiceTest.java @@ -15,6 +15,7 @@ import java.util.Map; import java.util.Objects; import java.util.Optional; +import java.util.UUID; import java.util.concurrent.atomic.AtomicLong; import java.util.concurrent.atomic.AtomicReference; import net.firedevops.firemud.automationscripting.v1.GetScriptPatchStatusResponse; @@ -541,7 +542,10 @@ void getGameInstanceRuntimeStateReturnsCanonicalVersionAndPinMetadata() { true, true, "SHARED", - "CREATE_ALLOWED"))); + "CREATE_ALLOWED", + 12L, + UUID.fromString("11111111-1111-1111-1111-111111111111"), + UUID.fromString("22222222-2222-2222-2222-222222222222")))); SessionContext.setContext("1", List.of("platformAdmin"), Map.of()); GameSessionControlPlaneGrpcService service = @@ -704,7 +708,10 @@ void getGameInstanceRuntimeStateClearsSingularRoutingBundleWhenRuntimeHasMultipl true, true, "SHARED", - "CREATE_ALLOWED"), + "CREATE_ALLOWED", + 11L, + UUID.fromString("11111111-1111-1111-1111-111111111111"), + UUID.fromString("22222222-2222-2222-2222-222222222222")), new GameplayAdmissionPointerSnapshot( "sandbox", "Sandbox World", @@ -717,7 +724,10 @@ void getGameInstanceRuntimeStateClearsSingularRoutingBundleWhenRuntimeHasMultipl false, true, "SHARED", - "CREATE_ALLOWED"))); + "CREATE_ALLOWED", + 12L, + UUID.fromString("33333333-3333-3333-3333-333333333333"), + UUID.fromString("44444444-4444-4444-4444-444444444444")))); SessionContext.setContext("1", List.of("platformAdmin"), Map.of()); GameSessionControlPlaneGrpcService service = @@ -793,7 +803,10 @@ void getGameInstanceRuntimeStateClearsSingularRoutingBundleWhenOnlyPointerIsInco true, true, "SHARED", - "CREATE_ALLOWED"))); + "CREATE_ALLOWED", + 11L, + UUID.fromString("11111111-1111-1111-1111-111111111111"), + UUID.fromString("22222222-2222-2222-2222-222222222222")))); SessionContext.setContext("1", List.of("platformAdmin"), Map.of()); GameSessionControlPlaneGrpcService service = @@ -868,7 +881,10 @@ void getGameInstanceRuntimeStateClearsSingularRoutingBundleWhenOnlyPointerLacksR true, true, "SHARED", - "CREATE_ALLOWED"))); + "CREATE_ALLOWED", + 11L, + UUID.fromString("11111111-1111-1111-1111-111111111111"), + UUID.fromString("22222222-2222-2222-2222-222222222222")))); SessionContext.setContext("1", List.of("platformAdmin"), Map.of()); GameSessionControlPlaneGrpcService service = @@ -1157,76 +1173,14 @@ public void onNext(GetGameSessionPinConvergenceResponse value) { } @Test - void setAdmissionPointerAllowsAdminCaller() { + void setAdmissionPointerRejectsInitialCreationUntilCatalogIdentityIsSupported() { GameInstanceRepository gameInstanceRepository = Mockito.mock(GameInstanceRepository.class); - GameInstance targetInstance = runningGameInstance(); - targetInstance.setId(7L); - targetInstance.setTenantId(1L); - targetInstance.setVersionId(9L); - targetInstance.setLaunchDescriptorId("ld-9"); - targetInstance.setRemapSetId("remap-1"); - Mockito.when(gameInstanceRepository.findById(7L)).thenReturn(Optional.of(targetInstance)); GameplayAdmissionPointerAuthorityService authorityService = Mockito.mock(GameplayAdmissionPointerAuthorityService.class); - Mockito.when(authorityService.findPointer(1L, "demo", "production")) - .thenReturn( - Optional.of( - new GameplayAdmissionPointerSnapshot( - "demo", - "Demo World", - "production", - "Live Realm", - 1L, - 5L, - 2L, - true, - true, - false, - "SHARED", - "ALLOW_NEW"))); - Mockito.when(authorityService.listPointerAudit(1L, "demo", "production")) - .thenReturn( - List.of( - new GameplayAdmissionPointerAuditEntry( - "demo", - "production", - "Demo World", - "Live Realm", - 1L, - 7L, - 3L, - true, - true, - false, - "SHARED", - "ALLOW_NEW", - "tester", - "cutover", - "req-1", - "pvu-1", - Instant.parse("2026-04-15T00:00:00Z")))); VersionUpgradePreparationService versionUpgradePreparationService = Mockito.mock(VersionUpgradePreparationService.class); - Mockito.when(versionUpgradePreparationService.getPreparedVersionUpgrade(1L, "pvu-1")) - .thenReturn( - new net.firedevops.firemud.gamesession.dto.PreparedVersionUpgradeDto( - "pvu-1", - "prep-req-1", - 1L, - 5L, - 7L, - 9L, - "ld-9", - "remap-1", - "COMPATIBLE", - List.of(), - List.of("WORLD", "ENTITY"), - Instant.parse("2026-04-16T00:00:00Z"), - List.of(), - null, - null, - null, - null)); + Mockito.when(authorityService.findPointer(1L, "demo", "production")) + .thenReturn(Optional.empty()); SessionContext.setContext("1", List.of("platformAdmin"), Map.of()); GameSessionControlPlaneGrpcService service = controlPlaneService( @@ -1253,10 +1207,9 @@ void setAdmissionPointerAllowsAdminCaller() { .setStateScope("SHARED") .setCharacterCreationPolicy("ALLOW_NEW") .setActorPrincipal("tester") - .setReason("cutover") + .setReason("initial create") .setControlPlaneRequestId("req-1") - .setExpectedPointerVersion(2L) - .setPreparedVersionUpgradeId("pvu-1") + .setExpectedPointerVersion(0L) .build(), new NoopObserver<>() { @Override @@ -1265,44 +1218,24 @@ public void onNext(SetAdmissionPointerResponse value) { } }); - assertEquals("demo", responseRef.get().getPointer().getWorldSlug()); - assertEquals(3L, responseRef.get().getPointer().getPointerVersion()); - assertEquals("pvu-1", responseRef.get().getPointer().getPreparedVersionUpgradeId()); - Mockito.verify(authorityService) - .upsertPointer( - Mockito.argThat( - mutation -> - Objects.equals(mutation.expectedPointerVersion(), 2L) - && Objects.equals(mutation.preparedVersionUpgradeId(), "pvu-1"))); + assertEquals("FAILED_PRECONDITION", responseRef.get().getError().getCode()); + assertEquals( + "admission-pointer creation is temporarily disabled until catalog revision and " + + "stable realm/namespace identity preconditions are supported", + responseRef.get().getError().getMessage()); + Mockito.verify(authorityService, Mockito.never()).upsertPointer(Mockito.any()); + Mockito.verify(authorityService, Mockito.never()).listPointerAudit(1L, "demo", "production"); + Mockito.verifyNoInteractions(gameInstanceRepository); + Mockito.verifyNoInteractions(versionUpgradePreparationService); } @Test - void setAdmissionPointerRejectsTargetChangeWithoutPreparedUpgrade() { + void setAdmissionPointerRejectsCreateWithoutExplicitZeroVersion() { GameInstanceRepository gameInstanceRepository = Mockito.mock(GameInstanceRepository.class); - GameInstance targetInstance = runningGameInstance(); - targetInstance.setId(7L); - targetInstance.setTenantId(1L); - targetInstance.setVersionId(9L); - targetInstance.setLaunchDescriptorId("ld-9"); - Mockito.when(gameInstanceRepository.findById(7L)).thenReturn(Optional.of(targetInstance)); GameplayAdmissionPointerAuthorityService authorityService = Mockito.mock(GameplayAdmissionPointerAuthorityService.class); Mockito.when(authorityService.findPointer(1L, "demo", "production")) - .thenReturn( - Optional.of( - new GameplayAdmissionPointerSnapshot( - "demo", - "Demo World", - "production", - "Live Realm", - 1L, - 5L, - 2L, - true, - true, - false, - "SHARED", - "ALLOW_NEW"))); + .thenReturn(Optional.empty()); SessionContext.setContext("1", List.of("platformAdmin"), Map.of()); GameSessionControlPlaneGrpcService service = controlPlaneService( @@ -1331,7 +1264,6 @@ void setAdmissionPointerRejectsTargetChangeWithoutPreparedUpgrade() { .setActorPrincipal("tester") .setReason("cutover") .setControlPlaneRequestId("req-1") - .setExpectedPointerVersion(2L) .build(), new NoopObserver<>() { @Override @@ -1340,12 +1272,18 @@ public void onNext(SetAdmissionPointerResponse value) { } }); - assertEquals("CUTOVER_PREPARATION_INVALID", responseRef.get().getError().getCode()); + assertEquals("FAILED_PRECONDITION", responseRef.get().getError().getCode()); + assertEquals( + "admission-pointer creation is temporarily disabled until catalog revision and " + + "stable realm/namespace identity preconditions are supported", + responseRef.get().getError().getMessage()); Mockito.verify(authorityService, Mockito.never()).upsertPointer(Mockito.any()); + Mockito.verify(authorityService, Mockito.never()).listPointerAudit(1L, "demo", "production"); + Mockito.verifyNoInteractions(gameInstanceRepository); } @Test - void setAdmissionPointerRejectsStaleExpectedVersion() { + void setAdmissionPointerRejectsMutationOfExistingPointerUntilCatalogRevisionIsSupported() { GameInstanceRepository gameInstanceRepository = Mockito.mock(GameInstanceRepository.class); GameInstance targetInstance = runningGameInstance(); targetInstance.setId(7L); @@ -1372,32 +1310,8 @@ void setAdmissionPointerRejectsStaleExpectedVersion() { false, "SHARED", "ALLOW_NEW"))); - Mockito.when(authorityService.upsertPointer(Mockito.any())) - .thenThrow( - new AdmissionPointerVersionMismatchException( - "expected_pointer_version does not match current pointer version")); VersionUpgradePreparationService versionUpgradePreparationService = Mockito.mock(VersionUpgradePreparationService.class); - Mockito.when(versionUpgradePreparationService.getPreparedVersionUpgrade(1L, "pvu-1")) - .thenReturn( - new net.firedevops.firemud.gamesession.dto.PreparedVersionUpgradeDto( - "pvu-1", - "prep-req-1", - 1L, - 5L, - 7L, - 9L, - "ld-9", - "remap-1", - "COMPATIBLE", - List.of(), - List.of("WORLD", "ENTITY"), - Instant.parse("2026-04-16T00:00:00Z"), - List.of(), - null, - null, - null, - null)); SessionContext.setContext("1", List.of("platformAdmin"), Map.of()); GameSessionControlPlaneGrpcService service = controlPlaneService( @@ -1436,7 +1350,14 @@ public void onNext(SetAdmissionPointerResponse value) { } }); - assertEquals("POINTER_VERSION_MISMATCH", responseRef.get().getError().getCode()); + assertEquals("FAILED_PRECONDITION", responseRef.get().getError().getCode()); + assertEquals( + "admission-pointer updates are temporarily disabled until catalog revision " + + "preconditions are supported", + responseRef.get().getError().getMessage()); + Mockito.verify(authorityService, Mockito.never()).upsertPointer(Mockito.any()); + Mockito.verifyNoInteractions(gameInstanceRepository); + Mockito.verifyNoInteractions(versionUpgradePreparationService); } @Test @@ -1491,7 +1412,7 @@ public void onNext(SetAdmissionPointerResponse value) { } @Test - void executePreparedVersionCutoverSwapsPointerUsingPreparedProof() { + void executePreparedVersionCutoverFailsClosedUntilCatalogRevisionIsSupported() { GameInstanceRepository gameInstanceRepository = Mockito.mock(GameInstanceRepository.class); GameInstance targetInstance = runningGameInstance(); targetInstance.setId(7L); @@ -1593,92 +1514,34 @@ public void onNext(ExecutePreparedVersionCutoverResponse value) { } }); - assertEquals(3L, responseRef.get().getPointer().getPointerVersion()); - assertEquals("pvu-1", responseRef.get().getPointer().getPreparedVersionUpgradeId()); - Mockito.verify(versionUpgradePreparationService) - .markPreparedVersionUpgradeExecuted(1L, "pvu-1", 7L, 3L, "req-1"); - Mockito.verify(authorityService) - .upsertPointer( - Mockito.argThat( - mutation -> - Objects.equals(mutation.preparedVersionUpgradeId(), "pvu-1") - && Objects.equals(mutation.expectedPointerVersion(), 2L) - && mutation.gameInstanceId() == 7L)); + assertEquals("FAILED_PRECONDITION", responseRef.get().getError().getCode()); + assertEquals( + "prepared cutover is temporarily disabled until catalog revision preconditions are supported", + responseRef.get().getError().getMessage()); + Mockito.verifyNoInteractions(authorityService); + Mockito.verifyNoInteractions(versionUpgradePreparationService); + Mockito.verifyNoInteractions(gameInstanceRepository); } @Test - void executePreparedVersionCutoverIsIdempotentAfterSameRequestAlreadyMovedPointer() { - GameplayAdmissionPointerAuthorityService authorityService = - Mockito.mock(GameplayAdmissionPointerAuthorityService.class); - Mockito.when(authorityService.findPointer(1L, "demo", "production")) - .thenReturn( - Optional.of( - new GameplayAdmissionPointerSnapshot( - "demo", - "Demo World", - "production", - "Live Realm", - 1L, - 7L, - 3L, - true, - true, - false, - "SHARED", - "ALLOW_NEW"))); - Mockito.when(authorityService.listPointerAudit(1L, "demo", "production")) - .thenReturn( - List.of( - new GameplayAdmissionPointerAuditEntry( - "demo", - "production", - "Demo World", - "Live Realm", - 1L, - 7L, - 3L, - true, - true, - false, - "SHARED", - "ALLOW_NEW", - "tester", - "cutover", - "req-1", - "pvu-1", - Instant.parse("2026-04-16T00:00:00Z")))); - VersionUpgradePreparationService versionUpgradePreparationService = - Mockito.mock(VersionUpgradePreparationService.class); - Mockito.when(versionUpgradePreparationService.getPreparedVersionUpgrade(1L, "pvu-1")) - .thenReturn( - new net.firedevops.firemud.gamesession.dto.PreparedVersionUpgradeDto( - "pvu-1", - "prep-req-1", - 1L, - 5L, - 7L, - 9L, - "ld-9", - "remap-1", - "COMPATIBLE", - List.of(), - List.of("WORLD", "ENTITY"), - Instant.parse("2026-04-16T00:00:00Z"), - List.of(), - 7L, - 3L, - Instant.parse("2026-04-16T00:00:01Z"), - "req-1")); + void executePreparedVersionCutoverMapsTruePointerVersionMismatchSeparately() { + GameSessionAdmissionPointerControlPlaneService admissionPointerControlPlaneService = + Mockito.mock(GameSessionAdmissionPointerControlPlaneService.class); + Mockito.doThrow(new AdmissionPointerVersionMismatchException("pointer version changed")) + .when(admissionPointerControlPlaneService) + .executePreparedVersionCutover( + Mockito.eq(1L), + Mockito.eq(7L), + Mockito.any(ExecutePreparedVersionCutoverRequest.class)); SessionContext.setContext("1", List.of("platformAdmin"), Map.of()); GameSessionControlPlaneGrpcService service = - controlPlaneService( - Mockito.mock(GameInstanceRepository.class), - Mockito.mock(GameplayCommandRepository.class), - Mockito.mock(RuntimeRegionStatusRepository.class), - authorityService, - Mockito.mock(InstanceCutoverCompatibilityService.class), - versionUpgradePreparationService, - Mockito.mock(TickService.class), + new GameSessionControlPlaneGrpcService( + null, + null, + null, + admissionPointerControlPlaneService, + null, + null, new SimpleMeterRegistry()); AtomicReference responseRef = new AtomicReference<>(); @@ -1701,16 +1564,14 @@ public void onNext(ExecutePreparedVersionCutoverResponse value) { } }); - assertEquals(3L, responseRef.get().getPointer().getPointerVersion()); - assertEquals("pvu-1", responseRef.get().getPointer().getPreparedVersionUpgradeId()); - Mockito.verify(authorityService, Mockito.never()).upsertPointer(Mockito.any()); - Mockito.verify(versionUpgradePreparationService, Mockito.never()) - .markPreparedVersionUpgradeExecuted( - Mockito.anyLong(), - Mockito.anyString(), - Mockito.anyLong(), - Mockito.anyLong(), - Mockito.anyString()); + assertEquals("POINTER_VERSION_MISMATCH", responseRef.get().getError().getCode()); + assertEquals("pointer version changed", responseRef.get().getError().getMessage()); + Mockito.verify(admissionPointerControlPlaneService) + .executePreparedVersionCutover( + Mockito.eq(1L), + Mockito.eq(7L), + Mockito.any(ExecutePreparedVersionCutoverRequest.class)); + Mockito.verifyNoMoreInteractions(admissionPointerControlPlaneService); } @Test diff --git a/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/service/impl/GameSessionGrpcServiceTest.java b/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/service/impl/GameSessionGrpcServiceTest.java index 27318cf7ba..ebe7a5b73a 100644 --- a/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/service/impl/GameSessionGrpcServiceTest.java +++ b/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/service/impl/GameSessionGrpcServiceTest.java @@ -2,6 +2,7 @@ import static org.junit.jupiter.api.Assertions.assertEquals; import static org.junit.jupiter.api.Assertions.assertFalse; +import static org.junit.jupiter.api.Assertions.assertTrue; import static org.junit.jupiter.api.Assertions.fail; import io.grpc.stub.StreamObserver; @@ -9,6 +10,7 @@ import java.time.Instant; import java.util.List; import java.util.Map; +import java.util.concurrent.atomic.AtomicBoolean; import java.util.concurrent.atomic.AtomicReference; import net.firedevops.firemud.common.gameplay.GameplayCatalogProperties; import net.firedevops.firemud.common.security.SessionContext; @@ -18,13 +20,18 @@ import net.firedevops.firemud.gamesession.dto.CommandEnqueueResult; import net.firedevops.firemud.gamesession.dto.GameInstanceDto; import net.firedevops.firemud.gamesession.entity.GameInstance; +import net.firedevops.firemud.gamesession.entity.GameplayAdmissionPointer; +import net.firedevops.firemud.gamesession.entity.GameplayAdmissionPointerEvent; import net.firedevops.firemud.gamesession.repository.GameInstanceRepository; +import net.firedevops.firemud.gamesession.repository.GameplayAdmissionPointerEventRepository; +import net.firedevops.firemud.gamesession.repository.GameplayAdmissionPointerRepository; import net.firedevops.firemud.gamesession.service.AccountPresenceQueryService; import net.firedevops.firemud.gamesession.service.AccountPresenceSnapshot; import net.firedevops.firemud.gamesession.service.AccountRecentPresenceDisposition; import net.firedevops.firemud.gamesession.service.FeatureFlagService; import net.firedevops.firemud.gamesession.service.GameInstanceService; import net.firedevops.firemud.gamesession.service.GameplayAdmissionPointerAuthorityService; +import net.firedevops.firemud.gamesession.service.GameplayAdmissionPointerMutation; import net.firedevops.firemud.gamesession.service.GameplayAdmissionPointerSnapshot; import net.firedevops.firemud.gamesession.service.IpConnectionLimiter; import net.firedevops.firemud.gamesession.service.PingService; @@ -36,6 +43,8 @@ import net.firedevops.firemud.gamesession.v1.GetTickStatusResponse; import net.firedevops.firemud.gamesession.v1.ListGameplayRealmsRequest; import net.firedevops.firemud.gamesession.v1.ListGameplayRealmsResponse; +import net.firedevops.firemud.gamesession.v1.ListGameplayWorldsRequest; +import net.firedevops.firemud.gamesession.v1.ListGameplayWorldsResponse; import net.firedevops.firemud.gamesession.v1.PauseTicksRequest; import net.firedevops.firemud.gamesession.v1.PauseTicksResponse; import net.firedevops.firemud.gamesession.v1.PingRequest; @@ -141,6 +150,51 @@ private static GameSessionGrpcService newService( ipConnectionLimiter); } + private static GameSessionGrpcService catalogService( + GameplayAdmissionPointerAuthorityService pointerAuthorityService) { + return newService( + Mockito.mock(PingService.class), + Mockito.mock(GameInstanceService.class), + Mockito.mock(FeatureFlagService.class), + Mockito.mock(TextCommandInterpreter.class), + Mockito.mock(GameInstanceRepository.class), + pointerAuthorityService, + new GameplayWorldCatalog(pointerAuthorityService), + Mockito.mock(TickService.class), + new SimpleMeterRegistry(), + Mockito.mock(IpConnectionLimiter.class)); + } + + private static GameplayAdmissionPointerSnapshot authorityPointer( + String worldSlug, + String realmSlug, + long tenantId, + long gameInstanceId, + boolean visible, + boolean publicProductionRealm) { + java.util.UUID realmId = + java.util.UUID.nameUUIDFromBytes( + ("realm/" + tenantId + "/" + worldSlug + "/" + realmSlug) + .getBytes(java.nio.charset.StandardCharsets.UTF_8)); + return new GameplayAdmissionPointerSnapshot( + worldSlug, + worldSlug + " World", + realmSlug, + realmSlug + " Realm", + tenantId, + gameInstanceId, + 1L, + visible, + publicProductionRealm, + false, + "SHARED", + "ALLOW_NEW", + 1L, + realmId, + java.util.UUID.nameUUIDFromBytes( + ("namespace/" + realmId).getBytes(java.nio.charset.StandardCharsets.UTF_8))); + } + @Test void pingReturnsPong() { PingService pingService = Mockito.mock(PingService.class); @@ -428,6 +482,329 @@ public void onCompleted() {} Mockito.verifyNoInteractions(accountPresenceQueryService); } + @Test + void listGameplayWorldsBuildsVisibleWorldsFromOneAuthoritySnapshot() { + GameplayAdmissionPointerAuthorityService pointerAuthorityService = + Mockito.mock(GameplayAdmissionPointerAuthorityService.class); + GameplayAdmissionPointerSnapshot firstSnapshot = + new GameplayAdmissionPointerSnapshot( + "demo", + "Demo World", + "production", + "Live Realm", + 7L, + 44L, + 17L, + true, + true, + false, + "SHARED", + "ALLOW_NEW", + 29L, + java.util.UUID.fromString("8a1df0f1-1b57-465e-9c4b-bb34f8153d31"), + java.util.UUID.fromString("2ea958e0-13a2-41d0-9c39-59a96cf31412")); + GameplayAdmissionPointerSnapshot secondSnapshot = + new GameplayAdmissionPointerSnapshot( + "other", + "Other World", + "production", + "Other Realm", + 7L, + 55L, + 3L, + false, + false, + false, + "ISOLATED", + "ALLOW_NEW", + 4L, + java.util.UUID.fromString("c0a801a0-7e42-4cc8-9e18-0c0b20d4e6f9"), + java.util.UUID.fromString("e94d4b9d-7635-4d7f-b70c-12f4e3ea8e27")); + Mockito.when(pointerAuthorityService.listPointers()) + .thenReturn(List.of(firstSnapshot, secondSnapshot)); + GameSessionGrpcService service = + newService( + Mockito.mock(PingService.class), + Mockito.mock(GameInstanceService.class), + Mockito.mock(FeatureFlagService.class), + Mockito.mock(TextCommandInterpreter.class), + Mockito.mock(GameInstanceRepository.class), + pointerAuthorityService, + new GameplayWorldCatalog(pointerAuthorityService), + Mockito.mock(TickService.class), + new SimpleMeterRegistry(), + Mockito.mock(IpConnectionLimiter.class)); + + ListGameplayWorldsResponse response = listGameplayWorlds(service); + + assertFalse(response.hasError()); + assertEquals(1, response.getWorldsCount()); + assertEquals("demo", response.getWorlds(0).getWorldSlug()); + assertEquals("Demo World", response.getWorlds(0).getDisplayName()); + Mockito.verify(pointerAuthorityService, Mockito.times(1)).listPointers(); + } + + @Test + void listGameplayWorldsAllowsAnEmptyAuthorityStore() { + GameplayAdmissionPointerAuthorityService pointerAuthorityService = + Mockito.mock(GameplayAdmissionPointerAuthorityService.class); + Mockito.when(pointerAuthorityService.listPointers()).thenReturn(List.of()); + GameSessionGrpcService service = + newService( + Mockito.mock(PingService.class), + Mockito.mock(GameInstanceService.class), + Mockito.mock(FeatureFlagService.class), + Mockito.mock(TextCommandInterpreter.class), + Mockito.mock(GameInstanceRepository.class), + pointerAuthorityService, + new GameplayWorldCatalog(pointerAuthorityService), + Mockito.mock(TickService.class), + new SimpleMeterRegistry(), + Mockito.mock(IpConnectionLimiter.class)); + + ListGameplayWorldsResponse response = listGameplayWorlds(service); + + assertFalse(response.hasError()); + assertEquals(0, response.getWorldsCount()); + Mockito.verify(pointerAuthorityService).listPointers(); + } + + @Test + void listGameplayWorldsRejectsAnIncompleteAuthorityPointer() { + GameplayAdmissionPointerAuthorityService pointerAuthorityService = + Mockito.mock(GameplayAdmissionPointerAuthorityService.class); + GameplayAdmissionPointerSnapshot incompleteSnapshot = + new GameplayAdmissionPointerSnapshot( + "demo", + "Demo World", + "production", + "Live Realm", + 7L, + 44L, + 17L, + true, + true, + false, + "SHARED", + "ALLOW_NEW", + 0L); + Mockito.when(pointerAuthorityService.listPointers()).thenReturn(List.of(incompleteSnapshot)); + GameSessionGrpcService service = + newService( + Mockito.mock(PingService.class), + Mockito.mock(GameInstanceService.class), + Mockito.mock(FeatureFlagService.class), + Mockito.mock(TextCommandInterpreter.class), + Mockito.mock(GameInstanceRepository.class), + pointerAuthorityService, + new GameplayWorldCatalog(pointerAuthorityService), + Mockito.mock(TickService.class), + new SimpleMeterRegistry(), + Mockito.mock(IpConnectionLimiter.class)); + + ListGameplayWorldsResponse response = listGameplayWorlds(service); + + assertEquals("ADMISSION_POINTER_UNAVAILABLE", response.getError().getCode()); + assertEquals(0, response.getWorldsCount()); + Mockito.verify(pointerAuthorityService).listPointers(); + } + + @Test + void listGameplayWorldsReturnsInternalForUnexpectedAuthorityFailureAndCompletesObserver() { + GameplayAdmissionPointerAuthorityService pointerAuthorityService = + Mockito.mock(GameplayAdmissionPointerAuthorityService.class); + Mockito.when(pointerAuthorityService.listPointers()) + .thenThrow(new IllegalStateException("unexpected authority dependency failure")); + SimpleMeterRegistry meterRegistry = new SimpleMeterRegistry(); + GameSessionGrpcService service = + newService( + Mockito.mock(PingService.class), + Mockito.mock(GameInstanceService.class), + Mockito.mock(FeatureFlagService.class), + Mockito.mock(TextCommandInterpreter.class), + Mockito.mock(GameInstanceRepository.class), + pointerAuthorityService, + new GameplayWorldCatalog(pointerAuthorityService), + Mockito.mock(TickService.class), + meterRegistry, + Mockito.mock(IpConnectionLimiter.class)); + AtomicReference response = new AtomicReference<>(); + AtomicBoolean completed = new AtomicBoolean(); + + service.listGameplayWorlds( + ListGameplayWorldsRequest.getDefaultInstance(), + new StreamObserver<>() { + @Override + public void onNext(ListGameplayWorldsResponse value) { + response.set(value); + } + + @Override + public void onError(Throwable t) { + fail(t); + } + + @Override + public void onCompleted() { + completed.set(true); + } + }); + + assertEquals("INTERNAL", response.get().getError().getCode()); + assertEquals(1.0, meterRegistry.counter("grpc.app_error", "code", "INTERNAL").count(), 0.0); + assertTrue(completed.get()); + Mockito.verify(pointerAuthorityService).listPointers(); + } + + @Test + void gameplayDiscoveryRejectsPublicRealmsAcrossDifferentWorldsForOneTenant() { + GameplayAdmissionPointerAuthorityService pointerAuthorityService = + Mockito.mock(GameplayAdmissionPointerAuthorityService.class); + Mockito.when(pointerAuthorityService.listPointers()) + .thenReturn( + List.of( + authorityPointer("alpha", "live", 7L, 44L, true, true), + authorityPointer("beta", "live", 7L, 55L, true, true))); + GameSessionGrpcService service = catalogService(pointerAuthorityService); + + ListGameplayWorldsResponse worlds = listGameplayWorlds(service); + ListGameplayRealmsResponse realms = listGameplayRealms(service, "alpha"); + + assertEquals("ADMISSION_POINTER_UNAVAILABLE", worlds.getError().getCode()); + assertEquals(0, worlds.getWorldsCount()); + assertEquals("ADMISSION_POINTER_UNAVAILABLE", realms.getError().getCode()); + assertEquals(0, realms.getRealmsCount()); + Mockito.verify(pointerAuthorityService, Mockito.times(2)).listPointers(); + } + + @Test + void publicAdmissionRejectsNonUniqueTenantGlobalPublicRealm() { + GameplayAdmissionPointerAuthorityService pointerAuthorityService = + Mockito.mock(GameplayAdmissionPointerAuthorityService.class); + GameplayAdmissionPointerSnapshot selectedPublicRealm = + authorityPointer("alpha", "live", 7L, 44L, true, true); + Mockito.when(pointerAuthorityService.findPointer(7L, "alpha", "live")) + .thenReturn(java.util.Optional.of(selectedPublicRealm)); + Mockito.when(pointerAuthorityService.listPointers()) + .thenReturn( + List.of(selectedPublicRealm, authorityPointer("beta", "live", 7L, 55L, true, true))); + GameSessionGrpcService service = catalogService(pointerAuthorityService); + AtomicReference response = new AtomicReference<>(); + + service.getAdmissionPointer( + GetAdmissionPointerRequest.newBuilder() + .setTenantId("7") + .setWorldSlug("alpha") + .setRealmSlug("live") + .build(), + new StreamObserver<>() { + @Override + public void onNext(GetAdmissionPointerResponse value) { + response.set(value); + } + + @Override + public void onError(Throwable t) { + fail(t); + } + + @Override + public void onCompleted() {} + }); + + assertEquals("ADMISSION_POINTER_UNAVAILABLE", response.get().getError().getCode()); + assertFalse(response.get().hasAdmissionPointer()); + Mockito.verify(pointerAuthorityService).listPointers(); + } + + @Test + void privateAdmissionDoesNotRequirePublicRealmCardinalityLookup() { + GameplayAdmissionPointerAuthorityService pointerAuthorityService = + Mockito.mock(GameplayAdmissionPointerAuthorityService.class); + GameplayAdmissionPointerSnapshot privateRealm = + authorityPointer("private", "preview", 7L, 66L, true, false); + Mockito.when(pointerAuthorityService.findPointer(7L, "private", "preview")) + .thenReturn(java.util.Optional.of(privateRealm)); + Mockito.when(pointerAuthorityService.listPointers()) + .thenReturn( + List.of( + authorityPointer("alpha", "live", 7L, 44L, true, true), + authorityPointer("beta", "live", 7L, 55L, true, true))); + GameSessionGrpcService service = catalogService(pointerAuthorityService); + AtomicReference response = new AtomicReference<>(); + + service.getAdmissionPointer( + GetAdmissionPointerRequest.newBuilder() + .setTenantId("7") + .setWorldSlug("private") + .setRealmSlug("preview") + .build(), + new StreamObserver<>() { + @Override + public void onNext(GetAdmissionPointerResponse value) { + response.set(value); + } + + @Override + public void onError(Throwable t) { + fail(t); + } + + @Override + public void onCompleted() {} + }); + + assertFalse(response.get().hasError()); + assertEquals("66", response.get().getAdmissionPointer().getGameInstanceId()); + Mockito.verify(pointerAuthorityService, Mockito.never()).listPointers(); + } + + @Test + void getAdmissionPointerReturnsHiddenMetadataWithoutPublicCardinalityAuthorization() { + GameplayAdmissionPointerAuthorityService pointerAuthorityService = + Mockito.mock(GameplayAdmissionPointerAuthorityService.class); + GameplayAdmissionPointerSnapshot hiddenRealm = + authorityPointer("private", "preview", 7L, 66L, false, true); + Mockito.when(pointerAuthorityService.findPointer(7L, "private", "preview")) + .thenReturn(java.util.Optional.of(hiddenRealm)); + GameSessionGrpcService service = catalogService(pointerAuthorityService); + AtomicReference response = new AtomicReference<>(); + + service.getAdmissionPointer( + GetAdmissionPointerRequest.newBuilder() + .setTenantId("7") + .setWorldSlug("private") + .setRealmSlug("preview") + .build(), + new StreamObserver<>() { + @Override + public void onNext(GetAdmissionPointerResponse value) { + response.set(value); + } + + @Override + public void onError(Throwable t) { + fail(t); + } + + @Override + public void onCompleted() {} + }); + + assertFalse(response.get().hasError()); + assertFalse(response.get().getAdmissionPointer().getVisible()); + assertEquals(true, response.get().getAdmissionPointer().getPublicProductionRealm()); + assertEquals( + hiddenRealm.catalogRevision(), response.get().getAdmissionPointer().getCatalogRevision()); + assertEquals( + hiddenRealm.realmId().toString(), response.get().getAdmissionPointer().getRealmId()); + assertEquals( + hiddenRealm.playableStateNamespaceId().toString(), + response.get().getAdmissionPointer().getPlayableStateNamespaceId()); + Mockito.verify(pointerAuthorityService).findPointer(7L, "private", "preview"); + Mockito.verify(pointerAuthorityService, Mockito.never()).listPointers(); + } + @Test void gameplayCatalogRpcReturnsCanonicalRealmData() { PingService pingService = Mockito.mock(PingService.class); @@ -440,36 +817,26 @@ void gameplayCatalogRpcReturnsCanonicalRealmData() { GameplayAdmissionPointerAuthorityService pointerAuthorityService = Mockito.mock(GameplayAdmissionPointerAuthorityService.class); SimpleMeterRegistry meterRegistry = new SimpleMeterRegistry(); - GameplayCatalogProperties properties = new GameplayCatalogProperties(); - GameplayCatalogProperties.World world = new GameplayCatalogProperties.World(); - world.setSlug("demo"); - world.setDisplayName("Demo World"); - GameplayCatalogProperties.Realm realm = new GameplayCatalogProperties.Realm(); - realm.setSlug("production"); - realm.setDisplayName("Live Realm"); - realm.setTenantId(7L); - realm.setGameInstanceId(999L); - realm.setPointerVersion(999L); - realm.setStateScope(GameplayCatalogProperties.RealmStateScope.ISOLATED); - realm.setCharacterCreationPolicy(GameplayCatalogProperties.CharacterCreationPolicy.COPIED_ONLY); - world.setRealms(List.of(realm)); - properties.setWorlds(List.of(world)); + GameplayAdmissionPointerSnapshot authoritativeSnapshot = + new GameplayAdmissionPointerSnapshot( + "demo", + "Demo World", + "production", + "Live Realm", + 7L, + 44L, + 17L, + true, + true, + false, + "ISOLATED", + "COPIED_ONLY", + 29L, + java.util.UUID.fromString("8a1df0f1-1b57-465e-9c4b-bb34f8153d31"), + java.util.UUID.fromString("2ea958e0-13a2-41d0-9c39-59a96cf31412")); + Mockito.when(pointerAuthorityService.listPointers()).thenReturn(List.of(authoritativeSnapshot)); Mockito.when(pointerAuthorityService.findPointer(7L, "demo", "production")) - .thenReturn( - java.util.Optional.of( - new GameplayAdmissionPointerSnapshot( - "demo", - "Demo World", - "production", - "Live Realm", - 7L, - 44L, - 17L, - true, - false, - false, - "ISOLATED", - "COPIED_ONLY"))); + .thenReturn(java.util.Optional.of(authoritativeSnapshot)); GameSessionGrpcService service = newService( pingService, @@ -478,7 +845,7 @@ void gameplayCatalogRpcReturnsCanonicalRealmData() { textCommandInterpreter, gameInstanceRepository, pointerAuthorityService, - TestGameplayWorldCatalogs.fromProperties(properties), + new GameplayWorldCatalog(pointerAuthorityService), tickService, meterRegistry, ipLimiter); @@ -504,6 +871,12 @@ public void onCompleted() {} assertEquals(1, realmsRef.get().getRealmsCount()); assertEquals("production", realmsRef.get().getRealms(0).getRealmSlug()); assertEquals("ISOLATED", realmsRef.get().getRealms(0).getStateScope()); + assertEquals(17L, realmsRef.get().getRealms(0).getPointerVersion()); + assertEquals(29L, realmsRef.get().getRealms(0).getCatalogRevision()); + assertEquals("8a1df0f1-1b57-465e-9c4b-bb34f8153d31", realmsRef.get().getRealms(0).getRealmId()); + assertEquals( + "2ea958e0-13a2-41d0-9c39-59a96cf31412", + realmsRef.get().getRealms(0).getPlayableStateNamespaceId()); AtomicReference pointerRef = new AtomicReference<>(); service.getAdmissionPointer( @@ -529,9 +902,337 @@ public void onCompleted() {} assertEquals("44", pointerRef.get().getAdmissionPointer().getGameInstanceId()); assertEquals(17L, pointerRef.get().getAdmissionPointer().getPointerVersion()); + assertEquals(29L, pointerRef.get().getAdmissionPointer().getCatalogRevision()); + assertEquals( + "8a1df0f1-1b57-465e-9c4b-bb34f8153d31", + pointerRef.get().getAdmissionPointer().getRealmId()); + assertEquals( + "2ea958e0-13a2-41d0-9c39-59a96cf31412", + pointerRef.get().getAdmissionPointer().getPlayableStateNamespaceId()); Mockito.verify(pointerAuthorityService).findPointer(7L, "demo", "production"); } + @Test + void missingCatalogRevisionFailsClosedForCatalogAndAdmissionPointerReads() { + PingService pingService = Mockito.mock(PingService.class); + GameInstanceService gameInstanceService = Mockito.mock(GameInstanceService.class); + FeatureFlagService featureFlagService = Mockito.mock(FeatureFlagService.class); + TextCommandInterpreter textCommandInterpreter = Mockito.mock(TextCommandInterpreter.class); + GameInstanceRepository gameInstanceRepository = Mockito.mock(GameInstanceRepository.class); + TickService tickService = Mockito.mock(TickService.class); + IpConnectionLimiter ipLimiter = Mockito.mock(IpConnectionLimiter.class); + GameplayAdmissionPointerAuthorityService pointerAuthorityService = + Mockito.mock(GameplayAdmissionPointerAuthorityService.class); + SimpleMeterRegistry meterRegistry = new SimpleMeterRegistry(); + GameplayAdmissionPointerSnapshot missingRevision = + new GameplayAdmissionPointerSnapshot( + "demo", + "Demo World", + "production", + "Live Realm", + 7L, + 44L, + 17L, + true, + true, + false, + "SHARED", + "ALLOW_NEW", + 0L); + Mockito.when(pointerAuthorityService.listPointers()).thenReturn(List.of(missingRevision)); + Mockito.when(pointerAuthorityService.findPointer(7L, "demo", "production")) + .thenReturn(java.util.Optional.of(missingRevision)); + GameSessionGrpcService service = + newService( + pingService, + gameInstanceService, + featureFlagService, + textCommandInterpreter, + gameInstanceRepository, + pointerAuthorityService, + new GameplayWorldCatalog(pointerAuthorityService), + tickService, + meterRegistry, + ipLimiter); + + AtomicReference realmsRef = new AtomicReference<>(); + service.listGameplayRealms( + ListGameplayRealmsRequest.newBuilder().setWorldSlug("demo").build(), + new StreamObserver<>() { + @Override + public void onNext(ListGameplayRealmsResponse value) { + realmsRef.set(value); + } + + @Override + public void onError(Throwable t) { + fail(t); + } + + @Override + public void onCompleted() {} + }); + + assertEquals("ADMISSION_POINTER_UNAVAILABLE", realmsRef.get().getError().getCode()); + assertEquals(0, realmsRef.get().getRealmsCount()); + + AtomicReference pointerRef = new AtomicReference<>(); + service.getAdmissionPointer( + GetAdmissionPointerRequest.newBuilder() + .setTenantId("7") + .setWorldSlug("demo") + .setRealmSlug("production") + .build(), + new StreamObserver<>() { + @Override + public void onNext(GetAdmissionPointerResponse value) { + pointerRef.set(value); + } + + @Override + public void onError(Throwable t) { + fail(t); + } + + @Override + public void onCompleted() {} + }); + + assertEquals("ADMISSION_POINTER_UNAVAILABLE", pointerRef.get().getError().getCode()); + assertFalse(pointerRef.get().hasAdmissionPointer()); + } + + private static ListGameplayRealmsResponse listGameplayRealms( + GameSessionGrpcService service, String worldSlug) { + AtomicReference response = new AtomicReference<>(); + service.listGameplayRealms( + ListGameplayRealmsRequest.newBuilder().setWorldSlug(worldSlug).build(), + new StreamObserver<>() { + @Override + public void onNext(ListGameplayRealmsResponse value) { + response.set(value); + } + + @Override + public void onError(Throwable t) { + fail(t); + } + + @Override + public void onCompleted() {} + }); + return response.get(); + } + + private static ListGameplayWorldsResponse listGameplayWorlds(GameSessionGrpcService service) { + AtomicReference response = new AtomicReference<>(); + service.listGameplayWorlds( + ListGameplayWorldsRequest.getDefaultInstance(), + new StreamObserver<>() { + @Override + public void onNext(ListGameplayWorldsResponse value) { + response.set(value); + } + + @Override + public void onError(Throwable t) { + fail(t); + } + + @Override + public void onCompleted() {} + }); + return response.get(); + } + + @Test + void missingStableRealmIdentityFailsClosedForCatalogReads() { + GameplayAdmissionPointerAuthorityService pointerAuthorityService = + Mockito.mock(GameplayAdmissionPointerAuthorityService.class); + GameplayAdmissionPointerSnapshot missingIdentity = + new GameplayAdmissionPointerSnapshot( + "demo", + "Demo World", + "production", + "Live Realm", + 7L, + 44L, + 17L, + true, + true, + false, + "SHARED", + "ALLOW_NEW", + 29L); + Mockito.when(pointerAuthorityService.listPointers()).thenReturn(List.of(missingIdentity)); + Mockito.when(pointerAuthorityService.findPointer(7L, "demo", "production")) + .thenReturn(java.util.Optional.of(missingIdentity)); + GameSessionGrpcService service = + newService( + Mockito.mock(PingService.class), + Mockito.mock(GameInstanceService.class), + Mockito.mock(FeatureFlagService.class), + Mockito.mock(TextCommandInterpreter.class), + Mockito.mock(GameInstanceRepository.class), + pointerAuthorityService, + new GameplayWorldCatalog(pointerAuthorityService), + Mockito.mock(TickService.class), + new SimpleMeterRegistry(), + Mockito.mock(IpConnectionLimiter.class)); + + AtomicReference response = new AtomicReference<>(); + service.listGameplayRealms( + ListGameplayRealmsRequest.newBuilder().setWorldSlug("demo").build(), + new StreamObserver<>() { + @Override + public void onNext(ListGameplayRealmsResponse value) { + response.set(value); + } + + @Override + public void onError(Throwable t) { + fail(t); + } + + @Override + public void onCompleted() {} + }); + + assertEquals("ADMISSION_POINTER_UNAVAILABLE", response.get().getError().getCode()); + assertEquals(0, response.get().getRealmsCount()); + + AtomicReference pointerResponse = new AtomicReference<>(); + service.getAdmissionPointer( + GetAdmissionPointerRequest.newBuilder() + .setTenantId("7") + .setWorldSlug("demo") + .setRealmSlug("production") + .build(), + new StreamObserver<>() { + @Override + public void onNext(GetAdmissionPointerResponse value) { + pointerResponse.set(value); + } + + @Override + public void onError(Throwable t) { + fail(t); + } + + @Override + public void onCompleted() {} + }); + + assertEquals("ADMISSION_POINTER_UNAVAILABLE", pointerResponse.get().getError().getCode()); + assertFalse(pointerResponse.get().hasAdmissionPointer()); + } + + @Test + void listGameplayRealmsMapsUnexpectedDependencyFailureToInternalAndCompletes() { + GameplayAdmissionPointerAuthorityService pointerAuthorityService = + Mockito.mock(GameplayAdmissionPointerAuthorityService.class); + Mockito.when(pointerAuthorityService.listPointers()) + .thenThrow(new IllegalStateException("sensitive authority diagnostic")); + GameSessionGrpcService service = + newService( + Mockito.mock(PingService.class), + Mockito.mock(GameInstanceService.class), + Mockito.mock(FeatureFlagService.class), + Mockito.mock(TextCommandInterpreter.class), + Mockito.mock(GameInstanceRepository.class), + pointerAuthorityService, + new GameplayWorldCatalog(pointerAuthorityService), + Mockito.mock(TickService.class), + new SimpleMeterRegistry(), + Mockito.mock(IpConnectionLimiter.class)); + + AtomicReference response = new AtomicReference<>(); + AtomicBoolean completed = new AtomicBoolean(); + service.listGameplayRealms( + ListGameplayRealmsRequest.newBuilder().setWorldSlug("demo").build(), + new StreamObserver<>() { + @Override + public void onNext(ListGameplayRealmsResponse value) { + response.set(value); + } + + @Override + public void onError(Throwable t) { + fail(t); + } + + @Override + public void onCompleted() { + completed.set(true); + } + }); + + assertEquals("INTERNAL", response.get().getError().getCode()); + assertEquals("Internal error", response.get().getError().getMessage()); + assertTrue(completed.get()); + assertEquals(0, response.get().getRealmsCount()); + } + + @Test + void catalogPolicyRevisionAdvancesIndependentlyFromPointerVersion() { + GameplayAdmissionPointerRepository pointerRepository = + Mockito.mock(GameplayAdmissionPointerRepository.class); + GameplayAdmissionPointerEventRepository eventRepository = + Mockito.mock(GameplayAdmissionPointerEventRepository.class); + AtomicReference currentPointer = new AtomicReference<>(); + Mockito.when(pointerRepository.findByTenantIdAndWorldSlugAndRealmSlug(7L, "demo", "production")) + .thenAnswer(invocation -> java.util.Optional.ofNullable(currentPointer.get())); + Mockito.when(pointerRepository.save(Mockito.any(GameplayAdmissionPointer.class))) + .thenAnswer( + invocation -> { + GameplayAdmissionPointer pointer = invocation.getArgument(0); + if (pointer.getId() == null) { + pointer.setId(11L); + } + currentPointer.set(pointer); + return pointer; + }); + Mockito.when(eventRepository.save(Mockito.any(GameplayAdmissionPointerEvent.class))) + .thenAnswer(invocation -> invocation.getArgument(0)); + DatabaseGameplayAdmissionPointerAuthorityService authorityService = + new DatabaseGameplayAdmissionPointerAuthorityService(pointerRepository, eventRepository); + + GameplayAdmissionPointerSnapshot created = + authorityService.upsertPointer(pointerMutation(44L, true, 0L)); + GameplayAdmissionPointerSnapshot policyChanged = + authorityService.upsertPointer(pointerMutation(44L, false, 1L)); + GameplayAdmissionPointerSnapshot routeChanged = + authorityService.upsertPointer(pointerMutation(45L, false, 1L)); + + assertEquals(1L, created.catalogRevision()); + assertEquals(1L, created.pointerVersion()); + assertEquals(2L, policyChanged.catalogRevision()); + assertEquals(1L, policyChanged.pointerVersion()); + assertEquals(2L, routeChanged.catalogRevision()); + assertEquals(2L, routeChanged.pointerVersion()); + } + + private static GameplayAdmissionPointerMutation pointerMutation( + long gameInstanceId, boolean publicProductionRealm, Long expectedPointerVersion) { + return new GameplayAdmissionPointerMutation( + "demo", + "Demo World", + "production", + "Live Realm", + 7L, + gameInstanceId, + true, + publicProductionRealm, + false, + "SHARED", + "ALLOW_NEW", + "test", + "catalog revision test", + "catalog-revision-test-" + expectedPointerVersion, + expectedPointerVersion, + null); + } + @Test void getAdmissionPointerRuntimeFailureReturnsInternalErrorDetail() { PingService pingService = Mockito.mock(PingService.class); diff --git a/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/service/impl/GameSessionRuntimeControlPlaneReadServiceTest.java b/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/service/impl/GameSessionRuntimeControlPlaneReadServiceTest.java index d483bf55b7..89cf63c43b 100644 --- a/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/service/impl/GameSessionRuntimeControlPlaneReadServiceTest.java +++ b/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/service/impl/GameSessionRuntimeControlPlaneReadServiceTest.java @@ -8,7 +8,9 @@ import static org.mockito.Mockito.verify; import static org.mockito.Mockito.when; +import java.util.List; import java.util.Optional; +import java.util.UUID; import net.firedevops.firemud.gamedesign.v1.GetPublishedScriptPatchVersionResponse; import net.firedevops.firemud.gamedesign.v1.PublishedScriptPatchVersion; import net.firedevops.firemud.gamedesign.v1.VersionLifecycleState; @@ -21,6 +23,7 @@ import net.firedevops.firemud.gamesession.repository.RemoteFollowupRepository; import net.firedevops.firemud.gamesession.repository.RuntimeRegionStatusRepository; import net.firedevops.firemud.gamesession.service.GameplayAdmissionPointerAuthorityService; +import net.firedevops.firemud.gamesession.service.GameplayAdmissionPointerSnapshot; import net.firedevops.firemud.gamesession.v1.GetGameInstanceRuntimeStateRequest; import net.firedevops.firemud.shared.v1.ErrorDetail; import net.firedevops.firemud.worldmanagement.v1.GetWorldInstanceLifecycleResponse; @@ -66,6 +69,131 @@ void runtimeReadReturnsPersistedScriptPinEpoch() { assertEquals(9L, state.getScriptPinEpoch()); } + @Test + void runtimeReadMapsDurableAdmissionPointerIdentity() { + WorldManagementClient world = mock(WorldManagementClient.class); + when(world.getWorldInstanceLifecycle(1L, 7L)) + .thenReturn( + worldLifecycle( + 1L, 7L, 3L, WorldInstanceLifecycleStatus.WORLD_INSTANCE_LIFECYCLE_STATUS_ACTIVE)); + GameplayAdmissionPointerAuthorityService authority = + mock(GameplayAdmissionPointerAuthorityService.class); + when(authority.listByRuntimeTarget(1L, 7L)) + .thenReturn( + List.of( + new GameplayAdmissionPointerSnapshot( + "demo", + "Demo World", + "production", + "Production", + 1L, + 7L, + 11L, + true, + true, + true, + "SHARED", + "CREATE_ALLOWED", + 12L, + UUID.fromString("11111111-1111-1111-1111-111111111111"), + UUID.fromString("22222222-2222-2222-2222-222222222222")))); + GameSessionRuntimeControlPlaneReadService service = + service(world, "RUNNING", null, null, null, null, authority); + + var state = service.getGameInstanceRuntimeState(1L, runtimeRequest()); + + assertEquals(12L, state.getCurrentAdmissionPointers(0).getCatalogRevision()); + assertEquals( + "11111111-1111-1111-1111-111111111111", state.getCurrentAdmissionPointers(0).getRealmId()); + assertEquals( + "22222222-2222-2222-2222-222222222222", + state.getCurrentAdmissionPointers(0).getPlayableStateNamespaceId()); + } + + @Test + void runtimeReadFailsClosedWhenAdmissionPointerIdentityIsMissing() { + WorldManagementClient world = mock(WorldManagementClient.class); + when(world.getWorldInstanceLifecycle(1L, 7L)) + .thenReturn( + worldLifecycle( + 1L, 7L, 3L, WorldInstanceLifecycleStatus.WORLD_INSTANCE_LIFECYCLE_STATUS_ACTIVE)); + GameplayAdmissionPointerAuthorityService authority = + mock(GameplayAdmissionPointerAuthorityService.class); + when(authority.listByRuntimeTarget(1L, 7L)) + .thenReturn( + List.of( + new GameplayAdmissionPointerSnapshot( + "demo", + "Demo World", + "production", + "Production", + 1L, + 7L, + 11L, + true, + true, + true, + "SHARED", + "CREATE_ALLOWED", + 12L, + UUID.fromString("11111111-1111-1111-1111-111111111111"), + null))); + GameSessionRuntimeControlPlaneReadService service = + service(world, "RUNNING", null, null, null, null, authority); + + GameSessionRuntimeControlPlaneReadService.RuntimeStateException error = + assertThrows( + GameSessionRuntimeControlPlaneReadService.RuntimeStateException.class, + () -> service.getGameInstanceRuntimeState(1L, runtimeRequest())); + + assertEquals("ADMISSION_POINTER_AUTHORITY_UNAVAILABLE", error.code()); + assertEquals( + "ADMISSION_POINTER_AUTHORITY_UNAVAILABLE: current admission pointer durable identity or catalog revision is unavailable", + error.getMessage()); + } + + @Test + void runtimeReadFailsClosedWhenAdmissionPointerCatalogRevisionIsMissing() { + WorldManagementClient world = mock(WorldManagementClient.class); + when(world.getWorldInstanceLifecycle(1L, 7L)) + .thenReturn( + worldLifecycle( + 1L, 7L, 3L, WorldInstanceLifecycleStatus.WORLD_INSTANCE_LIFECYCLE_STATUS_ACTIVE)); + GameplayAdmissionPointerAuthorityService authority = + mock(GameplayAdmissionPointerAuthorityService.class); + when(authority.listByRuntimeTarget(1L, 7L)) + .thenReturn( + List.of( + new GameplayAdmissionPointerSnapshot( + "demo", + "Demo World", + "production", + "Production", + 1L, + 7L, + 11L, + true, + true, + true, + "SHARED", + "CREATE_ALLOWED", + 0L, + UUID.fromString("11111111-1111-1111-1111-111111111111"), + UUID.fromString("22222222-2222-2222-2222-222222222222")))); + GameSessionRuntimeControlPlaneReadService service = + service(world, "RUNNING", null, null, null, null, authority); + + GameSessionRuntimeControlPlaneReadService.RuntimeStateException error = + assertThrows( + GameSessionRuntimeControlPlaneReadService.RuntimeStateException.class, + () -> service.getGameInstanceRuntimeState(1L, runtimeRequest())); + + assertEquals("ADMISSION_POINTER_AUTHORITY_UNAVAILABLE", error.code()); + assertEquals( + "ADMISSION_POINTER_AUTHORITY_UNAVAILABLE: current admission pointer durable identity or catalog revision is unavailable", + error.getMessage()); + } + @Test void runtimeReadOmitsPublicationForUnpinnedInstanceWithoutCallingGameDesign() { WorldManagementClient world = mock(WorldManagementClient.class); @@ -462,6 +590,24 @@ private GameSessionRuntimeControlPlaneReadService service( Long scriptPinEpoch, Long scriptPatchBaseVersionId, GameDesignClient gameDesignClient) { + return service( + world, + status, + scriptPatchVersion, + scriptPinEpoch, + scriptPatchBaseVersionId, + gameDesignClient, + mock(GameplayAdmissionPointerAuthorityService.class)); + } + + private GameSessionRuntimeControlPlaneReadService service( + WorldManagementClient world, + String status, + String scriptPatchVersion, + Long scriptPinEpoch, + Long scriptPatchBaseVersionId, + GameDesignClient gameDesignClient, + GameplayAdmissionPointerAuthorityService authority) { GameInstance instance = new GameInstance(); instance.setId(7L); instance.setTenantId(1L); @@ -488,7 +634,7 @@ private GameSessionRuntimeControlPlaneReadService service( mock(GameplayCommandRepository.class), mock(RemoteFollowupRepository.class), runtime, - mock(GameplayAdmissionPointerAuthorityService.class), + authority, gameDesignClient, world); } diff --git a/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/service/impl/InitialAdmissionBindServiceTest.java b/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/service/impl/InitialAdmissionBindServiceTest.java new file mode 100644 index 0000000000..348c071737 --- /dev/null +++ b/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/service/impl/InitialAdmissionBindServiceTest.java @@ -0,0 +1,305 @@ +package net.firedevops.firemud.gamesession.service.impl; + +import static org.assertj.core.api.Assertions.assertThat; +import static org.assertj.core.api.Assertions.assertThatThrownBy; +import static org.mockito.Mockito.mock; +import static org.mockito.Mockito.when; + +import java.sql.Connection; +import java.util.Optional; +import java.util.UUID; +import java.util.function.Supplier; +import net.firedevops.firemud.gamesession.entity.GameInstance; +import net.firedevops.firemud.gamesession.entity.InitialAdmissionBindAttempt; +import net.firedevops.firemud.gamesession.repository.GameInstanceRepository; +import net.firedevops.firemud.gamesession.repository.GameplayAdmissionPointerEventRepository; +import net.firedevops.firemud.gamesession.repository.InitialAdmissionBindAttemptRepository; +import net.firedevops.firemud.gamesession.repository.InitialAdmissionBindCatalogRepository; +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.InitialAdmissionBindRequest; +import org.jooq.DSLContext; +import org.jooq.SQLDialect; +import org.jooq.impl.DSL; +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.support.TransactionTemplate; + +class InitialAdmissionBindServiceTest { + @Test + void persistsStableCatalogAndIntentThenCommitsMatchingPointerAuditAndLedger() throws Exception { + Harness harness = newHarness("initial-bind-commit"); + when(harness.gameInstanceRepository.findByTenantIdAndGameInstanceIdForUpdate(17L, 93L)) + .thenReturn(Optional.of(gameInstance(17L, 93L, 700L, 44L))); + + InitialAdmissionBindCatalogDescriptor descriptor = descriptor(); + var firstCatalog = + tx(harness, () -> harness.service.registerPublicSharedFixtureCatalog(descriptor)); + var exactCatalogRetry = + tx(harness, () -> harness.service.registerPublicSharedFixtureCatalog(descriptor)); + assertThat(exactCatalogRetry.realmId()).isEqualTo(firstCatalog.realmId()); + assertThat(exactCatalogRetry.playableStateNamespaceId()) + .isEqualTo(firstCatalog.playableStateNamespaceId()); + assertThat(exactCatalogRetry.catalogRevision()).isEqualTo(1L); + assertThat(harness.dsl.fetchCount(DSL.table("gameplay_admission_pointer"))).isZero(); + + InitialAdmissionBindRequest request = + new InitialAdmissionBindRequest( + 17L, "demo", "production", "bind-17-93", digest(), 93L, 44L, 8L); + InitialAdmissionBindAttempt intent = tx(harness, () -> harness.service.beginIntent(request)); + assertThat(intent.status()).isEqualTo(InitialAdmissionBindAttempt.Status.PENDING); + assertThat(intent.holdId()).isNull(); + assertThat(tx(harness, () -> harness.service.beginIntent(request))) + .usingRecursiveComparison() + .isEqualTo(intent); + assertThatThrownBy( + () -> + tx( + harness, + () -> + harness.service.beginIntent( + new InitialAdmissionBindRequest( + 17L, + "demo", + "production", + "bind-17-93", + "b".repeat(64), + 93L, + 44L, + 8L)))) + .isInstanceOf(IllegalArgumentException.class) + .hasMessageContaining("IDEMPOTENCY_CONFLICT"); + + InitialAdmissionBindHoldBinding binding = + binding(firstCatalog.realmId(), firstCatalog.playableStateNamespaceId(), "bind-17-93"); + InitialAdmissionBindOwnerProof beforeHold = tx(harness, () -> harness.service.read(binding)); + assertThat(beforeHold.outcome()).isEqualTo(InitialAdmissionBindOwnerProof.Outcome.PENDING); + assertThat(beforeHold.ownerProofId()).isEqualTo(intent.attemptId().toString()); + + tx(harness, () -> harness.service.attachHold(binding)); + InitialAdmissionBindOwnerProof committed = tx(harness, () -> harness.service.commit(binding)); + assertThat(committed.outcome()).isEqualTo(InitialAdmissionBindOwnerProof.Outcome.COMMITTED); + assertThat(committed.ownerProofId()).isEqualTo(intent.attemptId().toString()); + assertThat(committed.pointerVersion()).isEqualTo(1L); + assertThat(committed.pointerAuditId()).isNotBlank(); + assertThat(committed.pointerAuditRequestDigest()).isEqualTo(digest()); + assertThat(tx(harness, () -> harness.service.commit(binding))).isEqualTo(committed); + assertThat(harness.dsl.fetchCount(DSL.table("gameplay_admission_pointer"))).isEqualTo(1); + assertThat(harness.dsl.fetchCount(DSL.table("gameplay_admission_pointer_event"))).isEqualTo(1); + + harness.dsl.execute( + "UPDATE gameplay_admission_pointer_event SET catalog_revision = NULL WHERE id = ?", + Long.parseLong(committed.pointerAuditId())); + assertThat(tx(harness, () -> harness.service.read(binding)).outcome()) + .isEqualTo(InitialAdmissionBindOwnerProof.Outcome.ERROR); + } + + @Test + void abortedAttemptIsDurableAndADelayedCommitCannotTurnItIntoPointer() throws Exception { + Harness harness = newHarness("initial-bind-abort"); + when(harness.gameInstanceRepository.findByTenantIdAndGameInstanceIdForUpdate(17L, 93L)) + .thenReturn(Optional.of(gameInstance(17L, 93L, 700L, 44L))); + var catalog = + tx(harness, () -> harness.service.registerPublicSharedFixtureCatalog(descriptor())); + InitialAdmissionBindRequest request = + new InitialAdmissionBindRequest( + 17L, "demo", "production", "bind-abort-93", digest(), 93L, 44L, 8L); + InitialAdmissionBindAttempt intent = tx(harness, () -> harness.service.beginIntent(request)); + InitialAdmissionBindHoldBinding binding = + binding(catalog.realmId(), catalog.playableStateNamespaceId(), "bind-abort-93"); + + InitialAdmissionBindOwnerProof aborted = tx(harness, () -> harness.service.abort(binding)); + assertThat(aborted.outcome()).isEqualTo(InitialAdmissionBindOwnerProof.Outcome.ABORTED); + assertThat(aborted.ownerProofId()).isEqualTo(intent.attemptId().toString()); + assertThat(aborted.futureCommitPrevented()).isTrue(); + assertThat(aborted.pointerAuditId()).isNull(); + assertThat(aborted.pointerVersion()).isZero(); + + InitialAdmissionBindOwnerProof delayedCommit = + tx(harness, () -> harness.service.commit(binding)); + assertThat(delayedCommit.outcome()).isEqualTo(InitialAdmissionBindOwnerProof.Outcome.ABORTED); + assertThat(harness.dsl.fetchCount(DSL.table("gameplay_admission_pointer"))).isZero(); + assertThat(harness.dsl.fetchCount(DSL.table("gameplay_admission_pointer_event"))).isZero(); + assertThatThrownBy( + () -> + tx( + harness, + () -> + harness.service.attachHold( + new InitialAdmissionBindHoldBinding( + UUID.randomUUID().toString(), + UUID.randomUUID().toString(), + binding.tenantId(), + binding.realmUuid(), + binding.playableStateNamespaceUuid(), + binding.playableStateScope(), + binding.gameInstanceId(), + binding.versionId(), + binding.activeLifecycleEpoch(), + binding.initialAdmissionRequestId(), + binding.requestDigest(), + true, + binding.expectedCatalogRevision())))) + .isInstanceOf(IllegalArgumentException.class) + .hasMessageContaining("IDEMPOTENCY_CONFLICT"); + } + + @Test + void exactCatalogRetryReusesIdsButChangedFixtureMetadataConflicts() throws Exception { + Harness harness = newHarness("initial-bind-catalog"); + var catalog = + tx(harness, () -> harness.service.registerPublicSharedFixtureCatalog(descriptor())); + + assertThatThrownBy( + () -> + tx( + harness, + () -> + harness.service.registerPublicSharedFixtureCatalog( + new InitialAdmissionBindCatalogDescriptor( + 17L, + 700L, + "demo", + "Changed Demo Name", + "production", + "Production Realm", + true)))) + .isInstanceOf(IllegalArgumentException.class) + .hasMessageContaining("IDEMPOTENCY_CONFLICT"); + assertThat(harness.catalogRepository.findByTenantId(17L).orElseThrow().realmId()) + .isEqualTo(catalog.realmId()); + assertThat(harness.dsl.fetchCount(DSL.table("gameplay_admission_pointer"))).isZero(); + } + + private static Harness newHarness(String databaseName) throws Exception { + DriverManagerDataSource setupDataSource = new DriverManagerDataSource(); + setupDataSource.setDriverClassName("org.h2.Driver"); + setupDataSource.setUrl( + "jdbc:h2:mem:" + + databaseName + + "-" + + System.nanoTime() + + ";MODE=PostgreSQL;DATABASE_TO_LOWER=TRUE;DB_CLOSE_DELAY=-1"); + try (Connection connection = setupDataSource.getConnection()) { + createSchema(DSL.using(connection, SQLDialect.H2)); + } + DSLContext dsl = DSL.using(new TransactionAwareDataSourceProxy(setupDataSource), SQLDialect.H2); + GameInstanceRepository gameInstanceRepository = mock(GameInstanceRepository.class); + InitialAdmissionBindCatalogRepository catalogRepository = + new InitialAdmissionBindCatalogRepository(dsl); + InitialAdmissionBindAttemptRepository attemptRepository = + new InitialAdmissionBindAttemptRepository(dsl); + DatabaseInitialAdmissionBindOwnerService service = + new DatabaseInitialAdmissionBindOwnerService( + catalogRepository, + attemptRepository, + new GameplayAdmissionPointerEventRepository(dsl), + gameInstanceRepository); + return new Harness( + dsl, + new TransactionTemplate(new DataSourceTransactionManager(setupDataSource)), + catalogRepository, + gameInstanceRepository, + service); + } + + private static void createSchema(DSLContext dsl) { + dsl.execute( + "CREATE TABLE gameplay_tenant_shared_playable_state_namespace (" + + "tenant_id BIGINT PRIMARY KEY, playable_state_namespace_id UUID NOT NULL UNIQUE, " + + "allocated_at TIMESTAMP NOT NULL DEFAULT CURRENT_TIMESTAMP)"); + dsl.execute( + "CREATE TABLE gameplay_initial_admission_bind_catalog (" + + "realm_id UUID PRIMARY KEY, tenant_id BIGINT NOT NULL, game_template_id BIGINT NOT NULL, " + + "world_slug VARCHAR(120) NOT NULL, world_display_name VARCHAR(200) NOT NULL, " + + "realm_slug VARCHAR(120) NOT NULL, realm_display_name VARCHAR(200) NOT NULL, " + + "catalog_revision BIGINT NOT NULL DEFAULT 1, playable_state_namespace_id UUID NOT NULL, " + + "visible BOOLEAN NOT NULL DEFAULT TRUE, public_production_realm BOOLEAN NOT NULL DEFAULT TRUE, " + + "requires_character_selection BOOLEAN NOT NULL, state_scope VARCHAR(32) NOT NULL DEFAULT 'SHARED', " + + "character_creation_policy VARCHAR(32) NOT NULL DEFAULT 'ALLOW_NEW', " + + "created_at TIMESTAMP NOT NULL DEFAULT CURRENT_TIMESTAMP, UNIQUE (tenant_id))"); + dsl.execute( + "CREATE TABLE gameplay_initial_admission_bind_attempt (" + + "attempt_id UUID PRIMARY KEY, tenant_id BIGINT NOT NULL, " + + "initial_admission_request_id VARCHAR(128) NOT NULL, request_digest VARCHAR(64) NOT NULL, " + + "realm_id UUID NOT NULL, playable_state_namespace_id UUID NOT NULL, " + + "playable_state_scope VARCHAR(32) NOT NULL, expected_no_prior_pointer BOOLEAN NOT NULL, " + + "catalog_revision BIGINT NOT NULL, game_instance_id BIGINT NOT NULL, version_id BIGINT NOT NULL, " + + "active_lifecycle_epoch BIGINT NOT NULL, hold_id UUID, hold_fence UUID, status VARCHAR(16) NOT NULL, " + + "pointer_id BIGINT, audit_event_id BIGINT, created_at TIMESTAMP NOT NULL, " + + "updated_at TIMESTAMP NOT NULL, terminal_at TIMESTAMP, UNIQUE (tenant_id, initial_admission_request_id))"); + dsl.execute( + "CREATE TABLE gameplay_admission_pointer (" + + "id BIGINT GENERATED BY DEFAULT AS IDENTITY PRIMARY KEY, world_slug VARCHAR(120) NOT NULL, " + + "world_display_name VARCHAR(200) NOT NULL, realm_slug VARCHAR(120) NOT NULL, " + + "realm_display_name VARCHAR(200) NOT NULL, tenant_id BIGINT NOT NULL, game_instance_id BIGINT NOT NULL, " + + "pointer_version BIGINT NOT NULL, catalog_revision BIGINT NOT NULL, realm_id UUID, " + + "playable_state_namespace_id UUID, visible BOOLEAN NOT NULL, public_production_realm BOOLEAN NOT NULL, " + + "requires_character_selection BOOLEAN NOT NULL, state_scope VARCHAR(32) NOT NULL, " + + "character_creation_policy VARCHAR(32) NOT NULL, last_updated_by VARCHAR(200) NOT NULL, " + + "last_update_reason VARCHAR(500) NOT NULL, created_at TIMESTAMP NOT NULL, updated_at TIMESTAMP NOT NULL, " + + "UNIQUE (tenant_id, world_slug, realm_slug), UNIQUE (tenant_id, game_instance_id))"); + dsl.execute( + "CREATE TABLE gameplay_admission_pointer_event (" + + "id BIGINT GENERATED BY DEFAULT AS IDENTITY PRIMARY KEY, world_slug VARCHAR(120) NOT NULL, " + + "realm_slug VARCHAR(120) NOT NULL, world_display_name VARCHAR(200) NOT NULL, " + + "realm_display_name VARCHAR(200) NOT NULL, tenant_id BIGINT NOT NULL, game_instance_id BIGINT NOT NULL, " + + "pointer_version BIGINT NOT NULL, catalog_revision BIGINT, realm_id UUID, " + + "playable_state_namespace_id UUID, visible BOOLEAN NOT NULL, public_production_realm BOOLEAN NOT NULL, " + + "requires_character_selection BOOLEAN NOT NULL, state_scope VARCHAR(32) NOT NULL, " + + "character_creation_policy VARCHAR(32) NOT NULL, actor_principal VARCHAR(200) NOT NULL, " + + "reason VARCHAR(500) NOT NULL, control_plane_request_id VARCHAR(128) NOT NULL, " + + "prepared_version_upgrade_id VARCHAR(64), occurred_at TIMESTAMP NOT NULL)"); + } + + private static T tx(Harness harness, Supplier action) { + return harness.transactionTemplate.execute(status -> action.get()); + } + + private static InitialAdmissionBindCatalogDescriptor descriptor() { + return new InitialAdmissionBindCatalogDescriptor( + 17L, 700L, "demo", "Demo World", "production", "Production Realm", true); + } + + private static GameInstance gameInstance( + long tenantId, long gameInstanceId, long templateId, long versionId) { + GameInstance instance = new GameInstance(); + instance.setTenantId(tenantId); + instance.setId(gameInstanceId); + instance.setGameTemplateId(templateId); + instance.setVersionId(versionId); + return instance; + } + + private static InitialAdmissionBindHoldBinding binding( + UUID realmId, UUID namespaceId, String initialAdmissionRequestId) { + return new InitialAdmissionBindHoldBinding( + "c791314b-b453-4451-8c34-1a5c6cdfd2dd", + "8bc5a38d-888d-4773-9815-0e9304a48145", + 17L, + realmId.toString(), + namespaceId.toString(), + "SHARED", + 93L, + 44L, + 8L, + initialAdmissionRequestId, + digest(), + true, + 1L); + } + + private static String digest() { + return "a".repeat(64); + } + + private record Harness( + DSLContext dsl, + TransactionTemplate transactionTemplate, + InitialAdmissionBindCatalogRepository catalogRepository, + GameInstanceRepository gameInstanceRepository, + DatabaseInitialAdmissionBindOwnerService service) {} +} diff --git a/services/world-management-service/src/main/java/net/firedevops/firemud/worldmanagement/client/GameSessionInitialAdmissionBindProofClient.java b/services/world-management-service/src/main/java/net/firedevops/firemud/worldmanagement/client/GameSessionInitialAdmissionBindProofClient.java new file mode 100644 index 0000000000..df12533b33 --- /dev/null +++ b/services/world-management-service/src/main/java/net/firedevops/firemud/worldmanagement/client/GameSessionInitialAdmissionBindProofClient.java @@ -0,0 +1,9 @@ +package net.firedevops.firemud.worldmanagement.client; + +import net.firedevops.firemud.worldmanagement.dto.InitialAdmissionBindOwnerProof; +import net.firedevops.firemud.worldmanagement.entity.InitialAdmissionBindHold; + +/** Authenticated Game Session owner-read boundary; no implementation is wired in this slice. */ +public interface GameSessionInitialAdmissionBindProofClient { + InitialAdmissionBindOwnerProof readOwnerProof(InitialAdmissionBindHold hold); +} diff --git a/services/world-management-service/src/main/java/net/firedevops/firemud/worldmanagement/dto/InitialAdmissionBindHoldDto.java b/services/world-management-service/src/main/java/net/firedevops/firemud/worldmanagement/dto/InitialAdmissionBindHoldDto.java new file mode 100644 index 0000000000..d2d16ccaf2 --- /dev/null +++ b/services/world-management-service/src/main/java/net/firedevops/firemud/worldmanagement/dto/InitialAdmissionBindHoldDto.java @@ -0,0 +1,20 @@ +package net.firedevops.firemud.worldmanagement.dto; + +import java.time.Instant; + +public record InitialAdmissionBindHoldDto( + String holdId, + String holdFence, + long tenantId, + String realmUuid, + String playableStateNamespaceUuid, + String playableStateScope, + long gameInstanceId, + long versionId, + long activeLifecycleEpoch, + String initialAdmissionRequestId, + String requestDigest, + boolean expectedNoPriorPointer, + long expectedCatalogRevision, + String status, + Instant diagnosticExpiresAt) {} diff --git a/services/world-management-service/src/main/java/net/firedevops/firemud/worldmanagement/dto/InitialAdmissionBindHoldRequest.java b/services/world-management-service/src/main/java/net/firedevops/firemud/worldmanagement/dto/InitialAdmissionBindHoldRequest.java new file mode 100644 index 0000000000..028d964752 --- /dev/null +++ b/services/world-management-service/src/main/java/net/firedevops/firemud/worldmanagement/dto/InitialAdmissionBindHoldRequest.java @@ -0,0 +1,14 @@ +package net.firedevops.firemud.worldmanagement.dto; + +public record InitialAdmissionBindHoldRequest( + long tenantId, + long gameInstanceId, + long versionId, + long activeLifecycleEpoch, + String initialAdmissionRequestId, + String requestDigest, + String realmUuid, + String playableStateNamespaceUuid, + String playableStateScope, + boolean expectedNoPriorPointer, + long expectedCatalogRevision) {} diff --git a/services/world-management-service/src/main/java/net/firedevops/firemud/worldmanagement/dto/InitialAdmissionBindOwnerProof.java b/services/world-management-service/src/main/java/net/firedevops/firemud/worldmanagement/dto/InitialAdmissionBindOwnerProof.java new file mode 100644 index 0000000000..c151c3a353 --- /dev/null +++ b/services/world-management-service/src/main/java/net/firedevops/firemud/worldmanagement/dto/InitialAdmissionBindOwnerProof.java @@ -0,0 +1,33 @@ +package net.firedevops.firemud.worldmanagement.dto; + +/** Typed Game Session owner readback; only an authenticated owner adapter may supply this proof. */ +public record InitialAdmissionBindOwnerProof( + Outcome outcome, + String holdId, + String holdFence, + long tenantId, + String realmUuid, + String playableStateNamespaceUuid, + String playableStateScope, + long gameInstanceId, + long versionId, + long activeLifecycleEpoch, + String initialAdmissionRequestId, + String requestDigest, + boolean expectedNoPriorPointer, + long expectedCatalogRevision, + String ownerProofId, + String pointerAuditId, + long pointerVersion, + String pointerAuditRequestDigest, + boolean priorPointerStillAbsent, + boolean futureCommitPrevented) { + public enum Outcome { + COMMITTED, + ABORTED, + NOT_FOUND, + PENDING, + UNAVAILABLE, + ERROR + } +} diff --git a/services/world-management-service/src/main/java/net/firedevops/firemud/worldmanagement/entity/InitialAdmissionBindHold.java b/services/world-management-service/src/main/java/net/firedevops/firemud/worldmanagement/entity/InitialAdmissionBindHold.java new file mode 100644 index 0000000000..631379ed05 --- /dev/null +++ b/services/world-management-service/src/main/java/net/firedevops/firemud/worldmanagement/entity/InitialAdmissionBindHold.java @@ -0,0 +1,29 @@ +package net.firedevops.firemud.worldmanagement.entity; + +import java.time.Instant; + +public record InitialAdmissionBindHold( + String holdId, + String holdFence, + long tenantId, + String realmUuid, + String playableStateNamespaceUuid, + String playableStateScope, + long gameInstanceId, + long versionId, + long activeLifecycleEpoch, + String initialAdmissionRequestId, + String requestDigest, + boolean expectedNoPriorPointer, + long expectedCatalogRevision, + String status, + Instant diagnosticExpiresAt, + String ownerProofId, + String ownerProofDigest, + String ownerPointerAuditId, + Long ownerPointerVersion, + String reconciliationError, + Instant createdAt, + Instant updatedAt, + Instant terminalAt, + long rowVersion) {} diff --git a/services/world-management-service/src/main/java/net/firedevops/firemud/worldmanagement/repository/InitialAdmissionBindHoldRepository.java b/services/world-management-service/src/main/java/net/firedevops/firemud/worldmanagement/repository/InitialAdmissionBindHoldRepository.java new file mode 100644 index 0000000000..dbc72b6fb9 --- /dev/null +++ b/services/world-management-service/src/main/java/net/firedevops/firemud/worldmanagement/repository/InitialAdmissionBindHoldRepository.java @@ -0,0 +1,236 @@ +package net.firedevops.firemud.worldmanagement.repository; + +import java.time.Instant; +import java.time.LocalDateTime; +import java.time.ZoneOffset; +import java.util.List; +import java.util.Optional; +import java.util.UUID; +import net.firedevops.firemud.worldmanagement.entity.InitialAdmissionBindHold; +import org.jooq.DSLContext; +import org.jooq.Record; +import org.jooq.Result; +import org.springframework.stereotype.Repository; + +@Repository +public class InitialAdmissionBindHoldRepository { + private static final String SELECT_COLUMNS = + "hold_id, hold_fence, tenant_id, realm_uuid, playable_state_namespace_uuid, " + + "playable_state_scope, game_instance_id, version_id, active_lifecycle_epoch, " + + "initial_admission_request_id, request_digest, expected_no_prior_pointer, " + + "expected_catalog_revision, status, diagnostic_expires_at, owner_proof_id, " + + "owner_proof_digest, owner_pointer_audit_id, owner_pointer_version, " + + "reconciliation_error, created_at, updated_at, terminal_at, row_version"; + + private final DSLContext dsl; + + public InitialAdmissionBindHoldRepository(DSLContext dsl) { + this.dsl = dsl; + } + + public Optional findByTenantIdAndRequestId( + long tenantId, String initialAdmissionRequestId) { + return one( + "SELECT " + + SELECT_COLUMNS + + " FROM initial_admission_bind_hold WHERE tenant_id = ? " + + "AND initial_admission_request_id = ?", + tenantId, + initialAdmissionRequestId); + } + + public Optional findByHoldId(String holdId) { + return one( + "SELECT " + SELECT_COLUMNS + " FROM initial_admission_bind_hold WHERE hold_id = ?::uuid", + UUID.fromString(holdId)); + } + + public Optional findByHoldIdForUpdate(String holdId) { + return one( + "SELECT " + + SELECT_COLUMNS + + " FROM initial_admission_bind_hold WHERE hold_id = ?::uuid FOR UPDATE", + UUID.fromString(holdId)); + } + + public List findNonterminal(int limit) { + Result rows = + dsl.fetch( + "SELECT " + + SELECT_COLUMNS + + " FROM initial_admission_bind_hold WHERE status IN " + + "('PENDING', 'RECONCILIATION_REQUIRED') ORDER BY updated_at, hold_id LIMIT ?", + Math.max(1, Math.min(limit, 256))); + return rows.map(this::toEntity); + } + + public boolean hasNonterminalForGameInstance(long tenantId, long gameInstanceId) { + return Boolean.TRUE.equals( + dsl.fetchValue( + "SELECT EXISTS (SELECT 1 FROM initial_admission_bind_hold " + + "WHERE tenant_id = ? AND game_instance_id = ? " + + "AND status IN ('PENDING', 'RECONCILIATION_REQUIRED'))", + Boolean.class, + tenantId, + gameInstanceId)); + } + + public boolean hasNonterminalForRealm(long tenantId, String realmUuid) { + return Boolean.TRUE.equals( + dsl.fetchValue( + "SELECT EXISTS (SELECT 1 FROM initial_admission_bind_hold " + + "WHERE tenant_id = ? AND realm_uuid = ?::uuid " + + "AND status IN ('PENDING', 'RECONCILIATION_REQUIRED'))", + Boolean.class, + tenantId, + UUID.fromString(realmUuid))); + } + + public Optional insertIfNoUniqueConflict( + InitialAdmissionBindHold hold) { + Result rows = + dsl.fetch( + "INSERT INTO initial_admission_bind_hold (hold_id, hold_fence, tenant_id, realm_uuid, " + + "playable_state_namespace_uuid, playable_state_scope, game_instance_id, version_id, " + + "active_lifecycle_epoch, initial_admission_request_id, request_digest, " + + "expected_no_prior_pointer, expected_catalog_revision, status, diagnostic_expires_at, " + + "created_at, updated_at, row_version) VALUES (?::uuid, ?::uuid, ?, ?::uuid, " + + "?::uuid, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, 0) " + + "ON CONFLICT DO NOTHING RETURNING " + + SELECT_COLUMNS, + UUID.fromString(hold.holdId()), + UUID.fromString(hold.holdFence()), + hold.tenantId(), + UUID.fromString(hold.realmUuid()), + UUID.fromString(hold.playableStateNamespaceUuid()), + hold.playableStateScope(), + hold.gameInstanceId(), + hold.versionId(), + hold.activeLifecycleEpoch(), + hold.initialAdmissionRequestId(), + hold.requestDigest(), + hold.expectedNoPriorPointer(), + hold.expectedCatalogRevision(), + hold.status(), + toLocalDateTime(hold.diagnosticExpiresAt()), + toLocalDateTime(hold.createdAt()), + toLocalDateTime(hold.updatedAt())); + return rows.isEmpty() ? Optional.empty() : Optional.of(toEntity(rows.getFirst())); + } + + public Optional markReconciliationRequired( + InitialAdmissionBindHold hold, String errorCode, Instant now) { + dsl.execute( + "UPDATE initial_admission_bind_hold SET status = 'RECONCILIATION_REQUIRED', " + + "reconciliation_error = ?, updated_at = ?, row_version = row_version + 1 " + + "WHERE hold_id = ?::uuid AND hold_fence = ?::uuid AND tenant_id = ? " + + "AND realm_uuid = ?::uuid AND playable_state_namespace_uuid = ?::uuid " + + "AND playable_state_scope = ? AND game_instance_id = ? AND version_id = ? " + + "AND active_lifecycle_epoch = ? AND initial_admission_request_id = ? " + + "AND request_digest = ? AND expected_no_prior_pointer = ? " + + "AND expected_catalog_revision = ? AND row_version = ? " + + "AND status IN ('PENDING', 'RECONCILIATION_REQUIRED')", + errorCode, + toLocalDateTime(now), + UUID.fromString(hold.holdId()), + UUID.fromString(hold.holdFence()), + hold.tenantId(), + UUID.fromString(hold.realmUuid()), + UUID.fromString(hold.playableStateNamespaceUuid()), + hold.playableStateScope(), + hold.gameInstanceId(), + hold.versionId(), + hold.activeLifecycleEpoch(), + hold.initialAdmissionRequestId(), + hold.requestDigest(), + hold.expectedNoPriorPointer(), + hold.expectedCatalogRevision(), + hold.rowVersion()); + return findByHoldIdForUpdate(hold.holdId()); + } + + public Optional recordTerminalProof( + InitialAdmissionBindHold hold, + String terminalStatus, + String ownerProofId, + String ownerProofDigest, + String pointerAuditId, + Long pointerVersion, + Instant now) { + int updated = + dsl.execute( + "UPDATE initial_admission_bind_hold SET status = ?, owner_proof_id = ?, " + + "owner_proof_digest = ?, owner_pointer_audit_id = ?, owner_pointer_version = ?, " + + "reconciliation_error = NULL, terminal_at = ?, updated_at = ?, " + + "row_version = row_version + 1 WHERE hold_id = ?::uuid AND hold_fence = ?::uuid " + + "AND tenant_id = ? AND realm_uuid = ?::uuid " + + "AND playable_state_namespace_uuid = ?::uuid AND playable_state_scope = ? " + + "AND game_instance_id = ? AND version_id = ? AND active_lifecycle_epoch = ? " + + "AND initial_admission_request_id = ? AND request_digest = ? " + + "AND expected_no_prior_pointer = ? AND expected_catalog_revision = ? " + + "AND row_version = ? AND status IN ('PENDING', 'RECONCILIATION_REQUIRED')", + terminalStatus, + ownerProofId, + ownerProofDigest, + pointerAuditId, + pointerVersion, + toLocalDateTime(now), + toLocalDateTime(now), + UUID.fromString(hold.holdId()), + UUID.fromString(hold.holdFence()), + hold.tenantId(), + UUID.fromString(hold.realmUuid()), + UUID.fromString(hold.playableStateNamespaceUuid()), + hold.playableStateScope(), + hold.gameInstanceId(), + hold.versionId(), + hold.activeLifecycleEpoch(), + hold.initialAdmissionRequestId(), + hold.requestDigest(), + hold.expectedNoPriorPointer(), + hold.expectedCatalogRevision(), + hold.rowVersion()); + return updated == 1 ? findByHoldIdForUpdate(hold.holdId()) : Optional.empty(); + } + + private Optional one(String query, Object... bindings) { + Result rows = dsl.fetch(query, bindings); + return rows.isEmpty() ? Optional.empty() : Optional.of(toEntity(rows.getFirst())); + } + + private InitialAdmissionBindHold toEntity(Record record) { + return new InitialAdmissionBindHold( + record.get("hold_id", UUID.class).toString(), + record.get("hold_fence", UUID.class).toString(), + record.get("tenant_id", Long.class), + record.get("realm_uuid", UUID.class).toString(), + record.get("playable_state_namespace_uuid", UUID.class).toString(), + record.get("playable_state_scope", String.class), + record.get("game_instance_id", Long.class), + record.get("version_id", Long.class), + record.get("active_lifecycle_epoch", Long.class), + record.get("initial_admission_request_id", String.class), + record.get("request_digest", String.class), + record.get("expected_no_prior_pointer", Boolean.class), + record.get("expected_catalog_revision", Long.class), + record.get("status", String.class), + toInstant(record.get("diagnostic_expires_at", LocalDateTime.class)), + record.get("owner_proof_id", String.class), + record.get("owner_proof_digest", String.class), + record.get("owner_pointer_audit_id", String.class), + record.get("owner_pointer_version", Long.class), + record.get("reconciliation_error", String.class), + toInstant(record.get("created_at", LocalDateTime.class)), + toInstant(record.get("updated_at", LocalDateTime.class)), + toInstant(record.get("terminal_at", LocalDateTime.class)), + record.get("row_version", Long.class)); + } + + private LocalDateTime toLocalDateTime(Instant instant) { + return instant == null ? null : LocalDateTime.ofInstant(instant, ZoneOffset.UTC); + } + + private Instant toInstant(LocalDateTime localDateTime) { + return localDateTime == null ? null : localDateTime.toInstant(ZoneOffset.UTC); + } +} diff --git a/services/world-management-service/src/main/java/net/firedevops/firemud/worldmanagement/repository/WorldInstanceRepository.java b/services/world-management-service/src/main/java/net/firedevops/firemud/worldmanagement/repository/WorldInstanceRepository.java index df1fc9d9c7..eff9e600e8 100644 --- a/services/world-management-service/src/main/java/net/firedevops/firemud/worldmanagement/repository/WorldInstanceRepository.java +++ b/services/world-management-service/src/main/java/net/firedevops/firemud/worldmanagement/repository/WorldInstanceRepository.java @@ -32,6 +32,29 @@ public Optional findByTenantIdAndGameInstanceId( .fetchOptional(this::toEntity); } + public Optional findByTenantIdAndGameInstanceIdForUpdate( + Long tenantId, Long gameInstanceId) { + return dsl.selectFrom(WORLD_INSTANCE) + .where( + WORLD_INSTANCE + .TENANT_ID + .eq(tenantId) + .and(WORLD_INSTANCE.GAME_INSTANCE_ID.eq(gameInstanceId))) + .forUpdate() + .fetchOptional(this::toEntity); + } + + public boolean hasNonterminalInitialAdmissionBindHold(Long tenantId, Long gameInstanceId) { + return Boolean.TRUE.equals( + dsl.fetchValue( + "SELECT EXISTS (SELECT 1 FROM initial_admission_bind_hold " + + "WHERE tenant_id = ? AND game_instance_id = ? " + + "AND status IN ('PENDING', 'RECONCILIATION_REQUIRED'))", + Boolean.class, + tenantId, + gameInstanceId)); + } + public Optional findById(Long id) { return dsl.selectFrom(WORLD_INSTANCE) .where(WORLD_INSTANCE.ID.eq(id)) diff --git a/services/world-management-service/src/main/java/net/firedevops/firemud/worldmanagement/service/InitialAdmissionBindHoldService.java b/services/world-management-service/src/main/java/net/firedevops/firemud/worldmanagement/service/InitialAdmissionBindHoldService.java new file mode 100644 index 0000000000..b5bec0ddcd --- /dev/null +++ b/services/world-management-service/src/main/java/net/firedevops/firemud/worldmanagement/service/InitialAdmissionBindHoldService.java @@ -0,0 +1,14 @@ +package net.firedevops.firemud.worldmanagement.service; + +import net.firedevops.firemud.worldmanagement.dto.InitialAdmissionBindHoldDto; +import net.firedevops.firemud.worldmanagement.dto.InitialAdmissionBindHoldRequest; +import net.firedevops.firemud.worldmanagement.dto.InitialAdmissionBindOwnerProof; + +public interface InitialAdmissionBindHoldService { + InitialAdmissionBindHoldDto acquire(InitialAdmissionBindHoldRequest request); + + InitialAdmissionBindHoldDto reconcileOwnerProof( + String holdId, InitialAdmissionBindOwnerProof ownerProof); + + InitialAdmissionBindHoldDto requireReconciliation(String holdId, String errorCode); +} diff --git a/services/world-management-service/src/main/java/net/firedevops/firemud/worldmanagement/service/impl/InitialAdmissionBindHoldReconciler.java b/services/world-management-service/src/main/java/net/firedevops/firemud/worldmanagement/service/impl/InitialAdmissionBindHoldReconciler.java new file mode 100644 index 0000000000..6bd2d07d1d --- /dev/null +++ b/services/world-management-service/src/main/java/net/firedevops/firemud/worldmanagement/service/impl/InitialAdmissionBindHoldReconciler.java @@ -0,0 +1,74 @@ +package net.firedevops.firemud.worldmanagement.service.impl; + +import java.time.Clock; +import java.util.List; +import net.firedevops.firemud.worldmanagement.client.GameSessionInitialAdmissionBindProofClient; +import net.firedevops.firemud.worldmanagement.repository.InitialAdmissionBindHoldRepository; +import net.firedevops.firemud.worldmanagement.service.InitialAdmissionBindHoldService; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; +import org.springframework.beans.factory.ObjectProvider; +import org.springframework.scheduling.annotation.Scheduled; +import org.springframework.stereotype.Component; + +/** Automatically reconciles World holds; until a GS adapter is wired, it stays fail-closed. */ +@Component +public class InitialAdmissionBindHoldReconciler { + private static final Logger logger = + LoggerFactory.getLogger(InitialAdmissionBindHoldReconciler.class); + + private final InitialAdmissionBindHoldRepository holdRepository; + private final InitialAdmissionBindHoldService holdService; + private final ObjectProvider proofClientProvider; + private final Clock clock; + + public InitialAdmissionBindHoldReconciler( + InitialAdmissionBindHoldRepository holdRepository, + InitialAdmissionBindHoldService holdService, + ObjectProvider proofClientProvider) { + this(holdRepository, holdService, proofClientProvider, Clock.systemUTC()); + } + + InitialAdmissionBindHoldReconciler( + InitialAdmissionBindHoldRepository holdRepository, + InitialAdmissionBindHoldService holdService, + ObjectProvider proofClientProvider, + Clock clock) { + this.holdRepository = holdRepository; + this.holdService = holdService; + this.proofClientProvider = proofClientProvider; + this.clock = clock; + } + + @Scheduled(fixedDelayString = "${world.initial-admission-bind.reconcile-delay-ms:5000}") + public void reconcilePendingHolds() { + List holds = + holdRepository.findNonterminal(32); + if (holds.isEmpty()) { + return; + } + GameSessionInitialAdmissionBindProofClient proofClient = proofClientProvider.getIfAvailable(); + for (var hold : holds) { + if (proofClient == null) { + holdService.requireReconciliation(hold.holdId(), "GS_OWNER_READ_UNAVAILABLE"); + continue; + } + if (!hold.diagnosticExpiresAt().isAfter(clock.instant())) { + logger.warn( + "Initial admission bind hold exceeded its diagnostic age holdId={} tenant={} gameInstanceId={}", + hold.holdId(), + hold.tenantId(), + hold.gameInstanceId()); + } + try { + holdService.reconcileOwnerProof(hold.holdId(), proofClient.readOwnerProof(hold)); + } catch (RuntimeException exception) { + logger.warn( + "Initial admission bind owner readback failed holdId={} errorType={}", + hold.holdId(), + exception.getClass().getSimpleName()); + holdService.requireReconciliation(hold.holdId(), "GS_OWNER_READ_FAILED"); + } + } + } +} diff --git a/services/world-management-service/src/main/java/net/firedevops/firemud/worldmanagement/service/impl/InitialAdmissionBindHoldServiceImpl.java b/services/world-management-service/src/main/java/net/firedevops/firemud/worldmanagement/service/impl/InitialAdmissionBindHoldServiceImpl.java new file mode 100644 index 0000000000..557c42c3e0 --- /dev/null +++ b/services/world-management-service/src/main/java/net/firedevops/firemud/worldmanagement/service/impl/InitialAdmissionBindHoldServiceImpl.java @@ -0,0 +1,450 @@ +package net.firedevops.firemud.worldmanagement.service.impl; + +import java.nio.charset.StandardCharsets; +import java.security.MessageDigest; +import java.security.NoSuchAlgorithmException; +import java.time.Clock; +import java.time.Duration; +import java.time.Instant; +import java.util.HexFormat; +import java.util.Objects; +import java.util.Optional; +import java.util.UUID; +import java.util.regex.Pattern; +import net.firedevops.firemud.worldmanagement.dto.InitialAdmissionBindHoldDto; +import net.firedevops.firemud.worldmanagement.dto.InitialAdmissionBindHoldRequest; +import net.firedevops.firemud.worldmanagement.dto.InitialAdmissionBindOwnerProof; +import net.firedevops.firemud.worldmanagement.entity.InitialAdmissionBindHold; +import net.firedevops.firemud.worldmanagement.entity.WorldInstance; +import net.firedevops.firemud.worldmanagement.repository.InitialAdmissionBindHoldRepository; +import net.firedevops.firemud.worldmanagement.repository.WorldInstanceRepository; +import net.firedevops.firemud.worldmanagement.service.InitialAdmissionBindHoldService; +import org.springframework.stereotype.Service; +import org.springframework.transaction.annotation.Transactional; + +@Service +public class InitialAdmissionBindHoldServiceImpl implements InitialAdmissionBindHoldService { + private static final String STATUS_PENDING = "PENDING"; + private static final String STATUS_ACTIVE = "ACTIVE"; + private static final String STATUS_RECONCILIATION_REQUIRED = "RECONCILIATION_REQUIRED"; + private static final String STATUS_COMMITTED = "COMMITTED"; + private static final String STATUS_ABORTED = "ABORTED"; + private static final Pattern SHA_256 = Pattern.compile("[0-9a-f]{64}"); + private static final Duration DIAGNOSTIC_HOLD_AGE = Duration.ofMinutes(5); + + private final InitialAdmissionBindHoldRepository holdRepository; + private final WorldInstanceRepository worldInstanceRepository; + private final Clock clock; + + public InitialAdmissionBindHoldServiceImpl( + InitialAdmissionBindHoldRepository holdRepository, + WorldInstanceRepository worldInstanceRepository) { + this(holdRepository, worldInstanceRepository, Clock.systemUTC()); + } + + InitialAdmissionBindHoldServiceImpl( + InitialAdmissionBindHoldRepository holdRepository, + WorldInstanceRepository worldInstanceRepository, + Clock clock) { + this.holdRepository = holdRepository; + this.worldInstanceRepository = worldInstanceRepository; + this.clock = clock; + } + + @Override + @Transactional + public InitialAdmissionBindHoldDto acquire(InitialAdmissionBindHoldRequest request) { + validateRequest(request); + WorldInstance worldInstance = + requireLockedWorldInstance(request.tenantId(), request.gameInstanceId()); + Optional existing = + holdRepository.findByTenantIdAndRequestId( + request.tenantId(), request.initialAdmissionRequestId()); + if (existing.isPresent()) { + InitialAdmissionBindHold hold = existing.get(); + requireSameRequestIdentity(hold, request); + if (isTerminal(hold.status())) { + return toDto(hold); + } + requireActiveTarget(worldInstance, request); + return toDto(hold); + } + + requireActiveTarget(worldInstance, request); + if (holdRepository.hasNonterminalForRealm(request.tenantId(), request.realmUuid())) { + throw new IllegalArgumentException( + "INITIAL_ADMISSION_BIND_HOLD_CONFLICT: realm has an unresolved initial admission hold"); + } + + Instant now = clock.instant(); + InitialAdmissionBindHold candidate = + new InitialAdmissionBindHold( + UUID.randomUUID().toString(), + UUID.randomUUID().toString(), + request.tenantId(), + request.realmUuid(), + request.playableStateNamespaceUuid(), + request.playableStateScope(), + request.gameInstanceId(), + request.versionId(), + request.activeLifecycleEpoch(), + request.initialAdmissionRequestId(), + request.requestDigest(), + true, + request.expectedCatalogRevision(), + STATUS_PENDING, + now.plus(DIAGNOSTIC_HOLD_AGE), + null, + null, + null, + null, + null, + now, + now, + null, + 0L); + Optional inserted = + holdRepository.insertIfNoUniqueConflict(candidate); + if (inserted.isPresent()) { + return toDto(inserted.get()); + } + + Optional racedRetry = + holdRepository.findByTenantIdAndRequestId( + request.tenantId(), request.initialAdmissionRequestId()); + if (racedRetry.isPresent()) { + requireSameRequestIdentity(racedRetry.get(), request); + return toDto(racedRetry.get()); + } + throw new IllegalArgumentException( + "INITIAL_ADMISSION_BIND_HOLD_CONFLICT: another unresolved hold owns this realm"); + } + + @Override + @Transactional + public InitialAdmissionBindHoldDto reconcileOwnerProof( + String holdId, InitialAdmissionBindOwnerProof ownerProof) { + InitialAdmissionBindHold hold = requireHold(holdId); + if (ownerProof == null) { + return requireReconciliation(holdId, "GS_OWNER_PROOF_MISSING"); + } + String proofDigest = proofDigest(ownerProof); + if (isTerminal(hold.status())) { + if (isTerminal(ownerProof.outcome()) + && sameIdentity(hold, ownerProof) + && hold.status().equals(statusFor(ownerProof.outcome())) + && proofDigest.equals(hold.ownerProofDigest())) { + return toDto(hold); + } + throw new IllegalArgumentException( + "IDEMPOTENCY_CONFLICT: terminal initial admission proof changed"); + } + + if (!isTerminal(ownerProof.outcome())) { + return markReconciliationRequired(hold, "GS_OWNER_" + outcomeName(ownerProof.outcome())); + } + if (!sameIdentity(hold, ownerProof)) { + return markReconciliationRequired(hold, "GS_OWNER_PROOF_MISMATCH"); + } + if (!hasDefinitiveTerminalEvidence(hold, ownerProof)) { + return markReconciliationRequired(hold, "GS_OWNER_TERMINAL_PROOF_INCOMPLETE"); + } + + Optional maybeWorldInstance = + worldInstanceRepository.findByTenantIdAndGameInstanceIdForUpdate( + hold.tenantId(), hold.gameInstanceId()); + hold = requireLockedHold(holdId); + if (isTerminal(hold.status())) { + if (sameIdentity(hold, ownerProof) + && hold.status().equals(statusFor(ownerProof.outcome())) + && proofDigest.equals(hold.ownerProofDigest())) { + return toDto(hold); + } + throw new IllegalArgumentException( + "IDEMPOTENCY_CONFLICT: terminal initial admission proof changed"); + } + if (!sameIdentity(hold, ownerProof) || !hasDefinitiveTerminalEvidence(hold, ownerProof)) { + return markReconciliationRequired(hold, "GS_OWNER_PROOF_MISMATCH"); + } + if (maybeWorldInstance.isEmpty() + || !STATUS_ACTIVE.equals(maybeWorldInstance.get().getStatus()) + || !Objects.equals(hold.versionId(), maybeWorldInstance.get().getVersionId()) + || hold.activeLifecycleEpoch() != maybeWorldInstance.get().getLifecycleEpoch()) { + return markReconciliationRequired(hold, "WORLD_LIFECYCLE_PROOF_MISMATCH"); + } + + String terminalStatus = statusFor(ownerProof.outcome()); + Optional updated = + holdRepository.recordTerminalProof( + hold, + terminalStatus, + ownerProof.ownerProofId(), + proofDigest, + terminalStatus.equals(STATUS_COMMITTED) ? ownerProof.pointerAuditId() : null, + terminalStatus.equals(STATUS_COMMITTED) ? ownerProof.pointerVersion() : null, + clock.instant()); + if (updated.isEmpty()) { + InitialAdmissionBindHold current = requireLockedHold(holdId); + if (isTerminal(current.status()) + && current.status().equals(terminalStatus) + && proofDigest.equals(current.ownerProofDigest())) { + return toDto(current); + } + throw new IllegalStateException("INITIAL_ADMISSION_BIND_HOLD_STALE: terminal update lost"); + } + return toDto(updated.get()); + } + + @Override + @Transactional + public InitialAdmissionBindHoldDto requireReconciliation(String holdId, String errorCode) { + InitialAdmissionBindHold hold = requireLockedHold(holdId); + if (isTerminal(hold.status())) { + return toDto(hold); + } + return markReconciliationRequired(hold, normalizeErrorCode(errorCode)); + } + + private InitialAdmissionBindHoldDto markReconciliationRequired( + InitialAdmissionBindHold hold, String errorCode) { + String normalizedErrorCode = normalizeErrorCode(errorCode); + if (STATUS_RECONCILIATION_REQUIRED.equals(hold.status()) + && normalizedErrorCode.equals(hold.reconciliationError())) { + return toDto(hold); + } + return holdRepository + .markReconciliationRequired(hold, normalizedErrorCode, clock.instant()) + .map(this::toDto) + .orElseThrow( + () -> + new IllegalStateException( + "INITIAL_ADMISSION_BIND_HOLD_STALE: reconciliation update lost")); + } + + private void validateRequest(InitialAdmissionBindHoldRequest request) { + if (request == null + || request.tenantId() <= 0L + || request.gameInstanceId() <= 0L + || request.versionId() <= 0L + || request.activeLifecycleEpoch() <= 0L + || request.expectedCatalogRevision() <= 0L + || !isSupportedPlayableStateScope(request.playableStateScope()) + || !request.expectedNoPriorPointer()) { + throw new IllegalArgumentException( + "INVALID_ARGUMENT: initial admission bind requires a supported scope, positive target and catalog revisions, and an absent prior pointer"); + } + requireText(request.initialAdmissionRequestId(), "initialAdmissionRequestId", 128); + if (!SHA_256.matcher(nullToEmpty(request.requestDigest())).matches()) { + throw new IllegalArgumentException( + "INVALID_ARGUMENT: requestDigest must be lowercase SHA-256 hex"); + } + requireCanonicalUuid(request.realmUuid(), "realmUuid"); + requireCanonicalUuid(request.playableStateNamespaceUuid(), "playableStateNamespaceUuid"); + } + + private boolean isSupportedPlayableStateScope(String scope) { + return "SHARED".equals(scope) || "ISOLATED".equals(scope); + } + + private void requireActiveTarget( + WorldInstance worldInstance, InitialAdmissionBindHoldRequest request) { + if (!STATUS_ACTIVE.equals(worldInstance.getStatus()) + || !Objects.equals(request.versionId(), worldInstance.getVersionId()) + || request.activeLifecycleEpoch() != worldInstance.getLifecycleEpoch()) { + throw new IllegalArgumentException( + "WORLD_LIFECYCLE_PROOF_MISMATCH: target is not ACTIVE at the requested version and epoch"); + } + } + + private void requireSameRequestIdentity( + InitialAdmissionBindHold hold, InitialAdmissionBindHoldRequest request) { + if (hold.tenantId() != request.tenantId() + || hold.gameInstanceId() != request.gameInstanceId() + || hold.versionId() != request.versionId() + || hold.activeLifecycleEpoch() != request.activeLifecycleEpoch() + || !hold.initialAdmissionRequestId().equals(request.initialAdmissionRequestId()) + || !hold.requestDigest().equals(request.requestDigest()) + || !hold.realmUuid().equals(request.realmUuid()) + || !hold.playableStateNamespaceUuid().equals(request.playableStateNamespaceUuid()) + || !hold.playableStateScope().equals(request.playableStateScope()) + || !hold.expectedNoPriorPointer() + || !request.expectedNoPriorPointer() + || hold.expectedCatalogRevision() != request.expectedCatalogRevision()) { + throw new IllegalArgumentException( + "IDEMPOTENCY_CONFLICT: initial admission request identity changed"); + } + } + + private boolean sameIdentity( + InitialAdmissionBindHold hold, InitialAdmissionBindOwnerProof proof) { + return proof != null + && hold.holdId().equals(proof.holdId()) + && hold.holdFence().equals(proof.holdFence()) + && hold.tenantId() == proof.tenantId() + && hold.realmUuid().equals(proof.realmUuid()) + && hold.playableStateNamespaceUuid().equals(proof.playableStateNamespaceUuid()) + && hold.playableStateScope().equals(proof.playableStateScope()) + && hold.gameInstanceId() == proof.gameInstanceId() + && hold.versionId() == proof.versionId() + && hold.activeLifecycleEpoch() == proof.activeLifecycleEpoch() + && hold.initialAdmissionRequestId().equals(proof.initialAdmissionRequestId()) + && hold.requestDigest().equals(proof.requestDigest()) + && hold.expectedNoPriorPointer() == proof.expectedNoPriorPointer() + && hold.expectedCatalogRevision() == proof.expectedCatalogRevision(); + } + + private boolean hasDefinitiveTerminalEvidence( + InitialAdmissionBindHold hold, InitialAdmissionBindOwnerProof proof) { + if (proof.ownerProofId() == null || proof.ownerProofId().isBlank()) { + return false; + } + if (proof.outcome() == InitialAdmissionBindOwnerProof.Outcome.COMMITTED) { + return proof.expectedNoPriorPointer() + && proof.pointerVersion() > 0L + && proof.pointerAuditId() != null + && !proof.pointerAuditId().isBlank() + && hold.requestDigest().equals(proof.pointerAuditRequestDigest()); + } + return proof.outcome() == InitialAdmissionBindOwnerProof.Outcome.ABORTED + && proof.futureCommitPrevented() + && (proof.pointerAuditId() == null || proof.pointerAuditId().isBlank()) + && proof.pointerVersion() == 0L; + } + + private InitialAdmissionBindHold requireLockedHold(String holdId) { + requireCanonicalUuid(holdId, "holdId"); + return holdRepository + .findByHoldIdForUpdate(holdId) + .orElseThrow( + () -> + new IllegalArgumentException( + "INITIAL_ADMISSION_BIND_HOLD_NOT_FOUND: hold not found")); + } + + private InitialAdmissionBindHold requireHold(String holdId) { + requireCanonicalUuid(holdId, "holdId"); + return holdRepository + .findByHoldId(holdId) + .orElseThrow( + () -> + new IllegalArgumentException( + "INITIAL_ADMISSION_BIND_HOLD_NOT_FOUND: hold not found")); + } + + private WorldInstance requireLockedWorldInstance(long tenantId, long gameInstanceId) { + return worldInstanceRepository + .findByTenantIdAndGameInstanceIdForUpdate(tenantId, gameInstanceId) + .orElseThrow( + () -> + new IllegalArgumentException("WORLD_INSTANCE_NOT_FOUND: world instance not found")); + } + + private boolean isTerminal(String status) { + return STATUS_COMMITTED.equals(status) || STATUS_ABORTED.equals(status); + } + + private boolean isTerminal(InitialAdmissionBindOwnerProof.Outcome outcome) { + return outcome == InitialAdmissionBindOwnerProof.Outcome.COMMITTED + || outcome == InitialAdmissionBindOwnerProof.Outcome.ABORTED; + } + + private String statusFor(InitialAdmissionBindOwnerProof.Outcome outcome) { + return switch (outcome) { + case COMMITTED -> STATUS_COMMITTED; + case ABORTED -> STATUS_ABORTED; + default -> throw new IllegalArgumentException("Owner proof is not terminal"); + }; + } + + private String outcomeName(InitialAdmissionBindOwnerProof.Outcome outcome) { + return outcome == null ? "PROOF_INVALID" : outcome.name(); + } + + private String proofDigest(InitialAdmissionBindOwnerProof proof) { + String canonical = + String.join( + "\n", + outcomeName(proof.outcome()), + nullToEmpty(proof.holdId()), + nullToEmpty(proof.holdFence()), + Long.toString(proof.tenantId()), + nullToEmpty(proof.realmUuid()), + nullToEmpty(proof.playableStateNamespaceUuid()), + nullToEmpty(proof.playableStateScope()), + Long.toString(proof.gameInstanceId()), + Long.toString(proof.versionId()), + Long.toString(proof.activeLifecycleEpoch()), + nullToEmpty(proof.initialAdmissionRequestId()), + nullToEmpty(proof.requestDigest()), + Boolean.toString(proof.expectedNoPriorPointer()), + Long.toString(proof.expectedCatalogRevision()), + nullToEmpty(proof.ownerProofId()), + nullToEmpty(proof.pointerAuditId()), + Long.toString(proof.pointerVersion()), + nullToEmpty(proof.pointerAuditRequestDigest()), + Boolean.toString(proof.priorPointerStillAbsent()), + Boolean.toString(proof.futureCommitPrevented())); + try { + return HexFormat.of() + .formatHex( + MessageDigest.getInstance("SHA-256") + .digest(canonical.getBytes(StandardCharsets.UTF_8))); + } catch (NoSuchAlgorithmException exception) { + throw new AssertionError("SHA-256 is required by the Java platform", exception); + } + } + + private InitialAdmissionBindHoldDto toDto(InitialAdmissionBindHold hold) { + return new InitialAdmissionBindHoldDto( + hold.holdId(), + hold.holdFence(), + hold.tenantId(), + hold.realmUuid(), + hold.playableStateNamespaceUuid(), + hold.playableStateScope(), + hold.gameInstanceId(), + hold.versionId(), + hold.activeLifecycleEpoch(), + hold.initialAdmissionRequestId(), + hold.requestDigest(), + hold.expectedNoPriorPointer(), + hold.expectedCatalogRevision(), + hold.status(), + hold.diagnosticExpiresAt()); + } + + private String normalizeErrorCode(String errorCode) { + if (errorCode == null || !errorCode.matches("[A-Z0-9_]{1,128}")) { + return "GS_OWNER_READ_UNAVAILABLE"; + } + return errorCode; + } + + private void requireCanonicalUuid(String value, String fieldName) { + if (value == null) { + throw new IllegalArgumentException("INVALID_ARGUMENT: " + fieldName + " must be a UUID"); + } + try { + if (!UUID.fromString(value).toString().equals(value)) { + throw new IllegalArgumentException("noncanonical UUID"); + } + } catch (IllegalArgumentException exception) { + throw new IllegalArgumentException("INVALID_ARGUMENT: " + fieldName + " must be a UUID"); + } + } + + private void requireText(String value, String fieldName, int maxLength) { + if (value == null + || value.isBlank() + || value.length() > maxLength + || !value.equals(value.trim()) + || value.indexOf('\n') >= 0 + || value.indexOf('\r') >= 0) { + throw new IllegalArgumentException("INVALID_ARGUMENT: " + fieldName + " is invalid"); + } + } + + private String nullToEmpty(String value) { + return value == null ? "" : value; + } +} diff --git a/services/world-management-service/src/main/java/net/firedevops/firemud/worldmanagement/service/impl/InitialAdmissionBindWorkloadGuard.java b/services/world-management-service/src/main/java/net/firedevops/firemud/worldmanagement/service/impl/InitialAdmissionBindWorkloadGuard.java new file mode 100644 index 0000000000..7a21c78703 --- /dev/null +++ b/services/world-management-service/src/main/java/net/firedevops/firemud/worldmanagement/service/impl/InitialAdmissionBindWorkloadGuard.java @@ -0,0 +1,31 @@ +package net.firedevops.firemud.worldmanagement.service.impl; + +import net.firedevops.firemud.common.grpc.GrpcPeerIdentity; +import net.firedevops.firemud.common.security.AdminAuthorizationException; +import net.firedevops.firemud.common.security.SessionContext; +import net.firedevops.firemud.worldmanagement.v1.WorldManagementServiceGrpc; + +/** Method-local Game Session workload authorization for initial-bind hold acquisition. */ +public final class InitialAdmissionBindWorkloadGuard { + private final String trustedNamespace; + + public InitialAdmissionBindWorkloadGuard(String trustedNamespace) { + this.trustedNamespace = trustedNamespace; + } + + public void requireGameSessionAcquireCaller() { + GrpcPeerIdentity peerIdentity = GrpcPeerIdentity.current(); + if (!WorldManagementServiceGrpc.getAcquireInitialAdmissionBindHoldMethod() + .getFullMethodName() + .equals("world_management.v1.WorldManagementService/AcquireInitialAdmissionBindHold") + || trustedNamespace == null + || !GrpcPeerIdentity.isValidNamespace(trustedNamespace) + || peerIdentity == null + || !peerIdentity.isService("game-session-service") + || !peerIdentity.isInNamespace(trustedNamespace) + || SessionContext.hasAuthenticatedCallerContext()) { + throw new AdminAuthorizationException( + "Initial admission hold requires only the authenticated Game Session workload peer identity"); + } + } +} 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 7151814b65..180dd36a8c 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 @@ -337,26 +337,18 @@ public WorldInstanceLifecycleSnapshotDto terminateWorldInstance( if (terminationRequestId == null || terminationRequestId.isBlank()) { throw new IllegalArgumentException("INVALID_ARGUMENT: terminationRequestId is required"); } - WorldInstance worldInstance = requireWorldInstance(tenantId, gameInstanceId); + WorldInstance worldInstance = + executeLocalTermination( + () -> + beginOrResumeTermination( + tenantId, + gameInstanceId, + expectedLifecycleEpoch, + terminationRequestId, + reason)); if (STATUS_TERMINATED.equals(worldInstance.getStatus())) { return snapshot(worldInstance); } - if (STATUS_ACTIVE.equals(worldInstance.getStatus())) { - requireLifecycleEpoch(worldInstance, expectedLifecycleEpoch); - worldInstance.setStatus(STATUS_TERMINATING); - worldInstance.setTerminationRequestId(terminationRequestId); - worldInstance.setFailureReason(normalizeBlank(reason)); - worldInstance.setLifecycleEpoch(worldInstance.getLifecycleEpoch() + 1L); - worldInstanceRepository.save(worldInstance); - } else if (STATUS_TERMINATING.equals(worldInstance.getStatus())) { - if (!terminationRequestId.equals(worldInstance.getTerminationRequestId())) { - throw new IllegalArgumentException( - "INVALID_WORLD_INSTANCE_STATE: world instance is terminating under a different request id"); - } - } else { - throw new IllegalArgumentException( - "INVALID_WORLD_INSTANCE_STATE: world instance is not in ACTIVE or TERMINATING state"); - } var cleanupResponse = entityManagementClient == null ? null @@ -369,7 +361,8 @@ public WorldInstanceLifecycleSnapshotDto terminateWorldInstance( WorldInstanceLifecycleSnapshotDto terminatedSnapshot = executeLocalTermination( () -> { - WorldInstance finalWorldInstance = requireWorldInstance(tenantId, gameInstanceId); + WorldInstance finalWorldInstance = + requireLockedWorldInstance(tenantId, gameInstanceId); if (!terminationRequestId.equals(finalWorldInstance.getTerminationRequestId())) { throw new IllegalArgumentException( "INVALID_WORLD_INSTANCE_STATE: world instance termination request changed before finalization"); @@ -395,14 +388,55 @@ public WorldInstanceLifecycleSnapshotDto terminateWorldInstance( return terminatedSnapshot; } - private WorldInstanceLifecycleSnapshotDto executeLocalTermination( - java.util.function.Supplier termination) { + private WorldInstance beginOrResumeTermination( + long tenantId, + long gameInstanceId, + long expectedLifecycleEpoch, + String terminationRequestId, + String reason) { + WorldInstance worldInstance = requireLockedWorldInstance(tenantId, gameInstanceId); + if (STATUS_TERMINATED.equals(worldInstance.getStatus())) { + return worldInstance; + } + if (STATUS_ACTIVE.equals(worldInstance.getStatus())) { + requireLifecycleEpoch(worldInstance, expectedLifecycleEpoch); + if (worldInstanceRepository.hasNonterminalInitialAdmissionBindHold( + tenantId, gameInstanceId)) { + throw new IllegalArgumentException( + "INITIAL_ADMISSION_BIND_HOLD_ACTIVE: initial admission binding is unresolved"); + } + worldInstance.setStatus(STATUS_TERMINATING); + worldInstance.setTerminationRequestId(terminationRequestId); + worldInstance.setFailureReason(normalizeBlank(reason)); + worldInstance.setLifecycleEpoch(worldInstance.getLifecycleEpoch() + 1L); + return worldInstanceRepository.save(worldInstance); + } + if (STATUS_TERMINATING.equals(worldInstance.getStatus())) { + if (!terminationRequestId.equals(worldInstance.getTerminationRequestId())) { + throw new IllegalArgumentException( + "INVALID_WORLD_INSTANCE_STATE: world instance is terminating under a different request id"); + } + return worldInstance; + } + throw new IllegalArgumentException( + "INVALID_WORLD_INSTANCE_STATE: world instance is not in ACTIVE or TERMINATING state"); + } + + private T executeLocalTermination(java.util.function.Supplier termination) { if (transactionOperations == null) { return termination.get(); } return transactionOperations.execute(status -> termination.get()); } + private WorldInstance requireLockedWorldInstance(long tenantId, long gameInstanceId) { + return worldInstanceRepository + .findByTenantIdAndGameInstanceIdForUpdate(tenantId, gameInstanceId) + .orElseThrow( + () -> + new IllegalArgumentException("WORLD_INSTANCE_NOT_FOUND: world instance not found")); + } + private void cleanupWorldRuntimeState(long tenantId, long gameInstanceId) { worldEventRepository.deleteByTenantIdAndGameInstanceId(tenantId, gameInstanceId); roomInstanceExitRepository.deleteByTenantIdAndGameInstanceId(tenantId, gameInstanceId); 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 cdaf3e1c7d..39566abf51 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 @@ -13,18 +13,24 @@ import net.firedevops.firemud.common.security.PublicationReadGuard; import net.firedevops.firemud.common.security.RequestIdValidation; import net.firedevops.firemud.common.security.SessionContext; +import net.firedevops.firemud.entitymanagement.v1.PlayableStateScope; import net.firedevops.firemud.shared.v1.RoomInstanceRef; +import net.firedevops.firemud.worldmanagement.dto.InitialAdmissionBindHoldDto; +import net.firedevops.firemud.worldmanagement.dto.InitialAdmissionBindHoldRequest; import net.firedevops.firemud.worldmanagement.dto.PreparedWorldInstanceRequest; import net.firedevops.firemud.worldmanagement.dto.RoomSnapshotDto; import net.firedevops.firemud.worldmanagement.dto.RoomSnapshotDto.RoomExitSnapshotDto; import net.firedevops.firemud.worldmanagement.dto.RuntimeRoomDto; import net.firedevops.firemud.worldmanagement.dto.WorldDesignMutationRequestDto; +import net.firedevops.firemud.worldmanagement.service.InitialAdmissionBindHoldService; import net.firedevops.firemud.worldmanagement.service.PingService; import net.firedevops.firemud.worldmanagement.service.RoomService; import net.firedevops.firemud.worldmanagement.service.WorldDesignMutationService; import net.firedevops.firemud.worldmanagement.service.WorldDraftDesignDigestService; import net.firedevops.firemud.worldmanagement.service.WorldInstanceActivationService; import net.firedevops.firemud.worldmanagement.service.WorldUpgradeValidationService; +import net.firedevops.firemud.worldmanagement.v1.AcquireInitialAdmissionBindHoldRequest; +import net.firedevops.firemud.worldmanagement.v1.AcquireInitialAdmissionBindHoldResponse; import net.firedevops.firemud.worldmanagement.v1.ActivatePreparedWorldInstanceRequest; import net.firedevops.firemud.worldmanagement.v1.ActivatePreparedWorldInstanceResponse; import net.firedevops.firemud.worldmanagement.v1.ApplyWorldDesignMutationRequest; @@ -43,6 +49,7 @@ import net.firedevops.firemud.worldmanagement.v1.GetRoomSnapshotResponse; import net.firedevops.firemud.worldmanagement.v1.GetWorldInstanceLifecycleRequest; import net.firedevops.firemud.worldmanagement.v1.GetWorldInstanceLifecycleResponse; +import net.firedevops.firemud.worldmanagement.v1.InitialAdmissionBindHoldStatus; import net.firedevops.firemud.worldmanagement.v1.PingRequest; import net.firedevops.firemud.worldmanagement.v1.PingResponse; import net.firedevops.firemud.worldmanagement.v1.PrepareWorldInstanceRequest; @@ -88,6 +95,8 @@ public class WorldManagementGrpcService private final MeterRegistry meterRegistry; private final ObjectMapper objectMapper; private final PublicationReadGuard publicationReadGuard; + private InitialAdmissionBindHoldService initialAdmissionBindHoldService; + private InitialAdmissionBindWorkloadGuard initialAdmissionBindWorkloadGuard; private WorldManagementGrpcService( PublicationReadGuard publicationReadGuard, @@ -137,6 +146,15 @@ public WorldManagementGrpcService( objectMapper); } + @Autowired + public void configureInitialAdmissionBindHoldBoundary( + InitialAdmissionBindHoldService holdService, + @Value("${firemud.grpc.workload-namespace:}") String workloadNamespace) { + this.initialAdmissionBindHoldService = holdService; + this.initialAdmissionBindWorkloadGuard = + new InitialAdmissionBindWorkloadGuard(workloadNamespace); + } + public WorldManagementGrpcService( PingService pingService, RoomService roomService, @@ -292,6 +310,59 @@ public void getWorldInstanceLifecycle( responseObserver.onCompleted(); } + @Override + @Timed(value = "worldGrpc.acquireInitialAdmissionBindHold") + public void acquireInitialAdmissionBindHold( + AcquireInitialAdmissionBindHoldRequest request, + StreamObserver responseObserver) { + AcquireInitialAdmissionBindHoldResponse.Builder builder = + AcquireInitialAdmissionBindHoldResponse.newBuilder(); + try { + if (initialAdmissionBindHoldService == null || initialAdmissionBindWorkloadGuard == null) { + throw new AdminAuthorizationException( + "Initial admission hold authorization is not configured"); + } + initialAdmissionBindWorkloadGuard.requireGameSessionAcquireCaller(); + var hold = + initialAdmissionBindHoldService.acquire( + new InitialAdmissionBindHoldRequest( + RequestIdValidation.requirePositiveLong(request.getTenantId(), "tenantId"), + RequestIdValidation.requirePositiveLong( + request.getGameInstanceId(), "gameInstanceId"), + RequestIdValidation.requirePositiveLong(request.getVersionId(), "versionId"), + request.getExpectedActiveLifecycleEpoch(), + request.getInitialAdmissionRequestId(), + request.getRequestDigest(), + request.getRealmUuid(), + request.getPlayableStateNamespaceUuid(), + normalizePlayableStateScope(request.getPlayableStateScope()), + request.getExpectedNoPriorPointer(), + request.getExpectedCatalogRevision())); + builder.setHold(toProto(hold)); + } catch (AdminAuthorizationException ex) { + builder.setError( + GrpcAppErrors.error( + meterRegistry, + logger, + "AcquireInitialAdmissionBindHold", + "PERMISSION_DENIED", + ex.getMessage())); + } catch (IllegalArgumentException ex) { + builder.setError( + GrpcAppErrors.error( + meterRegistry, + logger, + "AcquireInitialAdmissionBindHold", + errorCodeFor(ex), + errorMessageFor(ex))); + } catch (Exception ex) { + builder.setError( + GrpcAppErrors.internal(meterRegistry, logger, "AcquireInitialAdmissionBindHold", ex)); + } + responseObserver.onNext(builder.build()); + responseObserver.onCompleted(); + } + @Override @Timed(value = "worldGrpc.terminateWorldInstance") public void terminateWorldInstance( @@ -677,6 +748,57 @@ private WorldInstanceLifecycleSnapshot toProto( .build(); } + private net.firedevops.firemud.worldmanagement.v1.InitialAdmissionBindHold toProto( + InitialAdmissionBindHoldDto hold) { + return net.firedevops.firemud.worldmanagement.v1.InitialAdmissionBindHold.newBuilder() + .setHoldId(hold.holdId()) + .setHoldFence(hold.holdFence()) + .setTenantId(Long.toString(hold.tenantId())) + .setRealmUuid(hold.realmUuid()) + .setPlayableStateNamespaceUuid(hold.playableStateNamespaceUuid()) + .setPlayableStateScope(toProtoPlayableStateScope(hold.playableStateScope())) + .setGameInstanceId(Long.toString(hold.gameInstanceId())) + .setVersionId(Long.toString(hold.versionId())) + .setActiveLifecycleEpoch(hold.activeLifecycleEpoch()) + .setInitialAdmissionRequestId(hold.initialAdmissionRequestId()) + .setRequestDigest(hold.requestDigest()) + .setExpectedNoPriorPointer(hold.expectedNoPriorPointer()) + .setExpectedCatalogRevision(hold.expectedCatalogRevision()) + .setStatus(toProtoInitialAdmissionBindStatus(hold.status())) + .setDiagnosticExpiresAtEpochMillis(hold.diagnosticExpiresAt().toEpochMilli()) + .build(); + } + + private String normalizePlayableStateScope(PlayableStateScope scope) { + return switch (scope) { + case PLAYABLE_STATE_SCOPE_SHARED -> "SHARED"; + case PLAYABLE_STATE_SCOPE_ISOLATED -> "ISOLATED"; + default -> + throw new IllegalArgumentException( + "INVALID_ARGUMENT: playableStateScope must be SHARED or ISOLATED"); + }; + } + + private PlayableStateScope toProtoPlayableStateScope(String scope) { + return switch (scope) { + case "SHARED" -> PlayableStateScope.PLAYABLE_STATE_SCOPE_SHARED; + case "ISOLATED" -> PlayableStateScope.PLAYABLE_STATE_SCOPE_ISOLATED; + default -> throw new IllegalStateException("Unsupported persisted playable state scope"); + }; + } + + private InitialAdmissionBindHoldStatus toProtoInitialAdmissionBindStatus(String status) { + return switch (status) { + case "PENDING" -> InitialAdmissionBindHoldStatus.INITIAL_ADMISSION_BIND_HOLD_STATUS_PENDING; + case "RECONCILIATION_REQUIRED" -> + InitialAdmissionBindHoldStatus.INITIAL_ADMISSION_BIND_HOLD_STATUS_RECONCILIATION_REQUIRED; + case "COMMITTED" -> + InitialAdmissionBindHoldStatus.INITIAL_ADMISSION_BIND_HOLD_STATUS_COMMITTED; + case "ABORTED" -> InitialAdmissionBindHoldStatus.INITIAL_ADMISSION_BIND_HOLD_STATUS_ABORTED; + default -> InitialAdmissionBindHoldStatus.INITIAL_ADMISSION_BIND_HOLD_STATUS_UNSPECIFIED; + }; + } + private WorldInstanceLifecycleStatus toProtoStatus(String status) { return switch (status) { case "PREPARING" -> WorldInstanceLifecycleStatus.WORLD_INSTANCE_LIFECYCLE_STATUS_PREPARING; diff --git a/services/world-management-service/src/main/resources/db/migration/V23__initial_admission_bind_hold.sql b/services/world-management-service/src/main/resources/db/migration/V23__initial_admission_bind_hold.sql new file mode 100644 index 0000000000..09e21c0df4 --- /dev/null +++ b/services/world-management-service/src/main/resources/db/migration/V23__initial_admission_bind_hold.sql @@ -0,0 +1,69 @@ +CREATE TABLE initial_admission_bind_hold ( + hold_id UUID PRIMARY KEY, + hold_fence UUID NOT NULL UNIQUE, + tenant_id BIGINT NOT NULL CHECK (tenant_id > 0), + realm_uuid UUID NOT NULL, + playable_state_namespace_uuid UUID NOT NULL, + playable_state_scope VARCHAR(16) NOT NULL + CHECK (playable_state_scope IN ('SHARED', 'ISOLATED')), + game_instance_id BIGINT NOT NULL CHECK (game_instance_id > 0), + version_id BIGINT NOT NULL CHECK (version_id > 0), + active_lifecycle_epoch BIGINT NOT NULL CHECK (active_lifecycle_epoch > 0), + initial_admission_request_id VARCHAR(128) NOT NULL + CHECK (BTRIM(initial_admission_request_id) <> ''), + request_digest CHAR(64) NOT NULL CHECK (request_digest ~ '^[0-9a-f]{64}$'), + expected_no_prior_pointer BOOLEAN NOT NULL CHECK (expected_no_prior_pointer), + expected_catalog_revision BIGINT NOT NULL CHECK (expected_catalog_revision > 0), + status VARCHAR(32) NOT NULL + CHECK (status IN ('PENDING', 'RECONCILIATION_REQUIRED', 'COMMITTED', 'ABORTED')), + diagnostic_expires_at TIMESTAMP NOT NULL, + owner_proof_id VARCHAR(128), + owner_proof_digest CHAR(64), + owner_pointer_audit_id VARCHAR(128), + owner_pointer_version BIGINT, + reconciliation_error VARCHAR(128), + created_at TIMESTAMP NOT NULL DEFAULT CURRENT_TIMESTAMP, + updated_at TIMESTAMP NOT NULL DEFAULT CURRENT_TIMESTAMP, + terminal_at TIMESTAMP, + row_version BIGINT NOT NULL DEFAULT 0, + CONSTRAINT uk_initial_admission_bind_request + UNIQUE (tenant_id, initial_admission_request_id), + CONSTRAINT fk_initial_admission_bind_world_instance + FOREIGN KEY (tenant_id, game_instance_id) + REFERENCES world_instance (tenant_id, game_instance_id), + CONSTRAINT ck_initial_admission_bind_owner_proof + CHECK ( + (status IN ('PENDING', 'RECONCILIATION_REQUIRED') + AND owner_proof_id IS NULL + AND owner_proof_digest IS NULL + AND owner_pointer_audit_id IS NULL + AND owner_pointer_version IS NULL + AND terminal_at IS NULL) + OR (status = 'COMMITTED' + AND owner_proof_id IS NOT NULL + AND BTRIM(owner_proof_id) <> '' + AND owner_proof_digest IS NOT NULL + AND owner_proof_digest ~ '^[0-9a-f]{64}$' + AND owner_pointer_audit_id IS NOT NULL + AND BTRIM(owner_pointer_audit_id) <> '' + AND owner_pointer_version IS NOT NULL + AND owner_pointer_version > 0 + AND terminal_at IS NOT NULL) + OR (status = 'ABORTED' + AND owner_proof_id IS NOT NULL + AND BTRIM(owner_proof_id) <> '' + AND owner_proof_digest IS NOT NULL + AND owner_proof_digest ~ '^[0-9a-f]{64}$' + AND owner_pointer_audit_id IS NULL + AND owner_pointer_version IS NULL + AND terminal_at IS NOT NULL) + ) +); + +CREATE UNIQUE INDEX uk_initial_admission_bind_active_realm + ON initial_admission_bind_hold (tenant_id, realm_uuid) + WHERE status IN ('PENDING', 'RECONCILIATION_REQUIRED'); + +CREATE INDEX idx_initial_admission_bind_reconcile + ON initial_admission_bind_hold (updated_at, hold_id) + WHERE status IN ('PENDING', 'RECONCILIATION_REQUIRED'); diff --git a/services/world-management-service/src/test/java/integration/net/firedevops/firemud/worldmanagement/InitialAdmissionBindHoldPostgresIntegrationTest.java b/services/world-management-service/src/test/java/integration/net/firedevops/firemud/worldmanagement/InitialAdmissionBindHoldPostgresIntegrationTest.java new file mode 100644 index 0000000000..77831ad9e6 --- /dev/null +++ b/services/world-management-service/src/test/java/integration/net/firedevops/firemud/worldmanagement/InitialAdmissionBindHoldPostgresIntegrationTest.java @@ -0,0 +1,248 @@ +package net.firedevops.firemud.worldmanagement; + +import static org.assertj.core.api.Assertions.assertThat; +import static org.assertj.core.api.Assertions.assertThatThrownBy; +import static org.mockito.ArgumentMatchers.anyLong; +import static org.mockito.ArgumentMatchers.anyString; +import static org.mockito.Mockito.doAnswer; + +import java.util.UUID; +import java.util.concurrent.CountDownLatch; +import java.util.concurrent.ExecutorService; +import java.util.concurrent.Executors; +import java.util.concurrent.Future; +import java.util.concurrent.TimeUnit; +import net.firedevops.firemud.entitymanagement.v1.CleanupRuntimeInstanceResponse; +import net.firedevops.firemud.test.PostgresBackedServiceTestSupport; +import net.firedevops.firemud.worldmanagement.client.EntityManagementClient; +import net.firedevops.firemud.worldmanagement.client.GameDesignClient; +import net.firedevops.firemud.worldmanagement.client.GameSessionClient; +import net.firedevops.firemud.worldmanagement.dto.InitialAdmissionBindHoldRequest; +import net.firedevops.firemud.worldmanagement.jooq.tables.WorldInstance; +import net.firedevops.firemud.worldmanagement.jooq.tables.records.WorldInstanceRecord; +import net.firedevops.firemud.worldmanagement.repository.InitialAdmissionBindHoldRepository; +import net.firedevops.firemud.worldmanagement.repository.WorldInstanceRepository; +import net.firedevops.firemud.worldmanagement.service.InitialAdmissionBindHoldService; +import net.firedevops.firemud.worldmanagement.service.WorldLifecycleCommandService; +import net.firedevops.firemud.worldmanagement.service.impl.InitialAdmissionBindHoldServiceImpl; +import org.jooq.DSLContext; +import org.junit.jupiter.api.Test; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.boot.test.context.SpringBootTest; +import org.springframework.grpc.server.lifecycle.GrpcServerLifecycle; +import org.springframework.test.context.DynamicPropertyRegistry; +import org.springframework.test.context.DynamicPropertySource; +import org.springframework.test.context.bean.override.mockito.MockitoBean; +import org.springframework.transaction.PlatformTransactionManager; +import org.springframework.transaction.support.TransactionTemplate; +import org.testcontainers.containers.GenericContainer; +import org.testcontainers.containers.PostgreSQLContainer; +import org.testcontainers.junit.jupiter.Container; +import org.testcontainers.junit.jupiter.Testcontainers; + +@Testcontainers(disabledWithoutDocker = true) +@SuppressWarnings("resource") +@SpringBootTest( + classes = WorldManagementServiceApplication.class, + properties = {"spring.grpc.server.port=0"}) +class InitialAdmissionBindHoldPostgresIntegrationTest { + @Container + static PostgreSQLContainer postgres = new PostgreSQLContainer<>("postgres:16-alpine"); + + @Container + static GenericContainer redis = + new GenericContainer<>("redis:7.2-alpine").withExposedPorts(6379); + + @DynamicPropertySource + static void configure(DynamicPropertyRegistry registry) { + PostgresBackedServiceTestSupport.registerPostgresService( + registry, postgres, "world_management_service"); + PostgresBackedServiceTestSupport.registerRedisService(registry, redis); + } + + @Autowired private DSLContext dsl; + @Autowired private WorldInstanceRepository worldInstanceRepository; + @Autowired private InitialAdmissionBindHoldRepository holdRepository; + @Autowired private InitialAdmissionBindHoldService holdService; + @Autowired private WorldLifecycleCommandService lifecycleCommandService; + @Autowired private PlatformTransactionManager transactionManager; + + @MockitoBean private GrpcServerLifecycle grpcServerLifecycle; + @MockitoBean private GameDesignClient gameDesignClient; + @MockitoBean private GameSessionClient gameSessionClient; + @MockitoBean private EntityManagementClient entityManagementClient; + + @Test + void holdAcquireWinsConcurrentTerminationAndExactRetrySurvivesServiceRecreation() + throws Exception { + long tenantId = 81001L; + long gameInstanceId = uniqueGameInstanceId(); + insertActiveWorldInstance(tenantId, gameInstanceId); + InitialAdmissionBindHoldRequest request = request(tenantId, gameInstanceId); + CountDownLatch lifecycleLocked = new CountDownLatch(1); + CountDownLatch allowAcquireCommit = new CountDownLatch(1); + TransactionTemplate transactionTemplate = new TransactionTemplate(transactionManager); + + try (ExecutorService executor = Executors.newFixedThreadPool(2)) { + Future acquireFuture = + executor.submit( + () -> + transactionTemplate.execute( + status -> { + worldInstanceRepository + .findByTenantIdAndGameInstanceIdForUpdate(tenantId, gameInstanceId) + .orElseThrow(); + lifecycleLocked.countDown(); + await(allowAcquireCommit); + return holdService.acquire(request); + })); + assertThat(lifecycleLocked.await(5, TimeUnit.SECONDS)).isTrue(); + + CountDownLatch terminationStarted = new CountDownLatch(1); + Future terminationFuture = + executor.submit( + () -> { + terminationStarted.countDown(); + try { + lifecycleCommandService.terminateWorldInstance( + tenantId, gameInstanceId, 4L, "terminate-race-1", "race"); + return "unexpected termination success"; + } catch (IllegalArgumentException exception) { + return exception.getMessage(); + } + }); + assertThat(terminationStarted.await(5, TimeUnit.SECONDS)).isTrue(); + allowAcquireCommit.countDown(); + + var acquired = acquireFuture.get(10, TimeUnit.SECONDS); + String terminationResult = terminationFuture.get(10, TimeUnit.SECONDS); + assertThat(acquired).isNotNull(); + assertThat(terminationResult).startsWith("INITIAL_ADMISSION_BIND_HOLD_ACTIVE:"); + InitialAdmissionBindHoldServiceImpl restartedService = + new InitialAdmissionBindHoldServiceImpl(holdRepository, worldInstanceRepository); + var retry = transactionTemplate.execute(status -> restartedService.acquire(request)); + assertThat(retry).isNotNull(); + assertThat(retry.holdId()).isEqualTo(acquired.holdId()); + assertThat(retry.holdFence()).isEqualTo(acquired.holdFence()); + } finally { + allowAcquireCommit.countDown(); + deleteFixture(tenantId, gameInstanceId); + } + } + + @Test + void terminationWinsRaceAndLaterAcquireCannotCreateAnInitialHold() throws Exception { + long tenantId = 81002L; + long gameInstanceId = uniqueGameInstanceId(); + insertActiveWorldInstance(tenantId, gameInstanceId); + CountDownLatch ownerCleanupCalled = new CountDownLatch(1); + CountDownLatch allowOwnerCleanup = new CountDownLatch(1); + doAnswer( + invocation -> { + ownerCleanupCalled.countDown(); + await(allowOwnerCleanup); + return CleanupRuntimeInstanceResponse.newBuilder().build(); + }) + .when(entityManagementClient) + .cleanupRuntimeInstance(anyLong(), anyLong(), anyString()); + + try (ExecutorService executor = Executors.newSingleThreadExecutor()) { + Future termination = + executor.submit( + () -> + lifecycleCommandService.terminateWorldInstance( + tenantId, gameInstanceId, 4L, "terminate-race-2", "race")); + assertThat(ownerCleanupCalled.await(5, TimeUnit.SECONDS)).isTrue(); + + assertThatThrownBy(() -> holdService.acquire(request(tenantId, gameInstanceId))) + .isInstanceOf(IllegalArgumentException.class) + .hasMessageStartingWith("WORLD_LIFECYCLE_PROOF_MISMATCH:"); + allowOwnerCleanup.countDown(); + termination.get(10, TimeUnit.SECONDS); + } finally { + allowOwnerCleanup.countDown(); + deleteFixture(tenantId, gameInstanceId); + } + } + + @Test + void reconciliationRequiredHoldContinuesToBlockTermination() { + long tenantId = 81003L; + long gameInstanceId = uniqueGameInstanceId(); + insertActiveWorldInstance(tenantId, gameInstanceId); + try { + var acquired = holdService.acquire(request(tenantId, gameInstanceId)); + holdService.requireReconciliation(acquired.holdId(), "GS_OWNER_READ_UNAVAILABLE"); + + assertThatThrownBy( + () -> + lifecycleCommandService.terminateWorldInstance( + tenantId, gameInstanceId, 4L, "terminate-held-1", "stop")) + .isInstanceOf(IllegalArgumentException.class) + .hasMessageStartingWith("INITIAL_ADMISSION_BIND_HOLD_ACTIVE:"); + } finally { + deleteFixture(tenantId, gameInstanceId); + } + } + + private void insertActiveWorldInstance(long tenantId, long gameInstanceId) { + var table = WorldInstance.WORLD_INSTANCE; + WorldInstanceRecord record = dsl.newRecord(table); + record.setTenantId(tenantId); + record.setGameInstanceId(gameInstanceId); + record.setGameTemplateId(81L); + record.setControlPlaneRequestId("initial-bind-test-" + gameInstanceId); + record.setLaunchDescriptorId("initial-bind-launch"); + record.setVersionId(71L); + record.setGenerationConfigRevision("initial-bind-generation"); + record.setReleaseBundleId(91L); + record.setPublishedReleaseBundleRef("initial-bind-release"); + record.setVersionStateEpoch(31L); + record.setLifecycleEpoch(4L); + record.setStatus("ACTIVE"); + record.setRowVersion(0L); + record.store(); + } + + private InitialAdmissionBindHoldRequest request(long tenantId, long gameInstanceId) { + return new InitialAdmissionBindHoldRequest( + tenantId, + gameInstanceId, + 71L, + 4L, + "initial-bind-request-" + gameInstanceId, + "f".repeat(64), + UUID.randomUUID().toString(), + UUID.randomUUID().toString(), + "SHARED", + true, + 1L); + } + + private long uniqueGameInstanceId() { + return Math.abs(System.nanoTime()) + 10_000L; + } + + private void deleteFixture(long tenantId, long gameInstanceId) { + dsl.execute( + "DELETE FROM initial_admission_bind_hold WHERE tenant_id = ? AND game_instance_id = ?", + tenantId, + gameInstanceId); + dsl.deleteFrom(WorldInstance.WORLD_INSTANCE) + .where( + WorldInstance.WORLD_INSTANCE + .TENANT_ID + .eq(tenantId) + .and(WorldInstance.WORLD_INSTANCE.GAME_INSTANCE_ID.eq(gameInstanceId))) + .execute(); + } + + private static void await(CountDownLatch latch) { + try { + assertThat(latch.await(10, TimeUnit.SECONDS)).isTrue(); + } catch (InterruptedException exception) { + Thread.currentThread().interrupt(); + throw new AssertionError("Interrupted while coordinating PostgreSQL race", exception); + } + } +} diff --git a/services/world-management-service/src/test/java/unit/net/firedevops/firemud/worldmanagement/service/impl/InitialAdmissionBindHoldServiceImplTest.java b/services/world-management-service/src/test/java/unit/net/firedevops/firemud/worldmanagement/service/impl/InitialAdmissionBindHoldServiceImplTest.java new file mode 100644 index 0000000000..2143e36d69 --- /dev/null +++ b/services/world-management-service/src/test/java/unit/net/firedevops/firemud/worldmanagement/service/impl/InitialAdmissionBindHoldServiceImplTest.java @@ -0,0 +1,411 @@ +package net.firedevops.firemud.worldmanagement.service.impl; + +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertNotEquals; +import static org.junit.jupiter.api.Assertions.assertThrows; +import static org.junit.jupiter.api.Assertions.assertTrue; +import static org.mockito.ArgumentMatchers.any; +import static org.mockito.Mockito.never; +import static org.mockito.Mockito.verify; +import static org.mockito.Mockito.when; + +import java.time.Instant; +import java.util.Optional; +import java.util.concurrent.atomic.AtomicReference; +import net.firedevops.firemud.worldmanagement.dto.InitialAdmissionBindHoldRequest; +import net.firedevops.firemud.worldmanagement.dto.InitialAdmissionBindOwnerProof; +import net.firedevops.firemud.worldmanagement.dto.InitialAdmissionBindOwnerProof.Outcome; +import net.firedevops.firemud.worldmanagement.entity.InitialAdmissionBindHold; +import net.firedevops.firemud.worldmanagement.entity.WorldInstance; +import net.firedevops.firemud.worldmanagement.repository.InitialAdmissionBindHoldRepository; +import net.firedevops.firemud.worldmanagement.repository.WorldInstanceRepository; +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Test; +import org.mockito.Mockito; + +class InitialAdmissionBindHoldServiceImplTest { + private static final long TENANT_ID = 42L; + private static final long GAME_INSTANCE_ID = 101L; + private static final long VERSION_ID = 11L; + private static final long ACTIVE_EPOCH = 7L; + private static final String REQUEST_ID = "initial-admission-1"; + private static final String REQUEST_DIGEST = "a".repeat(64); + private static final String REALM_UUID = "00000000-0000-0000-0000-000000000001"; + private static final String NAMESPACE_UUID = "00000000-0000-0000-0000-000000000002"; + private static final String HOLD_ID = "00000000-0000-0000-0000-000000000003"; + private static final String HOLD_FENCE = "00000000-0000-0000-0000-000000000004"; + + private InitialAdmissionBindHoldRepository holdRepository; + private WorldInstanceRepository worldInstanceRepository; + private InitialAdmissionBindHoldServiceImpl service; + + @BeforeEach + void setUp() { + holdRepository = Mockito.mock(InitialAdmissionBindHoldRepository.class); + worldInstanceRepository = Mockito.mock(WorldInstanceRepository.class); + service = new InitialAdmissionBindHoldServiceImpl(holdRepository, worldInstanceRepository); + when(worldInstanceRepository.findByTenantIdAndGameInstanceIdForUpdate( + TENANT_ID, GAME_INSTANCE_ID)) + .thenReturn(Optional.of(activeWorldInstance())); + } + + @Test + void acquireAllocatesOpaqueHoldAndExactRetryReusesItsIdentity() { + AtomicReference persisted = new AtomicReference<>(); + when(holdRepository.findByTenantIdAndRequestId(TENANT_ID, REQUEST_ID)) + .thenAnswer(invocation -> Optional.ofNullable(persisted.get())); + when(holdRepository.hasNonterminalForRealm(TENANT_ID, REALM_UUID)).thenReturn(false); + when(holdRepository.insertIfNoUniqueConflict(any())) + .thenAnswer( + invocation -> { + InitialAdmissionBindHold hold = invocation.getArgument(0); + persisted.set(hold); + return Optional.of(hold); + }); + + var first = service.acquire(request()); + var retry = service.acquire(request()); + + assertEquals("PENDING", first.status()); + assertNotEquals(REQUEST_ID, first.holdId()); + assertNotEquals(first.holdId(), first.holdFence()); + assertEquals(first.holdId(), retry.holdId()); + assertEquals(first.holdFence(), retry.holdFence()); + assertEquals(REALM_UUID, retry.realmUuid()); + assertEquals(NAMESPACE_UUID, retry.playableStateNamespaceUuid()); + assertEquals(17L, retry.expectedCatalogRevision()); + verify(worldInstanceRepository, Mockito.times(2)) + .findByTenantIdAndGameInstanceIdForUpdate(TENANT_ID, GAME_INSTANCE_ID); + } + + @Test + void acquireRejectsChangedRequestDigestForTheSameStableRequestId() { + when(holdRepository.findByTenantIdAndRequestId(TENANT_ID, REQUEST_ID)) + .thenReturn(Optional.of(pendingHold())); + + IllegalArgumentException error = + assertThrows( + IllegalArgumentException.class, + () -> + service.acquire( + new InitialAdmissionBindHoldRequest( + TENANT_ID, + GAME_INSTANCE_ID, + VERSION_ID, + ACTIVE_EPOCH, + REQUEST_ID, + "b".repeat(64), + REALM_UUID, + NAMESPACE_UUID, + "SHARED", + true, + 17L))); + + assertTrue(error.getMessage().startsWith("IDEMPOTENCY_CONFLICT:")); + verify(holdRepository, never()).insertIfNoUniqueConflict(any()); + } + + @Test + void acquireRejectsASecondNonterminalHoldForTheRealm() { + when(holdRepository.findByTenantIdAndRequestId(TENANT_ID, REQUEST_ID)) + .thenReturn(Optional.empty()); + when(holdRepository.hasNonterminalForRealm(TENANT_ID, REALM_UUID)).thenReturn(true); + + IllegalArgumentException error = + assertThrows(IllegalArgumentException.class, () -> service.acquire(request())); + + assertTrue(error.getMessage().startsWith("INITIAL_ADMISSION_BIND_HOLD_CONFLICT:")); + verify(holdRepository, never()).insertIfNoUniqueConflict(any()); + } + + @Test + void acquireRejectsAnUnsupportedPlayableStateScope() { + InitialAdmissionBindHoldRequest invalidScopeRequest = + new InitialAdmissionBindHoldRequest( + TENANT_ID, + GAME_INSTANCE_ID, + VERSION_ID, + ACTIVE_EPOCH, + REQUEST_ID, + REQUEST_DIGEST, + REALM_UUID, + NAMESPACE_UUID, + "PLAYABLE_STATE", + true, + 17L); + + IllegalArgumentException error = + assertThrows(IllegalArgumentException.class, () -> service.acquire(invalidScopeRequest)); + + assertTrue(error.getMessage().startsWith("INVALID_ARGUMENT:")); + verify(worldInstanceRepository, never()) + .findByTenantIdAndGameInstanceIdForUpdate(TENANT_ID, GAME_INSTANCE_ID); + } + + @Test + void pendingOwnerReadMovesHoldToBlockingReconciliationRequired() { + InitialAdmissionBindHold hold = pendingHold(); + when(holdRepository.findByHoldId(HOLD_ID)).thenReturn(Optional.of(hold)); + when(holdRepository.findByHoldIdForUpdate(HOLD_ID)).thenReturn(Optional.of(hold)); + when(holdRepository.markReconciliationRequired(any(), Mockito.eq("GS_OWNER_PENDING"), any())) + .thenAnswer(invocation -> Optional.of(withStatus(hold, "RECONCILIATION_REQUIRED", 1L))); + + var result = + service.reconcileOwnerProof(HOLD_ID, ownerProof(Outcome.PENDING, false, false, null)); + + assertEquals("RECONCILIATION_REQUIRED", result.status()); + verify(holdRepository, never()) + .recordTerminalProof(any(), any(), any(), any(), any(), any(), any()); + } + + @Test + void committedReadbackRequiresExactPointerAuditDigest() { + InitialAdmissionBindHold hold = pendingHold(); + when(holdRepository.findByHoldId(HOLD_ID)).thenReturn(Optional.of(hold)); + when(holdRepository.findByHoldIdForUpdate(HOLD_ID)).thenReturn(Optional.of(hold)); + when(holdRepository.markReconciliationRequired( + any(), Mockito.eq("GS_OWNER_TERMINAL_PROOF_INCOMPLETE"), any())) + .thenAnswer(invocation -> Optional.of(withStatus(hold, "RECONCILIATION_REQUIRED", 1L))); + + var result = + service.reconcileOwnerProof( + HOLD_ID, ownerProof(Outcome.COMMITTED, true, true, "c".repeat(64))); + + assertEquals("RECONCILIATION_REQUIRED", result.status()); + verify(worldInstanceRepository, never()) + .findByTenantIdAndGameInstanceIdForUpdate(TENANT_ID, GAME_INSTANCE_ID); + verify(holdRepository, never()) + .recordTerminalProof(any(), any(), any(), any(), any(), any(), any()); + } + + @Test + void exactCommittedPointerAndAuditReadbackTerminalizesAndReplays() { + InitialAdmissionBindHold pending = pendingHold(); + AtomicReference persisted = new AtomicReference<>(pending); + when(holdRepository.findByHoldId(HOLD_ID)) + .thenAnswer(invocation -> Optional.of(persisted.get())); + when(holdRepository.findByHoldIdForUpdate(HOLD_ID)) + .thenAnswer(invocation -> Optional.of(persisted.get())); + when(worldInstanceRepository.findByTenantIdAndGameInstanceIdForUpdate( + TENANT_ID, GAME_INSTANCE_ID)) + .thenReturn(Optional.of(activeWorldInstance())); + when(holdRepository.recordTerminalProof( + any(), + Mockito.eq("COMMITTED"), + Mockito.eq("gs-ledger-100"), + any(), + Mockito.eq("audit-100"), + Mockito.eq(1L), + any())) + .thenAnswer( + invocation -> { + InitialAdmissionBindHold committed = + withTerminalProof( + pending, + ownerProof(Outcome.COMMITTED, true, true, REQUEST_DIGEST), + invocation.getArgument(3)); + persisted.set(committed); + return Optional.of(committed); + }); + + var first = + service.reconcileOwnerProof( + HOLD_ID, ownerProof(Outcome.COMMITTED, true, true, REQUEST_DIGEST)); + var retry = + service.reconcileOwnerProof( + HOLD_ID, ownerProof(Outcome.COMMITTED, true, true, REQUEST_DIGEST)); + + assertEquals("COMMITTED", first.status()); + assertEquals(first, retry); + verify(holdRepository, Mockito.times(1)) + .recordTerminalProof(any(), any(), any(), any(), any(), any(), any()); + } + + @Test + void abortedAttemptRequiresDurableTombstoneAndPreventsFutureCommit() { + InitialAdmissionBindHold pending = pendingHold(); + when(holdRepository.findByHoldId(HOLD_ID)).thenReturn(Optional.of(pending)); + when(holdRepository.findByHoldIdForUpdate(HOLD_ID)).thenReturn(Optional.of(pending)); + when(holdRepository.markReconciliationRequired( + any(), Mockito.eq("GS_OWNER_TERMINAL_PROOF_INCOMPLETE"), any())) + .thenAnswer(invocation -> Optional.of(withStatus(pending, "RECONCILIATION_REQUIRED", 1L))); + + var result = + service.reconcileOwnerProof(HOLD_ID, ownerProof(Outcome.ABORTED, false, false, null)); + + assertEquals("RECONCILIATION_REQUIRED", result.status()); + verify(holdRepository, never()) + .recordTerminalProof(any(), any(), any(), any(), any(), any(), any()); + } + + @Test + void exactAbortedTombstoneDoesNotRequirePriorPointerAbsence() { + InitialAdmissionBindHold pending = pendingHold(); + InitialAdmissionBindOwnerProof proof = ownerProof(Outcome.ABORTED, false, true, null); + when(holdRepository.findByHoldId(HOLD_ID)).thenReturn(Optional.of(pending)); + when(holdRepository.findByHoldIdForUpdate(HOLD_ID)).thenReturn(Optional.of(pending)); + when(worldInstanceRepository.findByTenantIdAndGameInstanceIdForUpdate( + TENANT_ID, GAME_INSTANCE_ID)) + .thenReturn(Optional.of(activeWorldInstance())); + when(holdRepository.recordTerminalProof( + any(), + Mockito.eq("ABORTED"), + Mockito.eq("gs-ledger-100"), + any(), + Mockito.isNull(), + Mockito.isNull(), + any())) + .thenAnswer( + invocation -> + Optional.of(withTerminalProof(pending, proof, invocation.getArgument(3)))); + + var result = service.reconcileOwnerProof(HOLD_ID, proof); + + assertEquals("ABORTED", result.status()); + verify(holdRepository) + .recordTerminalProof( + any(), Mockito.eq("ABORTED"), any(), any(), Mockito.isNull(), Mockito.isNull(), any()); + } + + private InitialAdmissionBindHoldRequest request() { + return new InitialAdmissionBindHoldRequest( + TENANT_ID, + GAME_INSTANCE_ID, + VERSION_ID, + ACTIVE_EPOCH, + REQUEST_ID, + REQUEST_DIGEST, + REALM_UUID, + NAMESPACE_UUID, + "SHARED", + true, + 17L); + } + + private WorldInstance activeWorldInstance() { + WorldInstance worldInstance = new WorldInstance(); + worldInstance.setTenantId(TENANT_ID); + worldInstance.setGameInstanceId(GAME_INSTANCE_ID); + worldInstance.setVersionId(VERSION_ID); + worldInstance.setLifecycleEpoch(ACTIVE_EPOCH); + worldInstance.setStatus("ACTIVE"); + return worldInstance; + } + + private InitialAdmissionBindHold pendingHold() { + Instant now = Instant.parse("2026-09-01T00:00:00Z"); + return new InitialAdmissionBindHold( + HOLD_ID, + HOLD_FENCE, + TENANT_ID, + REALM_UUID, + NAMESPACE_UUID, + "SHARED", + GAME_INSTANCE_ID, + VERSION_ID, + ACTIVE_EPOCH, + REQUEST_ID, + REQUEST_DIGEST, + true, + 17L, + "PENDING", + now.plusSeconds(300), + null, + null, + null, + null, + null, + now, + now, + null, + 0L); + } + + private InitialAdmissionBindOwnerProof ownerProof( + Outcome outcome, + boolean attemptPointerAbsent, + boolean futureCommitPrevented, + String auditDigest) { + return new InitialAdmissionBindOwnerProof( + outcome, + HOLD_ID, + HOLD_FENCE, + TENANT_ID, + REALM_UUID, + NAMESPACE_UUID, + "SHARED", + GAME_INSTANCE_ID, + VERSION_ID, + ACTIVE_EPOCH, + REQUEST_ID, + REQUEST_DIGEST, + true, + 17L, + "gs-ledger-100", + outcome == Outcome.COMMITTED ? "audit-100" : null, + outcome == Outcome.COMMITTED ? 1L : 0L, + auditDigest, + attemptPointerAbsent, + futureCommitPrevented); + } + + private InitialAdmissionBindHold withStatus( + InitialAdmissionBindHold hold, String status, long rowVersion) { + return new InitialAdmissionBindHold( + hold.holdId(), + hold.holdFence(), + hold.tenantId(), + hold.realmUuid(), + hold.playableStateNamespaceUuid(), + hold.playableStateScope(), + hold.gameInstanceId(), + hold.versionId(), + hold.activeLifecycleEpoch(), + hold.initialAdmissionRequestId(), + hold.requestDigest(), + hold.expectedNoPriorPointer(), + hold.expectedCatalogRevision(), + status, + hold.diagnosticExpiresAt(), + hold.ownerProofId(), + hold.ownerProofDigest(), + hold.ownerPointerAuditId(), + hold.ownerPointerVersion(), + "GS_OWNER_PENDING", + hold.createdAt(), + hold.updatedAt(), + hold.terminalAt(), + rowVersion); + } + + private InitialAdmissionBindHold withTerminalProof( + InitialAdmissionBindHold hold, + InitialAdmissionBindOwnerProof proof, + String ownerProofDigest) { + return new InitialAdmissionBindHold( + hold.holdId(), + hold.holdFence(), + hold.tenantId(), + hold.realmUuid(), + hold.playableStateNamespaceUuid(), + hold.playableStateScope(), + hold.gameInstanceId(), + hold.versionId(), + hold.activeLifecycleEpoch(), + hold.initialAdmissionRequestId(), + hold.requestDigest(), + hold.expectedNoPriorPointer(), + hold.expectedCatalogRevision(), + proof.outcome().name(), + hold.diagnosticExpiresAt(), + proof.ownerProofId(), + ownerProofDigest, + proof.pointerAuditId(), + proof.pointerVersion() == 0L ? null : proof.pointerVersion(), + null, + hold.createdAt(), + hold.updatedAt(), + Instant.parse("2026-09-01T00:00:01Z"), + hold.rowVersion() + 1L); + } +} diff --git a/services/world-management-service/src/test/java/unit/net/firedevops/firemud/worldmanagement/service/impl/WorldLifecycleCommandServiceImplTest.java b/services/world-management-service/src/test/java/unit/net/firedevops/firemud/worldmanagement/service/impl/WorldLifecycleCommandServiceImplTest.java index 6a73afb9e4..d7ba28c7e4 100644 --- a/services/world-management-service/src/test/java/unit/net/firedevops/firemud/worldmanagement/service/impl/WorldLifecycleCommandServiceImplTest.java +++ b/services/world-management-service/src/test/java/unit/net/firedevops/firemud/worldmanagement/service/impl/WorldLifecycleCommandServiceImplTest.java @@ -6,6 +6,8 @@ import static org.junit.jupiter.api.Assertions.assertThrows; import static org.junit.jupiter.api.Assertions.assertTrue; import static org.mockito.ArgumentMatchers.any; +import static org.mockito.ArgumentMatchers.anyLong; +import static org.mockito.ArgumentMatchers.anyString; import static org.mockito.Mockito.doThrow; import static org.mockito.Mockito.mock; import static org.mockito.Mockito.verify; @@ -285,6 +287,30 @@ void terminateWorldInstanceDoesNotCommitTerminationWhenWorldCleanupFails() { verify(roomInstanceExitRepository).deleteByTenantIdAndGameInstanceId(42L, 101L); } + @Test + void terminationDoesNotCrossAnUnresolvedInitialAdmissionBindHold() { + WorldInstance instance = activeWorldInstance(); + stubPersistedWorldInstance(instance); + when(worldInstanceRepository.hasNonterminalInitialAdmissionBindHold(42L, 101L)) + .thenAnswer( + invocation -> { + assertTrue(localTransactionActive.get()); + return true; + }); + + IllegalArgumentException error = + assertThrows( + IllegalArgumentException.class, + () -> service.terminateWorldInstance(42L, 101L, 2L, "term-1", "stop")); + + assertTrue(error.getMessage().startsWith("INITIAL_ADMISSION_BIND_HOLD_ACTIVE:")); + assertEquals("ACTIVE", instance.getStatus()); + verify(entityManagementClient, org.mockito.Mockito.never()) + .cleanupRuntimeInstance(anyLong(), anyLong(), anyString()); + verify(worldInstanceRepository).findByTenantIdAndGameInstanceIdForUpdate(42L, 101L); + verify(worldInstanceRepository, org.mockito.Mockito.never()).save(any(WorldInstance.class)); + } + @Test void terminateWorldInstanceRetriesSameRequestAfterLocalCleanupFailure() { WorldInstance instance = activeWorldInstance(); @@ -430,6 +456,8 @@ void terminationFinalizationPropagatesOptimisticWriteFailure() { terminating.setLifecycleEpoch(3L); when(worldInstanceRepository.findByTenantIdAndGameInstanceId(42L, 101L)) .thenReturn(Optional.of(instance), Optional.of(terminating)); + when(worldInstanceRepository.findByTenantIdAndGameInstanceIdForUpdate(42L, 101L)) + .thenReturn(Optional.of(instance), Optional.of(terminating)); when(worldInstanceRepository.save(any(WorldInstance.class))) .thenAnswer( invocation -> { @@ -598,6 +626,17 @@ private AtomicReference stubPersistedWorldInstance(WorldInstance } return Optional.of(copyWorldInstance(persisted.get())); }); + AtomicBoolean firstLockedFind = new AtomicBoolean(true); + when(worldInstanceRepository.findByTenantIdAndGameInstanceIdForUpdate(42L, 101L)) + .thenAnswer( + invocation -> { + if (localTransactionActive.get()) { + worldInstanceReadInLocalTransaction.set(true); + } + return firstLockedFind.compareAndSet(true, false) + ? Optional.of(initiallyLoaded) + : Optional.of(copyWorldInstance(persisted.get())); + }); when(worldInstanceRepository.save(any(WorldInstance.class))) .thenAnswer( invocation -> { diff --git a/services/world-management-service/src/test/java/unit/net/firedevops/firemud/worldmanagement/service/impl/WorldManagementGrpcServiceTest.java b/services/world-management-service/src/test/java/unit/net/firedevops/firemud/worldmanagement/service/impl/WorldManagementGrpcServiceTest.java index fbfd3d491d..f7eac74fc5 100644 --- a/services/world-management-service/src/test/java/unit/net/firedevops/firemud/worldmanagement/service/impl/WorldManagementGrpcServiceTest.java +++ b/services/world-management-service/src/test/java/unit/net/firedevops/firemud/worldmanagement/service/impl/WorldManagementGrpcServiceTest.java @@ -18,17 +18,22 @@ import net.firedevops.firemud.common.security.GameplaySessionAttestationService; import net.firedevops.firemud.common.security.PublicationReadGuard; import net.firedevops.firemud.common.security.SessionContext; +import net.firedevops.firemud.entitymanagement.v1.PlayableStateScope; import net.firedevops.firemud.shared.v1.RoomInstanceRef; +import net.firedevops.firemud.worldmanagement.dto.InitialAdmissionBindHoldDto; import net.firedevops.firemud.worldmanagement.dto.RoomSnapshotDto; import net.firedevops.firemud.worldmanagement.dto.RuntimeRoomDto; import net.firedevops.firemud.worldmanagement.dto.WorldDesignMutationResultDto; import net.firedevops.firemud.worldmanagement.dto.WorldInstanceLifecycleSnapshotDto; +import net.firedevops.firemud.worldmanagement.service.InitialAdmissionBindHoldService; import net.firedevops.firemud.worldmanagement.service.PingService; import net.firedevops.firemud.worldmanagement.service.RoomService; import net.firedevops.firemud.worldmanagement.service.WorldDesignMutationService; import net.firedevops.firemud.worldmanagement.service.WorldDraftDesignDigestService; import net.firedevops.firemud.worldmanagement.service.WorldInstanceActivationService; import net.firedevops.firemud.worldmanagement.service.WorldUpgradeValidationService; +import net.firedevops.firemud.worldmanagement.v1.AcquireInitialAdmissionBindHoldRequest; +import net.firedevops.firemud.worldmanagement.v1.AcquireInitialAdmissionBindHoldResponse; import net.firedevops.firemud.worldmanagement.v1.ActivatePreparedWorldInstanceRequest; import net.firedevops.firemud.worldmanagement.v1.ActivatePreparedWorldInstanceResponse; import net.firedevops.firemud.worldmanagement.v1.ApplyWorldDesignMutationRequest; @@ -48,6 +53,7 @@ import net.firedevops.firemud.worldmanagement.v1.WorldDesignMutationOperation; import net.firedevops.firemud.worldmanagement.v1.WorldDesignMutationResult; import net.firedevops.firemud.worldmanagement.v1.WorldDesignScopeType; +import org.junit.jupiter.api.Nested; import org.junit.jupiter.api.Test; import org.mockito.Mockito; import org.springframework.http.HttpStatus; @@ -116,6 +122,172 @@ private static GetDraftDesignDigestResponse invokeDigestWithPeer( return ref.get(); } + private static AcquireInitialAdmissionBindHoldResponse invokeInitialBindAcquire( + WorldManagementGrpcService service, AcquireInitialAdmissionBindHoldRequest request) { + AtomicReference ref = new AtomicReference<>(); + service.acquireInitialAdmissionBindHold( + request, + new StreamObserver<>() { + @Override + public void onNext(AcquireInitialAdmissionBindHoldResponse value) { + ref.set(value); + } + + @Override + public void onError(Throwable t) { + throw new AssertionError("Initial bind hold RPC failed", t); + } + + @Override + public void onCompleted() {} + }); + return ref.get(); + } + + private static AcquireInitialAdmissionBindHoldRequest initialBindAcquireRequest() { + return AcquireInitialAdmissionBindHoldRequest.newBuilder() + .setTenantId("42") + .setGameInstanceId("101") + .setVersionId("11") + .setExpectedActiveLifecycleEpoch(7L) + .setInitialAdmissionRequestId("initial-admission-1") + .setRequestDigest("a".repeat(64)) + .setRealmUuid("00000000-0000-0000-0000-000000000001") + .setPlayableStateNamespaceUuid("00000000-0000-0000-0000-000000000002") + .setPlayableStateScope(PlayableStateScope.PLAYABLE_STATE_SCOPE_SHARED) + .setExpectedNoPriorPointer(true) + .setExpectedCatalogRevision(1L) + .build(); + } + + @Nested + class InitialAdmissionBindHoldBoundaryTest { + @Test + void initialAdmissionHoldAcquireDeniesMissingOrWrongWorkloadProof() { + InitialAdmissionBindHoldService holdService = + Mockito.mock(InitialAdmissionBindHoldService.class); + WorldManagementGrpcService service = + newService( + Mockito.mock(PingService.class), + Mockito.mock(RoomService.class), + new SimpleMeterRegistry()); + service.configureInitialAdmissionBindHoldBoundary(holdService, TEST_NAMESPACE); + SessionContext.clear(); + + var noPeerResponse = invokeInitialBindAcquire(service, initialBindAcquireRequest()); + assertEquals("PERMISSION_DENIED", noPeerResponse.getError().getCode()); + + AtomicReference wrongPeerResponse = + new AtomicReference<>(); + runWithPeer( + peer("entity-management-service"), + () -> + wrongPeerResponse.set( + invokeInitialBindAcquire(service, initialBindAcquireRequest()))); + assertEquals("PERMISSION_DENIED", wrongPeerResponse.get().getError().getCode()); + Mockito.verifyNoInteractions(holdService); + } + + @Test + void initialAdmissionHoldAcquireAcceptsOnlyGameSessionPeerAndReturnsExactFenceTuple() { + InitialAdmissionBindHoldService holdService = + Mockito.mock(InitialAdmissionBindHoldService.class); + Mockito.when(holdService.acquire(Mockito.any())) + .thenReturn( + new InitialAdmissionBindHoldDto( + "00000000-0000-0000-0000-000000000003", + "00000000-0000-0000-0000-000000000004", + 42L, + "00000000-0000-0000-0000-000000000001", + "00000000-0000-0000-0000-000000000002", + "SHARED", + 101L, + 11L, + 7L, + "initial-admission-1", + "a".repeat(64), + true, + 1L, + "PENDING", + java.time.Instant.parse("2026-10-01T00:05:00Z"))); + WorldManagementGrpcService service = + newService( + Mockito.mock(PingService.class), + Mockito.mock(RoomService.class), + new SimpleMeterRegistry()); + service.configureInitialAdmissionBindHoldBoundary(holdService, TEST_NAMESPACE); + SessionContext.clear(); + AtomicReference response = new AtomicReference<>(); + + runWithPeer( + peer("game-session-service"), + () -> response.set(invokeInitialBindAcquire(service, initialBindAcquireRequest()))); + + assertEquals("", response.get().getError().getCode()); + assertEquals("00000000-0000-0000-0000-000000000003", response.get().getHold().getHoldId()); + assertEquals("00000000-0000-0000-0000-000000000004", response.get().getHold().getHoldFence()); + assertEquals(1L, response.get().getHold().getExpectedCatalogRevision()); + assertEquals( + PlayableStateScope.PLAYABLE_STATE_SCOPE_SHARED, + response.get().getHold().getPlayableStateScope()); + Mockito.verify(holdService) + .acquire( + new net.firedevops.firemud.worldmanagement.dto.InitialAdmissionBindHoldRequest( + 42L, + 101L, + 11L, + 7L, + "initial-admission-1", + "a".repeat(64), + "00000000-0000-0000-0000-000000000001", + "00000000-0000-0000-0000-000000000002", + "SHARED", + true, + 1L)); + } + + @Test + void initialAdmissionHoldAcquireRejectsUnspecifiedAndUnrecognizedScopes() { + InitialAdmissionBindHoldService holdService = + Mockito.mock(InitialAdmissionBindHoldService.class); + WorldManagementGrpcService service = + newService( + Mockito.mock(PingService.class), + Mockito.mock(RoomService.class), + new SimpleMeterRegistry()); + service.configureInitialAdmissionBindHoldBoundary(holdService, TEST_NAMESPACE); + SessionContext.clear(); + + AtomicReference unspecifiedResponse = + new AtomicReference<>(); + runWithPeer( + peer("game-session-service"), + () -> + unspecifiedResponse.set( + invokeInitialBindAcquire( + service, + initialBindAcquireRequest().toBuilder() + .setPlayableStateScope( + PlayableStateScope.PLAYABLE_STATE_SCOPE_UNSPECIFIED) + .build()))); + assertEquals("INVALID_ARGUMENT", unspecifiedResponse.get().getError().getCode()); + + AtomicReference unrecognizedResponse = + new AtomicReference<>(); + runWithPeer( + peer("game-session-service"), + () -> + unrecognizedResponse.set( + invokeInitialBindAcquire( + service, + initialBindAcquireRequest().toBuilder() + .setPlayableStateScopeValue(999) + .build()))); + assertEquals("INVALID_ARGUMENT", unrecognizedResponse.get().getError().getCode()); + Mockito.verifyNoInteractions(holdService); + } + } + private static GetDraftDesignDigestRequest fullDigestRequest(String tenantId, String versionId) { PublicationDigestRequestBinding binding = PublicationDigestRequestBinding.full(tenantId, versionId, "request-7"); From 630521d1af0c383a459a0d8f3ef50e6e390e987e Mon Sep 17 00:00:00 2001 From: Ben Hook <5009589+benhook1013@users.noreply.github.com> Date: Fri, 2 Oct 2026 21:38:44 +1300 Subject: [PATCH 02/20] Complete run-owned initial admission bootstrap and accepted review fixes --- .../game-session-service/api-contracts.md | 2 +- .../world-management-service/api-contracts.md | 2 +- .../runtime-and-data.md | 2 +- ...ystem-architecture-authz-route-matrix.yaml | 43 ++ ...e-session-runtime-and-tick-coordination.md | 4 +- .../world-runtime-and-movement.md | 4 +- dev-tools/smoke/run-owned-compose.sh | 294 +++++++++ dev-tools/tests/compose-grpc-mtls-contract.sh | 106 ++- ...d-initial-admission-capability-contract.sh | 298 +++++++++ dev-tools/verify-fresh-bootstrap.sh | 4 + dev-tools/verify-restart-state.sh | 4 + dev-tools/verify-smoke-images.sh | 4 + docker/docker-compose.grpc-mtls.override.yml | 11 + .../v1/game_session_service.proto | 53 ++ .../client/WorldManagementClient.java | 72 +++ .../command/text/GameplayWorldCatalog.java | 29 +- ...yAdmissionPointerBootstrapInitializer.java | 8 +- ...wnedInitialAdmissionFixtureCapability.java | 438 +++++++++++++ ...nedInitialAdmissionFixtureCoordinator.java | 488 ++++++++++++++ .../gamesession/data/TestDataSeeder.java | 15 +- .../gamesession/entity/GameInstance.java | 5 + .../repository/GameInstanceRepository.java | 46 +- .../GameplayAdmissionPointerRepository.java | 17 +- ...InitialAdmissionBindAttemptRepository.java | 11 +- .../service/GameInstanceService.java | 3 + .../GameplayAdmissionCatalogPolicy.java | 55 ++ .../service/RunOwnedInitialLaunchResult.java | 7 + ...eplayAdmissionPointerAuthorityService.java | 18 +- .../service/impl/GameInstanceServiceImpl.java | 610 ++++++++++++++++++ .../GameSessionControlPlaneGrpcService.java | 185 ++++++ ...alAdmissionBindOwnerReadWorkloadGuard.java | 37 ++ .../src/main/resources/application.yml | 1 + .../V9__run_owned_initial_launch_identity.sql | 34 + ...dInitialLaunchPostgresIntegrationTest.java | 177 +++++ .../client/WorldManagementClientTest.java | 68 ++ .../text/GameplayWorldCatalogTest.java | 87 ++- .../command/text/PlayCommandHandlerTest.java | 2 + .../text/SessionResumptionFlowTest.java | 23 +- .../text/TextCommandInterpreterTest.java | 53 +- .../text/WorldsCommandHandlerTest.java | 19 + .../WorldsTextCommandDispatchHandlerTest.java | 1 + ...issionPointerBootstrapInitializerTest.java | 11 +- ...InitialAdmissionFixtureCapabilityTest.java | 170 +++++ ...nitialAdmissionFixtureCoordinatorTest.java | 396 ++++++++++++ .../gamesession/data/TestDataSeederTest.java | 11 +- ...ialAdmissionBindAttemptRepositoryTest.java | 122 ++++ ...yAdmissionPointerAuthorityServiceTest.java | 34 + .../impl/GameInstanceServiceImplTest.java | 354 ++++++++++ .../impl/GameSessionGrpcServiceTest.java | 18 +- .../InitialAdmissionBindOwnerReadTest.java | 288 +++++++++ .../GameSessionWebSocketHandlerTest.java | 71 +- .../gamesession/CrossServiceAppHarness.java | 12 +- ...essionInitialAdmissionBindProofClient.java | 163 +++++ .../worldmanagement/data/TestDataSeeder.java | 267 +------- .../dto/InitialAdmissionBindOwnerProof.java | 1 - .../InitialAdmissionBindHoldRepository.java | 66 +- .../repository/RoomRepository.java | 55 ++ .../InitialAdmissionBindHoldReconciler.java | 45 +- .../InitialAdmissionBindHoldServiceImpl.java | 7 +- ...RoomRepositoryPostgresIntegrationTest.java | 116 ++++ ...onInitialAdmissionBindProofClientTest.java | 223 +++++++ .../data/TestDataSeederTest.java | 391 ++--------- ...nitialAdmissionBindHoldRepositoryTest.java | 84 +++ ...nitialAdmissionBindHoldReconcilerTest.java | 97 +++ ...itialAdmissionBindHoldServiceImplTest.java | 81 ++- .../WorldLifecycleCommandServiceImplTest.java | 78 ++- .../impl/WorldManagementGrpcServiceTest.java | 10 + 67 files changed, 5714 insertions(+), 797 deletions(-) create mode 100644 dev-tools/tests/run-owned-initial-admission-capability-contract.sh create mode 100644 services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/data/RunOwnedInitialAdmissionFixtureCapability.java create mode 100644 services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/data/RunOwnedInitialAdmissionFixtureCoordinator.java create mode 100644 services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/service/GameplayAdmissionCatalogPolicy.java create mode 100644 services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/service/RunOwnedInitialLaunchResult.java create mode 100644 services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/service/impl/InitialAdmissionBindOwnerReadWorkloadGuard.java create mode 100644 services/game-session-service/src/main/resources/db/migration/V9__run_owned_initial_launch_identity.sql create mode 100644 services/game-session-service/src/test/java/integration/net/firedevops/firemud/gamesession/service/RunOwnedInitialLaunchPostgresIntegrationTest.java create mode 100644 services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/data/RunOwnedInitialAdmissionFixtureCapabilityTest.java create mode 100644 services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/data/RunOwnedInitialAdmissionFixtureCoordinatorTest.java create mode 100644 services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/repository/InitialAdmissionBindAttemptRepositoryTest.java create mode 100644 services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/service/impl/InitialAdmissionBindOwnerReadTest.java create mode 100644 services/world-management-service/src/main/java/net/firedevops/firemud/worldmanagement/client/GrpcGameSessionInitialAdmissionBindProofClient.java create mode 100644 services/world-management-service/src/test/java/integration/net/firedevops/firemud/worldmanagement/RoomRepositoryPostgresIntegrationTest.java create mode 100644 services/world-management-service/src/test/java/unit/net/firedevops/firemud/worldmanagement/client/GrpcGameSessionInitialAdmissionBindProofClientTest.java create mode 100644 services/world-management-service/src/test/java/unit/net/firedevops/firemud/worldmanagement/repository/InitialAdmissionBindHoldRepositoryTest.java create mode 100644 services/world-management-service/src/test/java/unit/net/firedevops/firemud/worldmanagement/service/impl/InitialAdmissionBindHoldReconcilerTest.java diff --git a/design/architecture/microservices/game-session-service/api-contracts.md b/design/architecture/microservices/game-session-service/api-contracts.md index 477970bf8c..e2ca90048a 100644 --- a/design/architecture/microservices/game-session-service/api-contracts.md +++ b/design/architecture/microservices/game-session-service/api-contracts.md @@ -52,7 +52,7 @@ The first admission-pointer bind for a realm is a separate owner transaction fro An exact retry or post-restart recovery reuses the same attempt and hold identities and reconciles the durable attempt, pointer, and audit. Game Session may record `ABORTED` only as a durable terminal outcome that prevents any later commit for that same attempt. World may accept that exact, authenticated owner-readback outcome bound to the same hold and tuple as abort proof; pointer absence, `NOT_FOUND`, `PENDING`, unavailable reads, mismatched tuple/audit, or contradictory evidence is not proof. World finalization requires an authenticated exact Game Session owner readback of the same hold and request identity/digest, tuple, committed pointer, matching audit, and `COMMITTED` outcome. Ambiguous results remain termination-fenced while automatic reconciliation retries; elapsed time does not release the World hold. See the World-owned [initial admission bind hold contract](../world-management-service/api-contracts.md#initial-admission-bind-hold-contract). -The current Game Session foundation includes local durable catalog/intent, pointer/audit, and commit/abort proof components. Focused local owner-ledger tests pass and PostgreSQL integration tests compile, but live database race/restart proof remains unavailable. The authenticated owner-read adapter, fixture delivery/coordinator, and durable `StartSession` retry integration are not wired. There is no startup autoactivation or new fixture ingress, and ambiguous outcomes continue to fence World termination. The existing cutover transaction and [replacement hold contract](../world-management-service/api-contracts.md#replacement-cutover-hold-contract) remain distinct; the canonical initial-bind contract is owned by [World](../world-management-service/api-contracts.md#initial-admission-bind-hold-contract). +The local run-owned Compose fixture path now reaches this owner transaction through a scheduled Game Session coordinator, explicitly disabled by default. It accepts only a read-only capability file bound to the claimed run and Compose project, one stable operation ID, the fixed demo/production fixture, and the exact development Game Session workload leaf and CA fingerprints; host input supplies no runtime ID, lifecycle epoch, catalog revision, pointer, or World hold identity. Game Session resolves and validates the published Game Design launch descriptor, durably reserves the matching launch identity, and drives World prepare/activate with exact epoch readback so a restart resumes the same launch. The coordinator persists the initial-bind intent before requesting the World hold, then uses the owner-local pointer/audit/outcome transaction and World’s authenticated owner-proof reconciliation; bounded retries reuse the same operation identity, and ambiguous evidence keeps the World termination fence closed. This path is a local Compose fixture bootstrap, not the accepted Account `JOIN` transaction or a production activation path; realm identity and admission-pointer authority remain defined by the [Multi-Tenancy contract](../../system-architecture-multi-tenancy.md#realm-catalog-and-admission-pointer-contract), and explicit join remains owned by [ADR 0025](../../decisions/adr-0025-explicit-open-enrollment-membership.md). See the [run-owned player-flow smoke boundary](../../system-architecture-testing.md#player-flow-smoke-and-reset-boundaries). Cross-service database race/restart proof remains outstanding; implementation and proof state are tracked in the [Game Session runtime tracker](../../../project-management/implementation-tracking/game-session-runtime-and-tick-coordination.md) and [validation workflow](../../../developer-workflows/validation-and-runtime-proof.md). The existing cutover transaction and [replacement hold contract](../world-management-service/api-contracts.md#replacement-cutover-hold-contract) remain distinct; the canonical initial-bind contract is owned by [World](../world-management-service/api-contracts.md#initial-admission-bind-hold-contract). ## Session Front-End and Lease-Owner Routing diff --git a/design/architecture/microservices/world-management-service/api-contracts.md b/design/architecture/microservices/world-management-service/api-contracts.md index 30233245d8..8bb7f741ff 100644 --- a/design/architecture/microservices/world-management-service/api-contracts.md +++ b/design/architecture/microservices/world-management-service/api-contracts.md @@ -269,7 +269,7 @@ Game Session owns the initial-bind attempt outcome and the admission pointer. It World finalizes only after an authenticated exact Game Session owner readback proves the same hold and request identity/digest, complete realm-target tuple, no-prior-pointer transition, committed pointer, matching audit event, and durable `COMMITTED` outcome. Definitive abort requires an authenticated exact readback of the durable `ABORTED` outcome bound to that same hold and tuple, with storage semantics that prevent any later commit for that attempt; World may then safely abort the hold. Pointer absence, a snapshot, `NOT_FOUND`, `PENDING`, an unavailable read, a tuple or audit mismatch, or contradictory evidence is not abort proof and never releases the hold. Any ambiguous or mismatched result leaves termination fenced and is reconciled automatically from the durable World hold and Game Session attempt record after retries, response loss, or process restart. Timeouts are repair triggers only; no hold is auto-released by elapsed time. -The current slice implements the typed `AcquireInitialAdmissionBindHold` RPC restricted to the authenticated Game Session workload, a separate durable World hold record, lifecycle-row serialization that blocks termination while the hold is unresolved, and scheduled fail-closed reconciliation. The authenticated Game Session owner-read adapter is not wired, so owner proof cannot yet resolve holds end to end. The 27 World focused tests passed; the three PostgreSQL race/restart integration cases were skipped without Docker and remain unproven here. The replacement hold contract above remains separate. +Current implementation includes the typed `AcquireInitialAdmissionBindHold` RPC restricted to the authenticated Game Session workload, the separate durable World hold record, lifecycle-row serialization that blocks termination while the hold is unresolved, scheduled fail-closed reconciliation, and a method-specific authenticated Game Session owner-read adapter. The run-owned local Compose fixture coordinator now reaches this hold after Game Session records its durable initial-bind intent; the World-owned reconciler resolves it only from authenticated exact owner proof. This remains an opt-in fixture path, not a change to the hold contract or a production activation path. PostgreSQL race/restart proof remains outstanding, and unavailable or mismatched owner evidence continues to fence termination. See the [Game Session initial-admission implementation status](../game-session-service/api-contracts.md#initial-admission-bind), [World Runtime and Movement tracker](../../../project-management/implementation-tracking/world-runtime-and-movement.md) for implementation anchors and current proof state, and the [validation and runtime proof workflow](../../../developer-workflows/validation-and-runtime-proof.md) for check selection. The replacement hold contract above remains separate. ## Instance Termination Contract diff --git a/design/architecture/microservices/world-management-service/runtime-and-data.md b/design/architecture/microservices/world-management-service/runtime-and-data.md index 6dc7956c8c..16a5c81f04 100644 --- a/design/architecture/microservices/world-management-service/runtime-and-data.md +++ b/design/architecture/microservices/world-management-service/runtime-and-data.md @@ -118,7 +118,7 @@ The initial realm bind uses a separate World-owned hold because it has no source The World termination compare-and-set checks that neither an initial-bind nor replacement hold is nonterminal under the same lifecycle-row serialization. A held instance cannot enter `TERMINATING` or advance its lifecycle epoch. Resolving the hold does not weaken ordinary termination: the stable cleanup request, frozen owner/registry snapshot, owner acknowledgements, and final `TERMINATED` compare-and-set remain in force. Game Session must atomically commit the first pointer, matching append-only audit, and terminal attempt outcome in its own database; World then uses authenticated exact owner readback to finalize or to accept only a durable `ABORTED` outcome bound to the same hold/tuple that prevents a later commit for that attempt. Missing, pending, unavailable, mismatched, or contradictory evidence leaves the hold nonterminal. Durable records and the automatic reconciliation path recover the exact identity/fence after response loss or restart; timeout or expiry only triggers repair and never auto-releases the hold. The full normative contract is in [Initial Admission Bind Hold Contract](./api-contracts.md#initial-admission-bind-hold-contract). -World now persists the initial-bind hold separately and includes it in the lifecycle-row termination check; its scheduled reconciler keeps the hold blocking when no authenticated owner reader is available. The authenticated Game Session owner-read adapter is not wired, and the three PostgreSQL race/restart tests were skipped without Docker. See the [World API contract](./api-contracts.md#initial-admission-bind-hold-contract) for the canonical contract and current proof status. +World now persists the initial-bind hold separately and includes it in the lifecycle-row termination check. Its scheduled reconciler uses the method-specific authenticated Game Session owner-proof reader; unavailable, ambiguous, or mismatched evidence keeps the hold nonterminal and termination-blocking. PostgreSQL-backed race/restart and live Compose proof remain unclaimed. See the [World API contract](./api-contracts.md#initial-admission-bind-hold-contract) and [World Runtime and Movement tracker](../../../project-management/implementation-tracking/world-runtime-and-movement.md) for the canonical contract and current proof status. ### Runtime configuration and events diff --git a/design/architecture/system-architecture-authz-route-matrix.yaml b/design/architecture/system-architecture-authz-route-matrix.yaml index 16ef35c108..2e28ddc04b 100644 --- a/design/architecture/system-architecture-authz-route-matrix.yaml +++ b/design/architecture/system-architecture-authz-route-matrix.yaml @@ -327,6 +327,11 @@ required_live_check_vocabulary: - browser_origin - capacity_admission_fence - cancellation_window + # Exact initial-admission owner-ledger and World hold admission checks. + - aborted_attempt_future_commit_fence + - active_target_version_epoch + - committed_pointer_audit_binding + - conflicting_hold_absence - conditional_membership - conditional_membership_generation - conditional_realm_access_grant @@ -347,7 +352,9 @@ required_live_check_vocabulary: - explicit_deletion_confirmation - export_availability - explicit_per_subscription_binding + - exact_attempt_tuple - exact_binding_admission_lease + - exact_retry_identity - binding_fence - binding_ownership - playable_state_namespace @@ -3768,3 +3775,39 @@ routes: required_fields: [control_plane_request_id, actor, reason, mutation_digest] canonical_errors: any_of: [IDEMPOTENCY_CONFLICT] + - service: game-session-service + route: GetInitialAdmissionBindProof + transport: grpc + scope: tenant + classification: internal_workload + auth_path: exact_mtls_workload + accepted_token_profiles: [] + token_type: none + token_issuer: none + token_audience: none + method_policy: exact_declared_route + allowed_callers: + any_of: [world-management-service] + mtls_callers: + any_of: ["spiffe://firemud/ns/{namespace}/sa/world-management-service"] + end_user_token_required: false + required_live_checks: [exact_attempt_tuple, committed_pointer_audit_binding, aborted_attempt_future_commit_fence] + required_fields: [hold_id, hold_fence, tenant_id, realm_uuid, playable_state_namespace_uuid, playable_state_scope, game_instance_id, version_id, active_lifecycle_epoch, initial_admission_request_id, request_digest, expected_no_prior_pointer, expected_catalog_revision] + - service: world-management-service + route: AcquireInitialAdmissionBindHold + transport: grpc + scope: tenant + classification: internal_workload + auth_path: exact_mtls_workload + accepted_token_profiles: [] + token_type: none + token_issuer: none + token_audience: none + method_policy: exact_declared_route + allowed_callers: + any_of: [game-session-service] + mtls_callers: + any_of: ["spiffe://firemud/ns/{namespace}/sa/game-session-service"] + end_user_token_required: false + required_live_checks: [active_target_version_epoch, exact_retry_identity, conflicting_hold_absence] + required_fields: [tenant_id, game_instance_id, version_id, expected_active_lifecycle_epoch, initial_admission_request_id, request_digest, realm_uuid, playable_state_namespace_uuid, playable_state_scope, expected_no_prior_pointer, expected_catalog_revision] 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 ad14efc767..d21d2bb4f5 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 @@ -8,7 +8,7 @@ This is a non-normative implementation tracker for Game Session runtime and tick This tracker consolidates the live Game Session execution substrate by capability. The recorded boundaries describe current implementation status and bounded follow-up work. -The initial-admission foundation now includes durable catalog/intent and pointer/audit commit/abort proof components. Its three local owner-ledger tests pass and PostgreSQL integration tests compile; live database race/restart proof is not claimed. The authenticated owner-read adapter, fixture delivery/coordinator, and durable `StartSession` retry integration remain unwired; no startup autoactivation or new fixture ingress is added. Ambiguous outcomes continue to fence World termination. See the [Game Session API status](../../architecture/microservices/game-session-service/api-contracts.md#initial-admission-bind) and canonical [World contract](../../architecture/microservices/world-management-service/api-contracts.md#initial-admission-bind-hold-contract). +The initial-admission foundation includes durable catalog/intent and pointer/audit commit/abort proof components, plus a method-specific Game Session owner-proof read connected to World’s hold reconciler. An opt-in, run-owned local Compose coordinator now validates the read-only fixture capability, resumes the descriptor-validated Game Session launch under its stable operation identity, persists initial-bind intent before requesting the World hold, and completes the owner transaction through authenticated proof. This does not implement the strict Account `JOIN` validation-through-commit gate, production activation, or generalized runtime-ID migration; default startup remains closed. Focused Game Session owner tests passed. Cross-service PostgreSQL race/restart and live Compose proof are not claimed, and ambiguous outcomes continue to fence World termination. See the [Game Session API status](../../architecture/microservices/game-session-service/api-contracts.md#initial-admission-bind) and canonical [World contract](../../architecture/microservices/world-management-service/api-contracts.md#initial-admission-bind-hold-contract). 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). @@ -42,6 +42,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 (see [Game Session API implementation status](../../architecture/microservices/game-session-service/api-contracts.md#implementation-status)); lease-owner forwarding for independently partitioned regions is not | `proven`: [GameSessionWebSocketHandlerTest](../../../services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/websocket/GameSessionWebSocketHandlerTest.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) cover the shipped front-door and routing seams | [Game Session API contracts](../../architecture/microservices/game-session-service/api-contracts.md); [Game Session runtime/data](../../architecture/microservices/game-session-service/runtime-and-data.md); [reconnection](../../architecture/system-architecture-reconnection.md) | [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) | [GameSessionWebSocketHandlerTest](../../../services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/websocket/GameSessionWebSocketHandlerTest.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); [GameSessionGrpcServiceTest](../../../services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/service/impl/GameSessionGrpcServiceTest.java) | `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 API contract requires front-end-to-lease-owner forwarding to be fenced, with retry/ambiguity handling. The current owner boundary is game-instance scoped and does not implement that forwarding or true region partitioning; no new design decision is recorded. | +| Initial-admission pointer bootstrap and owner readback | `partial`: durable catalog/intent and pointer/audit commit/abort proof, typed owner-proof receiver/client, run-owned launch resume, and the opt-in local Compose fixture coordinator are wired; the general `StartSession` retry path is not claimed | `in progress`: focused Game Session owner tests passed; cross-service PostgreSQL race/restart and live Compose proof are not claimed | [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); [run-owned player-flow smoke boundary](../../architecture/system-architecture-testing.md#player-flow-smoke-and-reset-boundaries) | [DatabaseInitialAdmissionBindOwnerService.java](../../../services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/service/impl/DatabaseInitialAdmissionBindOwnerService.java); [RunOwnedInitialAdmissionFixtureCoordinator.java](../../../services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/data/RunOwnedInitialAdmissionFixtureCoordinator.java); [RunOwnedInitialAdmissionFixtureCapability.java](../../../services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/data/RunOwnedInitialAdmissionFixtureCapability.java); [GameInstanceServiceImpl.java](../../../services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/service/impl/GameInstanceServiceImpl.java); [V8 initial-admission owner ledger](../../../services/game-session-service/src/main/resources/db/migration/V8__initial_admission_bind_owner_ledger.sql); [GetInitialAdmissionBindProof](../../../protos/game-session/v1/game_session_service.proto); [InitialAdmissionBindOwnerReadWorkloadGuard.java](../../../services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/service/impl/InitialAdmissionBindOwnerReadWorkloadGuard.java); [GrpcGameSessionInitialAdmissionBindProofClient.java](../../../services/world-management-service/src/main/java/net/firedevops/firemud/worldmanagement/client/GrpcGameSessionInitialAdmissionBindProofClient.java) | [InitialAdmissionBindServiceTest.java](../../../services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/service/impl/InitialAdmissionBindServiceTest.java); [InitialAdmissionBindOwnerReadTest.java](../../../services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/service/impl/InitialAdmissionBindOwnerReadTest.java); [RunOwnedInitialAdmissionFixtureCapabilityTest.java](../../../services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/data/RunOwnedInitialAdmissionFixtureCapabilityTest.java); [RunOwnedInitialAdmissionFixtureCoordinatorTest.java](../../../services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/data/RunOwnedInitialAdmissionFixtureCoordinatorTest.java); [GameInstanceServiceImplTest.java](../../../services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/service/impl/GameInstanceServiceImplTest.java); [GrpcGameSessionInitialAdmissionBindProofClientTest.java](../../../services/world-management-service/src/test/java/unit/net/firedevops/firemud/worldmanagement/client/GrpcGameSessionInitialAdmissionBindProofClientTest.java); [InitialAdmissionBindPostgresIntegrationTest.java](../../../services/game-session-service/src/test/java/integration/net/firedevops/firemud/gamesession/service/InitialAdmissionBindPostgresIntegrationTest.java) | World owns the separate hold and termination fence; see the [World runtime tracker](./world-runtime-and-movement.md) | The bounded local Compose coordinator does not complete the strict Account `JOIN` gate, production activation, or generalized runtime-ID migration. General `StartSession` retry integration and live cross-service PostgreSQL restart proof remain open; no ambiguous result releases World termination. | | `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. | @@ -180,6 +181,7 @@ The recorded Markdown and contract checks for these slices include `./gradlew li ## Active Gaps +- Initial-admission pointer creation is durable only within Game Session’s local owner ledger. The run-owned local Compose path now supplies an opt-in coordinator and a launch identity that resumes across restart; this does not satisfy Account’s strict `JOIN` validation-through-commit gate, activate production, or complete generalized runtime-ID migration. The general `StartSession` retry path and cross-service PostgreSQL race/restart proof remain open; startup stays closed by default and ambiguity continues to fence World termination. See the canonical [World hold contract](../../architecture/microservices/world-management-service/api-contracts.md#initial-admission-bind-hold-contract) and [run-owned smoke boundary](../../architecture/system-architecture-testing.md#player-flow-smoke-and-reset-boundaries). - TICK-03 is now the accepted command-level boundary: required versus optional effects, permitted terminal combinations, intentional `PARTIAL`, and stronger atomicity routing must be classified per command family. Current implementation and proof remain partial; no status promotion is implied. - TICK-04 remains partial and proof remains incomplete: operation/digest-bound participant guards and focused crash/retry/dead-letter coverage across World and Entity are still gaps under accepted contracts. Command-plan admission, `planOrdinal`, and root allocation are proposal-only in ADR 0183 and are not implementation or proof gaps unless that proposal is accepted. ADR 0069 owns effect identity, replay, and terminal-outcome rules; ADR 0071 owns durable tick commit before fenced coordination cleanup. - Replacement cutover remains partial at the Game Session boundary: the current wire/durable record/reconciler has no complete proof of exact cross-service cutover binding, post-swap readback, safe abort, or finalization, and must not infer success from a pointer write or an in-memory termination request. See the canonical [World Management replacement cutover hold contract](../../architecture/microservices/world-management-service/api-contracts.md#replacement-cutover-hold-contract) and [ADR 0122](../../architecture/decisions/adr-0122-stable-playable-state-namespaces-for-runtime-replacement.md). 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 095161d714..abd05d48b2 100644 --- a/design/project-management/implementation-tracking/world-runtime-and-movement.md +++ b/design/project-management/implementation-tracking/world-runtime-and-movement.md @@ -8,7 +8,7 @@ This is a non-normative implementation tracker for world runtime and movement. C This tracker is the permanent reader-facing implementation record for world runtime, room reads, movement, lifecycle orchestration, and Draft topology mutation. Canonical target-state design remains under [design/architecture](../../architecture/README.md). -The initial-admission foundation now has a typed Game Session workload-only acquire RPC, a durable World hold, lifecycle-row termination serialization, and scheduled fail-closed reconciliation. The authenticated owner-read adapter is not wired. The 27 World focused tests passed; three PostgreSQL race/restart tests were skipped without Docker. See the [World initial-bind contract](../../architecture/microservices/world-management-service/api-contracts.md#initial-admission-bind-hold-contract). +The initial-admission implementation now includes the typed Game Session workload-only acquire RPC, a durable World hold, lifecycle-row termination serialization, scheduled fail-closed reconciliation, and a method-specific authenticated Game Session owner-read adapter. The opt-in run-owned local Compose coordinator now drives the hold from Game Session’s durable initial-bind intent and resolves it only through exact authenticated owner proof. Raw Game Session `RUNNING` and World `ACTIVE` runtime seeds have been removed; local World metadata seeding retains versioned template rooms `1021` and `2045` for the current transitional movement contract. All 144 World unit tests pass; PostgreSQL race/restart and live Compose proof remain unclaimed. See the [World initial-bind contract](../../architecture/microservices/world-management-service/api-contracts.md#initial-admission-bind-hold-contract) and the [Game Session implementation status](../../architecture/microservices/game-session-service/api-contracts.md#initial-admission-bind). ## Packet 4 Status and Proof Gaps @@ -27,6 +27,7 @@ These links add decision provenance only; they do not upgrade world runtime, lif | Capability | Implementation | Verification | Design | Implementation anchors | Proof anchors | Secondary handoffs | Gap or decision | | --- | --- | --- | --- | --- | --- | --- | --- | | `GR-2.1` World topology, rooms, regions, and runtime instances | `partial` | `audited` | [World Management ownership](../../architecture/microservices/world-management-service/README.md); [World API contracts](../../architecture/microservices/world-management-service/api-contracts.md); [runtime and data](../../architecture/microservices/world-management-service/runtime-and-data.md); [world creation workflow](../../architecture/microservices/world-management-service/world-creation-workflow.md); [ADR 0093](../../architecture/decisions/adr-0093-game-design-coordinated-digest-attested-content-publication.md); [ADR 0098](../../architecture/decisions/adr-0098-request-bounded-generation-replay-and-explicit-regeneration.md); [ADR 0099](../../architecture/decisions/adr-0099-bounded-atomic-generation-with-staging-for-large-outputs.md); [ADR 0100](../../architecture/decisions/adr-0100-separate-generation-ingress-with-one-world-owned-engine.md); [ADR 0101](../../architecture/decisions/adr-0101-explicit-destructive-regeneration-with-previewed-scope.md); [ADR 0102](../../architecture/decisions/adr-0102-first-class-sparse-and-full-grid-world-topologies.md) | [WorldDesignMutationServiceImpl.java](../../../services/world-management-service/src/main/java/net/firedevops/firemud/worldmanagement/service/impl/WorldDesignMutationServiceImpl.java); [WorldInstanceActivationServiceImpl.java](../../../services/world-management-service/src/main/java/net/firedevops/firemud/worldmanagement/service/impl/WorldInstanceActivationServiceImpl.java); [WorldLifecycleCommandServiceImpl.java](../../../services/world-management-service/src/main/java/net/firedevops/firemud/worldmanagement/service/impl/WorldLifecycleCommandServiceImpl.java); [V18 version-scoped templates](../../../services/world-management-service/src/main/resources/db/migration/V18__version_scoped_world_templates.sql); [V19 mutation ledger](../../../services/world-management-service/src/main/resources/db/migration/V19__world_design_mutation_ledger.sql) | [WorldDesignMutationServiceImplTest.java](../../../services/world-management-service/src/test/java/unit/net/firedevops/firemud/worldmanagement/service/impl/WorldDesignMutationServiceImplTest.java); [WorldDraftDesignDigestServiceImplTest.java](../../../services/world-management-service/src/test/java/unit/net/firedevops/firemud/worldmanagement/service/impl/WorldDraftDesignDigestServiceImplTest.java); [WorldLifecycleCommandServiceImplTest.java](../../../services/world-management-service/src/test/java/unit/net/firedevops/firemud/worldmanagement/service/impl/WorldLifecycleCommandServiceImplTest.java); [WorldManagementGrpcServiceTest.java](../../../services/world-management-service/src/test/java/unit/net/firedevops/firemud/worldmanagement/service/impl/WorldManagementGrpcServiceTest.java) | [authoring](./game-authoring-publishing-and-activation.md); [realm routing](./realm-routing-and-playable-state.md); [Game Session runtime](./game-session-runtime-and-tick-coordination.md) | Partial: version-scoped topology, Draft mutation, and instance lifecycle exist, but generation still has hardcoded inputs, initial event scheduling is absent, and lifecycle prepare/activate retain blocking attestation calls. Accepted publication and procedural-generation decisions now define World-owned topology, request-bounded replay, atomic visibility, explicit replacement, and sparse/full-grid boundaries; typed ingress, destructive plans, staging bounds, and large-grid proof remain incomplete. | +| `GR-2.1` World-owned initial-admission hold and termination fence | `partial`: exact hold acquisition, serialized termination blocking, fail-closed reconciliation, authenticated Game Session owner proof, and the run-owned local Compose caller are wired; the general `StartSession` retry path is not claimed | `drift-found`: all 144 World unit tests pass; PostgreSQL race/restart proof remains outstanding | [World initial-admission bind hold contract](../../architecture/microservices/world-management-service/api-contracts.md#initial-admission-bind-hold-contract); [ADR 0123](../../architecture/decisions/adr-0123-database-authoritative-temporal-coordinated-world-lifecycle.md); [run-owned player-flow smoke boundary](../../architecture/system-architecture-testing.md#player-flow-smoke-and-reset-boundaries) | [WorldManagementGrpcService.java](../../../services/world-management-service/src/main/java/net/firedevops/firemud/worldmanagement/service/impl/WorldManagementGrpcService.java); [InitialAdmissionBindHoldServiceImpl.java](../../../services/world-management-service/src/main/java/net/firedevops/firemud/worldmanagement/service/impl/InitialAdmissionBindHoldServiceImpl.java); [InitialAdmissionBindHoldRepository.java](../../../services/world-management-service/src/main/java/net/firedevops/firemud/worldmanagement/repository/InitialAdmissionBindHoldRepository.java); [V23 initial-admission hold](../../../services/world-management-service/src/main/resources/db/migration/V23__initial_admission_bind_hold.sql); [GrpcGameSessionInitialAdmissionBindProofClient.java](../../../services/world-management-service/src/main/java/net/firedevops/firemud/worldmanagement/client/GrpcGameSessionInitialAdmissionBindProofClient.java) | [WorldManagementGrpcServiceTest.java](../../../services/world-management-service/src/test/java/unit/net/firedevops/firemud/worldmanagement/service/impl/WorldManagementGrpcServiceTest.java); [InitialAdmissionBindHoldServiceImplTest.java](../../../services/world-management-service/src/test/java/unit/net/firedevops/firemud/worldmanagement/service/impl/InitialAdmissionBindHoldServiceImplTest.java); [InitialAdmissionBindHoldRepositoryTest.java](../../../services/world-management-service/src/test/java/unit/net/firedevops/firemud/worldmanagement/repository/InitialAdmissionBindHoldRepositoryTest.java); [InitialAdmissionBindHoldPostgresIntegrationTest.java](../../../services/world-management-service/src/test/java/integration/net/firedevops/firemud/worldmanagement/InitialAdmissionBindHoldPostgresIntegrationTest.java) | [Game Session runtime tracker](./game-session-runtime-and-tick-coordination.md) | Run-owned Compose reaches the World hold from durable Game Session intent, but does not complete the strict Account `JOIN` gate, production activation, or generalized runtime-ID migration. PostgreSQL race/restart and live Compose proof remain open; ambiguity must continue fencing termination. | | `GR-2.2` Location, occupancy, movement, exits, and spatial reads | `partial` | `audited` | [World API contracts](../../architecture/microservices/world-management-service/api-contracts.md); [World runtime and data](../../architecture/microservices/world-management-service/runtime-and-data.md); [system architecture](../../architecture/system-architecture-overview.md); [spatial and ambient effects](../../architecture/system-architecture-spatial-and-ambient-effects-catalog.md); [ADR 0102](../../architecture/decisions/adr-0102-first-class-sparse-and-full-grid-world-topologies.md) | [WorldManagementGrpcService.java](../../../services/world-management-service/src/main/java/net/firedevops/firemud/worldmanagement/service/impl/WorldManagementGrpcService.java); [LookAggregationService.java](../../../services/game-logic-service/src/main/java/net/firedevops/firemud/gamelogic/service/LookAggregationService.java); [MoveAggregationService.java](../../../services/game-logic-service/src/main/java/net/firedevops/firemud/gamelogic/service/MoveAggregationService.java); [MoveCommandHandler.java](../../../services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/command/text/MoveCommandHandler.java); [room contract](../../../protos/world-management/v1/world_management_service.proto) | [WorldManagementGrpcServiceTest.java](../../../services/world-management-service/src/test/java/unit/net/firedevops/firemud/worldmanagement/service/impl/WorldManagementGrpcServiceTest.java); [LookAggregationServiceTest.java](../../../services/game-logic-service/src/test/java/net/firedevops/firemud/gamelogic/service/LookAggregationServiceTest.java); [MoveAggregationServiceTest.java](../../../services/game-logic-service/src/test/java/net/firedevops/firemud/gamelogic/service/MoveAggregationServiceTest.java); [MoveCommandHandlerTest.java](../../../services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/command/text/MoveCommandHandlerTest.java); [movement idempotency test](../../../services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/service/impl/RedisMovementEffectIdempotencyServiceTest.java) | [authoring](./game-authoring-publishing-and-activation.md); [gameplay](./gameplay-rules-entities-and-effects.md); [Game Session runtime](./game-session-runtime-and-tick-coordination.md); [player experience](./player-experience-commands-and-communication.md) | Partial: directional LOOK and movement primitives exist, but the WMS `ListRoomOccupants` handler and target-only `character_location`/`npc_location` location and occupancy persistence are absent. Live `room_instance` topology and the Game Session room binding are not the World-owned location authority, and the final LOOK identity is not yet the causal floor plus opaque World/Entity component versions; served-through proofs remain separate participant validation evidence. DROP/PICKUP also lack the target World `TargetingFactSnapshot` location/version validation in the Entity-local commit. [ADR 0054](../../architecture/decisions/adr-0054-split-spatial-authority-with-causal-read-composition.md) remains applied; implementation and proof gaps remain. Accepted full-grid topology decision now defines density-independent movement semantics and opaque scalable representation; large-grid identity, chunk/root finalization, base-plus-delta recovery, and movement-policy proof remain incomplete. | | `GR-2.3` Ambient, environmental, and scheduled world state | `partial` | `audited` | [World API contracts](../../architecture/microservices/world-management-service/api-contracts.md); [World runtime and data](../../architecture/microservices/world-management-service/runtime-and-data.md); [spatial and ambient effects](../../architecture/system-architecture-spatial-and-ambient-effects-catalog.md); [world creation workflow](../../architecture/microservices/world-management-service/world-creation-workflow.md) | [WorldEventServiceImpl.java](../../../services/world-management-service/src/main/java/net/firedevops/firemud/worldmanagement/service/impl/WorldEventServiceImpl.java); [WorldManagementGrpcService.java](../../../services/world-management-service/src/main/java/net/firedevops/firemud/worldmanagement/service/impl/WorldManagementGrpcService.java); [RoomSnapshotDto.java](../../../services/world-management-service/src/main/java/net/firedevops/firemud/worldmanagement/dto/RoomSnapshotDto.java); [V3 world events](../../../services/world-management-service/src/main/resources/db/migration/V3__world_events.sql); [V16 runtime event scope](../../../services/world-management-service/src/main/resources/db/migration/V16__runtime_world_event_scope.sql) | [WorldEventServiceImplTest.java](../../../services/world-management-service/src/test/java/unit/net/firedevops/firemud/worldmanagement/service/impl/WorldEventServiceImplTest.java); [RoomSnapshotDtoTest.java](../../../services/world-management-service/src/test/java/unit/net/firedevops/firemud/worldmanagement/dto/RoomSnapshotDtoTest.java); [WorldManagementGrpcServiceTest.java](../../../services/world-management-service/src/test/java/unit/net/firedevops/firemud/worldmanagement/service/impl/WorldManagementGrpcServiceTest.java) | [authoring](./game-authoring-publishing-and-activation.md); [automation](./automation-and-scheduler-runtime.md); [Game Session runtime](./game-session-runtime-and-tick-coordination.md); [gameplay](./gameplay-rules-entities-and-effects.md) | Partial: scheduled non-Weather event processing and ambient snapshot shape exist, but `ApplyRoomAmbientStatePatch` has no Java handler, durable effect-idempotency and general ambient patches are absent, and the creation workflow does not schedule initial events. Live `WorldEventService` rejects new `WEATHER_CHANGE` scheduling and leaves retained Weather rows unprocessed; the unresolved selector/fenced effect contract still blocks safe ambient mutation, so current code is not proof of the target World-owned fenced ambient-mutation contract. [ADR 0054](../../architecture/decisions/adr-0054-split-spatial-authority-with-causal-read-composition.md) remains the target owner; its World-side handler, durable replay guard, and focused proof remain unimplemented. | @@ -117,6 +118,7 @@ These links add decision provenance only; they do not upgrade world runtime, lif - The current Weather path is fail-closed while its selector and typed effect fence remain unresolved: new `WEATHER_CHANGE` scheduling is rejected before persistence, retained Weather rows remain unprocessed and non-mutating, and region-bearing non-Weather events require exact tenant/game-instance scope matching. Focused service proof covers the containment and valid non-Weather path; PostgreSQL integration proof covers Weather exclusion, exact tenant/game-instance scope, and single-claim `SKIP LOCKED` behavior. Safe Weather admission and retained-row reconciliation remain open. - Temporal activation/failure retries still lack durable operation-result reconciliation after a lost response, and StartSession compensation does not reconcile an already-`ACTIVE` world. Exact retries after fail/terminate workflow completion can signal a closed workflow instead of returning the durable terminal result; focused retry, compensation, and closed-workflow proof remains absent. - Replacement cutover still lacks the World-owned one-shot hold record/readback contract: exact source/target `ACTIVE` epoch locking, the nonterminal-hold termination predicate, hold-bound Game Session pointer transaction, safe abort/finalize reconciliation, diagnostic-only expiry, and focused proof. This remains target implementation drift; it does not introduce a new world lifecycle state. +- The run-owned local Compose initial-admission coordinator is implemented, but the general `StartSession` retry path, strict Account `JOIN` validation-through-commit gate, production activation, and generalized runtime-ID migration remain outside this slice. PostgreSQL hold/termination race and restart recovery, plus live Compose proof, remain unproved; World expiry is diagnostic only and no ambiguous outcome releases the termination fence. See the canonical [initial-admission bind hold contract](../../architecture/microservices/world-management-service/api-contracts.md#initial-admission-bind-hold-contract) and its [focused integration test](../../../services/world-management-service/src/test/java/integration/net/firedevops/firemud/worldmanagement/InitialAdmissionBindHoldPostgresIntegrationTest.java). - Starter-region preparation still persists hard-coded `SimpleDungeonGenerator` metadata and does not consume the frozen published generation inputs and provenance required by the launch descriptor. - Initial world-event scheduling is absent from the current prepare path despite being canonical lifecycle step 2. - Omitted optional terrain/population stages have no durable `SKIPPED_NOT_REQUIRED` outcome or operator-facing projection, so current lifecycle status cannot distinguish intentional omission from not-started or failed work. diff --git a/dev-tools/smoke/run-owned-compose.sh b/dev-tools/smoke/run-owned-compose.sh index a19ccf381d..b1ae0f8f9b 100644 --- a/dev-tools/smoke/run-owned-compose.sh +++ b/dev-tools/smoke/run-owned-compose.sh @@ -286,6 +286,300 @@ _firemud_smoke_write_marker() { rm -f "$temporary" } +_firemud_smoke_initial_admission_context() { + local digest project_name="$FIREMUD_SMOKE_EXPECTED_PROJECT" + digest="$(_firemud_smoke_capability)" || return 1 + if [[ "$FIREMUD_SMOKE_EXPECTED_MODE" == github ]]; then + FIREMUD_SMOKE_RUN_ID="gha-$(printf '%s' "$FIREMUD_SMOKE_CAPABILITY_INPUT" | _firemud_smoke_sha256)" || return 1 + fi + if [[ ! "$FIREMUD_SMOKE_RUN_ID" =~ ^[a-z0-9][a-z0-9-]{0,127}$ || ! "$project_name" =~ ^[a-z0-9][a-z0-9-]{0,127}$ ]]; then + _firemud_smoke_fail "initial-admission run and project identifiers must match the Game Session capability identifier format." + return 1 + fi + + FIREMUD_SMOKE_COMPOSE_PROJECT_NAME="$project_name" + FIREMUD_SMOKE_INITIAL_ADMISSION_CAPABILITY_PATH=/app/run-owned-initial-admission-capability.json + FIREMUD_SMOKE_INITIAL_ADMISSION_CAPABILITY_HOST_PATH="$FIREMUD_SMOKE_OWNERSHIP_DIR_RESOLVED/$FIREMUD_SMOKE_PROJECT_KEY.initial-admission-capability.json" + FIREMUD_SMOKE_INITIAL_ADMISSION_FIXTURE_ENABLED=false + FIREMUD_SMOKE_INITIAL_ADMISSION_CLAIM_DIGEST="$digest" + export FIREMUD_SMOKE_RUN_ID FIREMUD_SMOKE_COMPOSE_PROJECT_NAME + export FIREMUD_SMOKE_INITIAL_ADMISSION_CAPABILITY_PATH + export FIREMUD_SMOKE_INITIAL_ADMISSION_CAPABILITY_HOST_PATH + export FIREMUD_SMOKE_INITIAL_ADMISSION_FIXTURE_ENABLED +} + +_firemud_smoke_initial_admission_operation_id() { + python3 - "$FIREMUD_SMOKE_INITIAL_ADMISSION_CLAIM_DIGEST" \ + "$FIREMUD_SMOKE_RUN_ID" "$FIREMUD_SMOKE_COMPOSE_PROJECT_NAME" "$1" "$2" <<'PY' +import sys +import uuid + +claim_digest, run_id, project_name, leaf_sha256, ca_sha256 = sys.argv[1:] +namespace = uuid.UUID("2b7ca687-3637-4dc4-9b12-08ec4c6a9f76") +identity = "\0".join( + ( + "firemud.run-owned-initial-admission-fixture.v1", + claim_digest, + run_id, + project_name, + leaf_sha256, + ca_sha256, + ) +) +print(uuid.uuid5(namespace, identity)) +PY +} + +_firemud_smoke_validate_initial_admission_capability() { + local path="$1" operation_id="$2" leaf_sha256="$3" ca_sha256="$4" + local file_metadata + if [[ -L "$path" || ! -f "$path" ]]; then + _firemud_smoke_fail "initial-admission capability must be an existing regular non-symlink file." + return 1 + fi + file_metadata="$(stat -c '%u %a %F %s' "$path" 2>/dev/null || true)" + if [[ ! "$file_metadata" =~ ^$(id -u)[[:space:]]444[[:space:]]regular\ file[[:space:]][1-9][0-9]{0,4}$ ]]; then + _firemud_smoke_fail "initial-admission capability must be owner-owned, read-only, and bounded." + return 1 + fi + + if ! python3 - "$path" "$FIREMUD_SMOKE_RUN_ID" \ + "$FIREMUD_SMOKE_COMPOSE_PROJECT_NAME" "$operation_id" "$leaf_sha256" "$ca_sha256" <<'PY' +import json +import os +import re +import stat +import sys +import uuid + +path, run_id, project_name, operation_id, leaf_sha256, ca_sha256 = sys.argv[1:] +allowed = { + "schema", "runId", "composeProjectName", "operationId", "tenantId", + "gameTemplateId", "ownerAccountId", "worldSlug", "worldDisplayName", + "realmSlug", "realmDisplayName", "visible", "publicProductionRealm", + "requiresCharacterSelection", "stateScope", "characterCreationPolicy", + "gameSessionLeafSha256", "gameSessionUriSan", "caCertificateSha256", +} + +def unique_object(pairs): + result = {} + for key, value in pairs: + if key in result: + raise ValueError("duplicate key") + result[key] = value + return result + +try: + descriptor = os.open(path, os.O_RDONLY | os.O_NOFOLLOW | os.O_CLOEXEC) + try: + before = os.fstat(descriptor) + if ( + not stat.S_ISREG(before.st_mode) + or before.st_uid != os.getuid() + or stat.S_IMODE(before.st_mode) != 0o444 + or before.st_size <= 0 + or before.st_size > 16 * 1024 + ): + raise ValueError("bad capability file") + chunks = bytearray() + while len(chunks) <= 16 * 1024: + chunk = os.read(descriptor, min(1024, 16 * 1024 + 1 - len(chunks))) + if not chunk: + break + chunks.extend(chunk) + after = os.fstat(descriptor) + path_after = os.stat(path, follow_symlinks=False) + if ( + len(chunks) > 16 * 1024 + or not stat.S_ISREG(path_after.st_mode) + or (before.st_dev, before.st_ino) != (after.st_dev, after.st_ino) + or (before.st_dev, before.st_ino) != (path_after.st_dev, path_after.st_ino) + or (before.st_size, before.st_mtime_ns) != (after.st_size, after.st_mtime_ns) + or (before.st_size, before.st_mtime_ns) != (path_after.st_size, path_after.st_mtime_ns) + or before.st_uid != after.st_uid + or before.st_uid != path_after.st_uid + or stat.S_IMODE(after.st_mode) != 0o444 + or stat.S_IMODE(path_after.st_mode) != 0o444 + ): + raise ValueError("changed capability file") + payload = bytes(chunks) + finally: + os.close(descriptor) + value = json.loads(payload.decode("utf-8"), object_pairs_hook=unique_object) + uuid.UUID(operation_id) +except (OSError, UnicodeDecodeError, json.JSONDecodeError, ValueError): + raise SystemExit(1) + +expected = { + "schema": "firemud.run-owned-initial-admission-fixture.v1", + "runId": run_id, + "composeProjectName": project_name, + "operationId": operation_id, + "tenantId": 1, + "gameTemplateId": 1, + "ownerAccountId": 1, + "worldSlug": "demo", + "worldDisplayName": "Demo World", + "realmSlug": "production", + "realmDisplayName": "Live Realm", + "visible": True, + "publicProductionRealm": True, + "requiresCharacterSelection": False, + "stateScope": "SHARED", + "characterCreationPolicy": "ALLOW_NEW", + "gameSessionLeafSha256": leaf_sha256, + "gameSessionUriSan": "spiffe://firemud/ns/dev/sa/game-session-service", + "caCertificateSha256": ca_sha256, +} +safe_id = re.compile(r"[a-z0-9][a-z0-9-]{0,127}\Z") +if not safe_id.fullmatch(run_id) or not safe_id.fullmatch(project_name): + raise SystemExit(1) +if ( + not isinstance(value, dict) + or set(value) != allowed + or value != expected + or any(type(value[key]) is not type(expected[key]) for key in allowed) +): + raise SystemExit(1) +PY + then + _firemud_smoke_fail "initial-admission capability does not match the exact run claim, project, fixture, and TLS identity." + return 1 + fi +} + +ensure_run_owned_initial_admission_capability() { + local certificate_root="$1" mode="$2" + local expected_certificate_root leaf_certificate ca_certificate leaf_sha256 ca_sha256 + local operation_id capability_path temporary + local -a uri_sans=() + + case "$mode" in + create-or-verify|reuse-only) ;; + *) + _firemud_smoke_fail "initial-admission capability mode must be create-or-verify or reuse-only." + return 1 + ;; + esac + _firemud_smoke_prepare || return 1 + _firemud_smoke_lock || return 1 + _firemud_smoke_verify_marker || return 1 + _firemud_smoke_initial_admission_context || return 1 + + expected_certificate_root="$FIREMUD_SMOKE_OWNERSHIP_DIR_RESOLVED/$FIREMUD_SMOKE_PROJECT_KEY.grpc-mtls" + if [[ "$certificate_root" != "$expected_certificate_root" || -L "$certificate_root" || ! -d "$certificate_root" ]]; then + _firemud_smoke_fail "initial-admission TLS material must be under this claimed run's canonical certificate root." + return 1 + fi + leaf_certificate="$certificate_root/workloads/game-session-service/client.crt" + ca_certificate="$certificate_root/workloads/game-session-service/ca.crt" + if [[ -L "$certificate_root/workloads" || -L "$certificate_root/workloads/game-session-service" \ + || ! -d "$certificate_root/workloads/game-session-service" \ + || -L "$leaf_certificate" || ! -f "$leaf_certificate" \ + || -L "$ca_certificate" || ! -f "$ca_certificate" ]]; then + _firemud_smoke_fail "initial-admission TLS leaf and CA must be regular files in the claimed Game Session workload directory." + return 1 + fi + if [[ "$(grep -c -- '-----BEGIN CERTIFICATE-----' "$leaf_certificate" 2>/dev/null || true)" != 1 \ + || "$(grep -c -- '-----BEGIN CERTIFICATE-----' "$ca_certificate" 2>/dev/null || true)" != 1 ]]; then + _firemud_smoke_fail "initial-admission TLS leaf and CA must each contain exactly one certificate." + return 1 + fi + if ! openssl x509 -in "$leaf_certificate" -noout -checkend 0 >/dev/null 2>&1 \ + || ! openssl x509 -in "$ca_certificate" -noout -checkend 0 >/dev/null 2>&1 \ + || ! openssl verify -CAfile "$ca_certificate" "$leaf_certificate" >/dev/null 2>&1; then + _firemud_smoke_fail "initial-admission Game Session TLS leaf is invalid for the run-owned CA." + return 1 + fi + mapfile -t uri_sans < <(openssl x509 -in "$leaf_certificate" -noout -ext subjectAltName 2>/dev/null \ + | grep -oE 'URI:[^,[:space:]]+') + if ((${#uri_sans[@]} != 1)) \ + || [[ "${uri_sans[0]:-}" != URI:spiffe://firemud/ns/dev/sa/game-session-service ]]; then + _firemud_smoke_fail "initial-admission Game Session TLS leaf must contain one exact dev workload URI SAN." + return 1 + fi + leaf_sha256="$(openssl x509 -in "$leaf_certificate" -outform DER 2>/dev/null \ + | openssl dgst -sha256 2>/dev/null | awk '{print $NF}')" + ca_sha256="$(openssl x509 -in "$ca_certificate" -outform DER 2>/dev/null \ + | openssl dgst -sha256 2>/dev/null | awk '{print $NF}')" + if [[ ! "$leaf_sha256" =~ ^[a-f0-9]{64}$ || ! "$ca_sha256" =~ ^[a-f0-9]{64}$ ]]; then + _firemud_smoke_fail "could not fingerprint the run-owned Game Session TLS leaf and CA." + return 1 + fi + + capability_path="$FIREMUD_SMOKE_INITIAL_ADMISSION_CAPABILITY_HOST_PATH" + operation_id="$(_firemud_smoke_initial_admission_operation_id "$leaf_sha256" "$ca_sha256")" || { + _firemud_smoke_fail "could not derive the stable initial-admission operation identity." + return 1 + } + if [[ -e "$capability_path" || -L "$capability_path" ]]; then + _firemud_smoke_validate_initial_admission_capability \ + "$capability_path" "$operation_id" "$leaf_sha256" "$ca_sha256" + local validation_status=$? + if ((validation_status == 0)); then + FIREMUD_SMOKE_INITIAL_ADMISSION_FIXTURE_ENABLED=true + export FIREMUD_SMOKE_INITIAL_ADMISSION_FIXTURE_ENABLED + fi + return "$validation_status" + fi + if [[ "$mode" == reuse-only ]]; then + _firemud_smoke_fail "restart requires the existing matching initial-admission capability; it will not create one." + return 1 + fi + + temporary="$(mktemp "$FIREMUD_SMOKE_OWNERSHIP_DIR_RESOLVED/.initial-admission-capability.$FIREMUD_SMOKE_PROJECT_KEY.XXXXXX")" || { + _firemud_smoke_fail "could not create a temporary initial-admission capability." + return 1 + } + if ! python3 - "$temporary" "$FIREMUD_SMOKE_RUN_ID" \ + "$FIREMUD_SMOKE_COMPOSE_PROJECT_NAME" "$operation_id" "$leaf_sha256" "$ca_sha256" <<'PY' +import json +import pathlib +import sys + +path, run_id, project_name, operation_id, leaf_sha256, ca_sha256 = sys.argv[1:] +value = { + "schema": "firemud.run-owned-initial-admission-fixture.v1", + "runId": run_id, + "composeProjectName": project_name, + "operationId": operation_id, + "tenantId": 1, + "gameTemplateId": 1, + "ownerAccountId": 1, + "worldSlug": "demo", + "worldDisplayName": "Demo World", + "realmSlug": "production", + "realmDisplayName": "Live Realm", + "visible": True, + "publicProductionRealm": True, + "requiresCharacterSelection": False, + "stateScope": "SHARED", + "characterCreationPolicy": "ALLOW_NEW", + "gameSessionLeafSha256": leaf_sha256, + "gameSessionUriSan": "spiffe://firemud/ns/dev/sa/game-session-service", + "caCertificateSha256": ca_sha256, +} +with pathlib.Path(path).open("w", encoding="utf-8") as target: + json.dump(value, target, indent=2) + target.write("\n") +PY + then + rm -f -- "$temporary" + _firemud_smoke_fail "could not write the initial-admission capability." + return 1 + fi + if ! chmod 444 "$temporary" || ! ln "$temporary" "$capability_path"; then + rm -f -- "$temporary" + _firemud_smoke_fail "initial-admission capability creation raced or could not be made read-only." + return 1 + fi + rm -f -- "$temporary" + _firemud_smoke_validate_initial_admission_capability \ + "$capability_path" "$operation_id" "$leaf_sha256" "$ca_sha256" || return 1 + FIREMUD_SMOKE_INITIAL_ADMISSION_FIXTURE_ENABLED=true + export FIREMUD_SMOKE_INITIAL_ADMISSION_FIXTURE_ENABLED +} + require_run_owned_compose_project() { _firemud_smoke_prepare || return 1 _firemud_smoke_lock || return 1 diff --git a/dev-tools/tests/compose-grpc-mtls-contract.sh b/dev-tools/tests/compose-grpc-mtls-contract.sh index 29af9f9422..c3ba5ba5be 100644 --- a/dev-tools/tests/compose-grpc-mtls-contract.sh +++ b/dev-tools/tests/compose-grpc-mtls-contract.sh @@ -100,6 +100,91 @@ echo "Checking canonical Compose entrypoints." mtls_compose="$ROOT_DIR/docker/docker-compose.grpc-mtls.override.yml" rg -Fq 'FIREMUD_GRPC_PLAINTEXT: "false"' "$mtls_compose" rg -Fq 'GRPC_SERVER_TLS_ENABLED: "true"' "$mtls_compose" +python3 - "$mtls_compose" <<'PY' +import pathlib +import re +import sys + +lines = pathlib.Path(sys.argv[1]).read_text(encoding="utf-8").splitlines() +for service in ("entity-management-service", "world-management-service", "game-session-service"): + headers = [index for index, line in enumerate(lines) if line == f" {service}:"] + assert len(headers) == 1, service + start = headers[0] + end = next( + ( + index + for index in range(start + 1, len(lines)) + if lines[index].startswith(" ") and not lines[index].startswith(" ") + ), + len(lines), + ) + block = lines[start + 1 : end] + environments = [index for index, line in enumerate(block) if line == " environment:"] + assert len(environments) == 1, service + env_start = environments[0] + env_end = next( + ( + index + for index in range(env_start + 1, len(block)) + if block[index].startswith(" ") and not block[index].startswith(" ") + ), + len(block), + ) + environment = block[env_start + 1 : env_end] + assert any( + re.fullmatch( + r" FIREMUD_GRPC_WORKLOAD_NAMESPACE:\s*[\"']?dev[\"']?\s*(?:#.*)?", + line, + ) + for line in environment + ), f"{service} must set FIREMUD_GRPC_WORKLOAD_NAMESPACE to dev in its mTLS overlay" +PY +python3 - "$mtls_compose" <<'PY' +import pathlib +import sys + +lines = pathlib.Path(sys.argv[1]).read_text(encoding="utf-8").splitlines() +service_blocks = {} +for index, line in enumerate(lines): + if not line.startswith(" ") or line.startswith(" ") or not line.endswith(":"): + continue + service = line[2:-1] + end = next( + ( + position + for position in range(index + 1, len(lines)) + if lines[position].startswith(" ") and not lines[position].startswith(" ") + ), + len(lines), + ) + service_blocks[service] = lines[index + 1 : end] + +capability_path = "/app/run-owned-initial-admission-capability.json" +fixture_keys = ( + "FIREMUD_SMOKE_RUN_ID", + "FIREMUD_SMOKE_COMPOSE_PROJECT_NAME", + "FIREMUD_SMOKE_INITIAL_ADMISSION_FIXTURE_ENABLED", + "FIREMUD_SMOKE_INITIAL_ADMISSION_CAPABILITY_PATH", +) +for service, block in service_blocks.items(): + if service == "game-session-service": + for key in fixture_keys: + assert any(line.startswith(f" {key}:") for line in block), key + assert any( + line == f" FIREMUD_SMOKE_INITIAL_ADMISSION_CAPABILITY_PATH: {capability_path}" + for line in block + ) + assert any( + line == " source: ${FIREMUD_SMOKE_INITIAL_ADMISSION_CAPABILITY_HOST_PATH:-/dev/null}" + for line in block + ) + assert any(line == f" target: {capability_path}" for line in block) + assert any(line == " read_only: true" for line in block) + assert any(line == " create_host_path: false" for line in block) + else: + assert not any(any(key in line for key in fixture_keys) for line in block), service + assert not any(capability_path in line for line in block), service +PY rg -Fq 'client-auth: REQUIRE' "$ROOT_DIR/services/world-management-service/src/main/resources/application.yml" world_guard="$ROOT_DIR/services/world-management-service/src/main/java/net/firedevops/firemud/worldmanagement/service/impl/InitialAdmissionBindWorkloadGuard.java" world_grpc="$ROOT_DIR/services/world-management-service/src/main/java/net/firedevops/firemud/worldmanagement/service/impl/WorldManagementGrpcService.java" @@ -146,18 +231,21 @@ if command -v docker >/dev/null 2>&1 && docker compose version >/dev/null 2>&1; rendered_config="$TEST_ROOT/compose-config.json" FIREMUD_COMPOSE_GRPC_MTLS_CERT_ROOT="$fixture_root" SMOKE_IMAGE_TAG=contract \ + FIREMUD_SMOKE_INITIAL_ADMISSION_CAPABILITY_HOST_PATH="$TEST_ROOT/config-probe-capability.json" \ + FIREMUD_SMOKE_INITIAL_ADMISSION_FIXTURE_ENABLED=false \ + FIREMUD_SMOKE_RUN_ID='' FIREMUD_SMOKE_COMPOSE_PROJECT_NAME='' \ docker compose --env-file "$compose_fixture/.env" \ -f "$compose_fixture/docker/docker-compose.yml" \ -f "$compose_fixture/docker/docker-compose.override.yml" \ -f "$compose_fixture/docker/docker-compose.smoke-images.override.yml" \ -f "$compose_fixture/docker/docker-compose.grpc-mtls.override.yml" \ config --format json >"$rendered_config" - python3 - "$rendered_config" "$fixture_root" <<'PY' + python3 - "$rendered_config" "$fixture_root" "$TEST_ROOT/config-probe-capability.json" <<'PY' import json import pathlib import sys -config_path, cert_root = sys.argv[1:] +config_path, cert_root, capability_source = sys.argv[1:] config = json.loads(pathlib.Path(config_path).read_text(encoding="utf-8")) services = config["services"] app_names = { @@ -183,6 +271,20 @@ entity_namespace = services["entity-management-service"]["environment"].get("FIR assert entity_namespace == "dev", entity_namespace wms_namespace = services["world-management-service"]["environment"].get("FIREMUD_GRPC_WORKLOAD_NAMESPACE") assert wms_namespace == "dev", wms_namespace +game_session = services["game-session-service"] +game_session_environment = game_session["environment"] +assert game_session_environment.get("FIREMUD_SMOKE_RUN_ID") == "" +assert game_session_environment.get("FIREMUD_SMOKE_COMPOSE_PROJECT_NAME") == "" +assert game_session_environment.get("FIREMUD_SMOKE_INITIAL_ADMISSION_FIXTURE_ENABLED") == "false" +capability_path = "/app/run-owned-initial-admission-capability.json" +assert game_session_environment.get("FIREMUD_SMOKE_INITIAL_ADMISSION_CAPABILITY_PATH") == capability_path +capability_mounts = [mount for mount in game_session.get("volumes", []) if mount.get("target") == capability_path] +assert len(capability_mounts) == 1, capability_mounts +assert capability_mounts[0]["source"] == capability_source, capability_mounts[0] +assert capability_mounts[0].get("read_only") is True +for name, service in services.items(): + if name != "game-session-service": + assert not any(mount.get("target") == capability_path for mount in service.get("volumes", [])), name assert services["account-service"]["image"].endswith(":contract") print("Verified Compose mTLS wiring and image-only service configuration.") PY diff --git a/dev-tools/tests/run-owned-initial-admission-capability-contract.sh b/dev-tools/tests/run-owned-initial-admission-capability-contract.sh new file mode 100644 index 0000000000..cf8d9714ab --- /dev/null +++ b/dev-tools/tests/run-owned-initial-admission-capability-contract.sh @@ -0,0 +1,298 @@ +#!/usr/bin/env bash +set -euo pipefail + +ROOT_DIR="$(cd "$(dirname "${BASH_SOURCE[0]}")/../.." && pwd)" +TEST_ROOT="$(mktemp -d "${TMPDIR:-/tmp}/firemud-run-owned-admission-contract.XXXXXX")" +trap 'rm -rf -- "$TEST_ROOT"' EXIT +chmod 700 "$TEST_ROOT" + +docker() { + case "$1 $2" in + "ps -a"|"network ls"|"volume ls") return 0 ;; + *) + echo "Unexpected Docker command in capability contract: $*" >&2 + return 1 + ;; + esac +} +export -f docker + +# shellcheck disable=SC1091 # The repository root is resolved at runtime. +source "$ROOT_DIR/dev-tools/smoke/run-owned-compose.sh" + +ownership_dir="$TEST_ROOT/ownership" +mkdir -m 700 -- "$ownership_dir" +export FIREMUD_SMOKE_TEST_MODE=1 +export FIREMUD_SMOKE_OWNERSHIP_DIR="$ownership_dir" +unset GITHUB_ACTIONS GITHUB_RUN_ID GITHUB_RUN_ATTEMPT GITHUB_JOB + +expect_failure() { + local label="$1" + shift + local output="$TEST_ROOT/failure-output" + if "$@" >"$output" 2>&1; then + echo "Expected refusal for $label, but the capability helper accepted it." >&2 + exit 1 + fi +} + +load_operation_id() { + python3 - "$1" <<'PY' +import json +import pathlib +import sys + +value = json.loads(pathlib.Path(sys.argv[1]).read_text(encoding="utf-8")) +expected_fields = { + "schema", "runId", "composeProjectName", "operationId", "tenantId", + "gameTemplateId", "ownerAccountId", "worldSlug", "worldDisplayName", + "realmSlug", "realmDisplayName", "visible", "publicProductionRealm", + "requiresCharacterSelection", "stateScope", "characterCreationPolicy", + "gameSessionLeafSha256", "gameSessionUriSan", "caCertificateSha256", +} +assert set(value) == expected_fields, set(value) +assert value["schema"] == "firemud.run-owned-initial-admission-fixture.v1" +assert value["tenantId"] == 1 +assert value["gameTemplateId"] == 1 +assert value["ownerAccountId"] == 1 +assert value["worldSlug"] == "demo" +assert value["worldDisplayName"] == "Demo World" +assert value["realmSlug"] == "production" +assert value["realmDisplayName"] == "Live Realm" +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["gameSessionUriSan"] == "spiffe://firemud/ns/dev/sa/game-session-service" +print(value["operationId"]) +PY +} + +reject_wrong_claim() { + FIREMUD_SMOKE_OWNERSHIP_TOKEN="$(printf 'f%.0s' {1..64})" \ + ensure_run_owned_initial_admission_capability "$base_certificate_root" create-or-verify +} + +reject_wrong_run() { + FIREMUD_SMOKE_RUN_ID=wrong-run \ + ensure_run_owned_initial_admission_capability "$base_certificate_root" create-or-verify +} + +reject_wrong_project() { + COMPOSE_PROJECT_NAME=wrong-project \ + ensure_run_owned_initial_admission_capability "$base_certificate_root" create-or-verify +} + +reject_symlinked_capability() { + local saved="$TEST_ROOT/capability-symlink-target.json" + mv -- "$base_capability" "$saved" + ln -s -- "$saved" "$base_capability" + if ensure_run_owned_initial_admission_capability "$base_certificate_root" create-or-verify; then + rm -f -- "$base_capability" + mv -- "$saved" "$base_capability" + return 0 + fi + rm -f -- "$base_capability" + mv -- "$saved" "$base_capability" + return 1 +} + +reject_replaced_capability() { + ensure_run_owned_initial_admission_capability "$base_certificate_root" create-or-verify +} + +reject_missing_restart_capability() { + ensure_run_owned_initial_admission_capability "$base_certificate_root" reuse-only +} + +reject_wrong_github_job() { + GITHUB_JOB=other-job ensure_run_owned_initial_admission_capability \ + "$base_certificate_root" create-or-verify +} + +prepare_local_claim() { + local run_id="$1" + export FIREMUD_SMOKE_RUN_ID="$run_id" + export COMPOSE_PROJECT_NAME="firemud-smoke-$run_id" + FIREMUD_SMOKE_OWNERSHIP_TOKEN="$(openssl rand -hex 32)" + export FIREMUD_SMOKE_OWNERSHIP_TOKEN + claim_run_owned_compose_project +} + +generate_local_certificates() { + local certificate_root="$1" + _firemud_smoke_unlock + FIREMUD_COMPOSE_GRPC_MTLS_CERT_ROOT="$certificate_root" \ + bash "$ROOT_DIR/dev-tools/certs/ensure-dev-certs.sh" --compose-mtls "$certificate_root" + claim_run_owned_compose_project +} + +prepare_local_claim "cap-contract-local" +base_run_id="$FIREMUD_SMOKE_RUN_ID" +base_project="$COMPOSE_PROJECT_NAME" +base_token="$FIREMUD_SMOKE_OWNERSHIP_TOKEN" +base_certificate_root="$FIREMUD_SMOKE_OWNERSHIP_DIR_RESOLVED/$FIREMUD_SMOKE_PROJECT_KEY.grpc-mtls" +base_capability="$FIREMUD_SMOKE_OWNERSHIP_DIR_RESOLVED/$FIREMUD_SMOKE_PROJECT_KEY.initial-admission-capability.json" + +expect_failure missing_tls ensure_run_owned_initial_admission_capability \ + "$base_certificate_root" create-or-verify +[[ ! -e "$base_capability" && "$FIREMUD_SMOKE_INITIAL_ADMISSION_FIXTURE_ENABLED" == false ]] + +generate_local_certificates "$base_certificate_root" +ensure_run_owned_initial_admission_capability "$base_certificate_root" create-or-verify +[[ "$FIREMUD_SMOKE_INITIAL_ADMISSION_FIXTURE_ENABLED" == true ]] +[[ "$FIREMUD_SMOKE_COMPOSE_PROJECT_NAME" == "$base_project" ]] +[[ "$FIREMUD_SMOKE_INITIAL_ADMISSION_CAPABILITY_PATH" == /app/run-owned-initial-admission-capability.json ]] +[[ "$FIREMUD_SMOKE_INITIAL_ADMISSION_CAPABILITY_HOST_PATH" == "$base_capability" ]] +[[ "$FIREMUD_SMOKE_INITIAL_ADMISSION_CAPABILITY_HOST_PATH" != "$FIREMUD_SMOKE_INITIAL_ADMISSION_CAPABILITY_PATH" ]] +[[ "$(stat -c '%a' "$(dirname "$base_capability")")" == 700 ]] +[[ "$(stat -c '%u %a %F' "$base_capability")" == "$(id -u) 444 regular file" ]] +base_operation_id="$(load_operation_id "$base_capability")" +ensure_run_owned_initial_admission_capability "$base_certificate_root" reuse-only +ensure_run_owned_initial_admission_capability "$base_certificate_root" create-or-verify +[[ "$(load_operation_id "$base_capability")" == "$base_operation_id" ]] + +expect_failure wrong_claim reject_wrong_claim +expect_failure wrong_run reject_wrong_run +expect_failure wrong_project reject_wrong_project +expect_failure symlinked_capability reject_symlinked_capability +[[ "$(load_operation_id "$base_capability")" == "$base_operation_id" ]] + +capability_backup="$TEST_ROOT/capability-original.json" +cp -p -- "$base_capability" "$capability_backup" +python3 - "$TEST_ROOT/replaced-capability.json" "$base_capability" <<'PY' +import json +import pathlib +import sys +import uuid + +source = pathlib.Path(sys.argv[2]) +value = json.loads(source.read_text(encoding="utf-8")) +replacement = uuid.UUID(value["operationId"]).int ^ 1 +value["operationId"] = str(uuid.UUID(int=replacement)) +pathlib.Path(sys.argv[1]).write_text(json.dumps(value, indent=2) + "\n", encoding="utf-8") +PY +chmod 444 "$TEST_ROOT/replaced-capability.json" +mv -- "$TEST_ROOT/replaced-capability.json" "$base_capability" +expect_failure replaced_capability reject_replaced_capability +mv -- "$capability_backup" "$base_capability" +[[ "$(load_operation_id "$base_capability")" == "$base_operation_id" ]] + +capability_backup="$TEST_ROOT/capability-before-missing-restart.json" +mv -- "$base_capability" "$capability_backup" +expect_failure missing_restart_capability reject_missing_restart_capability +[[ ! -e "$base_capability" ]] +mv -- "$capability_backup" "$base_capability" + +_firemud_smoke_unlock +prepare_local_claim "cap-contract-cert-source" +source_certificate_root="$FIREMUD_SMOKE_OWNERSHIP_DIR_RESOLVED/$FIREMUD_SMOKE_PROJECT_KEY.grpc-mtls" +generate_local_certificates "$source_certificate_root" +_firemud_smoke_unlock +export FIREMUD_SMOKE_RUN_ID="$base_run_id" +export COMPOSE_PROJECT_NAME="$base_project" +export FIREMUD_SMOKE_OWNERSHIP_TOKEN="$base_token" +claim_run_owned_compose_project +cp -p -- "$base_certificate_root/workloads/game-session-service/client.crt" "$TEST_ROOT/original-client.crt" +cp -p -- "$base_certificate_root/workloads/game-session-service/ca.crt" "$TEST_ROOT/original-ca.crt" +chmod 600 "$base_certificate_root/workloads/game-session-service/client.crt" \ + "$base_certificate_root/workloads/game-session-service/ca.crt" +cp -- "$source_certificate_root/workloads/game-session-service/client.crt" \ + "$base_certificate_root/workloads/game-session-service/client.crt" +cp -- "$source_certificate_root/workloads/game-session-service/ca.crt" \ + "$base_certificate_root/workloads/game-session-service/ca.crt" +chmod 444 "$base_certificate_root/workloads/game-session-service/client.crt" \ + "$base_certificate_root/workloads/game-session-service/ca.crt" +expect_failure changed_certificate ensure_run_owned_initial_admission_capability \ + "$base_certificate_root" create-or-verify +chmod 600 "$base_certificate_root/workloads/game-session-service/client.crt" \ + "$base_certificate_root/workloads/game-session-service/ca.crt" +cp -- "$TEST_ROOT/original-client.crt" "$base_certificate_root/workloads/game-session-service/client.crt" +cp -- "$TEST_ROOT/original-ca.crt" "$base_certificate_root/workloads/game-session-service/ca.crt" +chmod 444 "$base_certificate_root/workloads/game-session-service/client.crt" \ + "$base_certificate_root/workloads/game-session-service/ca.crt" +ensure_run_owned_initial_admission_capability "$base_certificate_root" reuse-only +[[ "$(load_operation_id "$base_capability")" == "$base_operation_id" ]] + +_firemud_smoke_unlock +export GITHUB_ACTIONS=true +export GITHUB_RUN_ID=801 +export GITHUB_RUN_ATTEMPT=3 +export GITHUB_JOB=smoke +export COMPOSE_PROJECT_NAME=smoke-full-801-3 +FIREMUD_SMOKE_OWNERSHIP_TOKEN="$(openssl rand -hex 32)" +export FIREMUD_SMOKE_OWNERSHIP_TOKEN +claim_run_owned_compose_project +expected_github_run_id="$(python3 - <<'PY' +import hashlib +print("gha-" + hashlib.sha256(b"github:801:3:smoke").hexdigest()) +PY +)" +_firemud_smoke_initial_admission_context +[[ "$FIREMUD_SMOKE_RUN_ID" == "$expected_github_run_id" ]] +[[ "$FIREMUD_SMOKE_COMPOSE_PROJECT_NAME" == smoke-full-801-3 ]] +github_certificate_root="$FIREMUD_SMOKE_OWNERSHIP_DIR_RESOLVED/$FIREMUD_SMOKE_PROJECT_KEY.grpc-mtls" +_firemud_smoke_unlock +FIREMUD_COMPOSE_GRPC_MTLS_CERT_ROOT="$github_certificate_root" \ + bash "$ROOT_DIR/dev-tools/certs/ensure-dev-certs.sh" --compose-mtls "$github_certificate_root" +claim_run_owned_compose_project +ensure_run_owned_initial_admission_capability "$github_certificate_root" create-or-verify +github_capability="$FIREMUD_SMOKE_INITIAL_ADMISSION_CAPABILITY_HOST_PATH" +github_operation_id="$(load_operation_id "$github_capability")" +python3 - "$github_capability" "$expected_github_run_id" <<'PY' +import json +import pathlib +import sys + +value = json.loads(pathlib.Path(sys.argv[1]).read_text(encoding="utf-8")) +assert value["runId"] == sys.argv[2] +assert value["composeProjectName"] == "smoke-full-801-3" +PY +ensure_run_owned_initial_admission_capability "$github_certificate_root" reuse-only +expect_failure wrong_github_job reject_wrong_github_job +[[ "$(load_operation_id "$github_capability")" == "$github_operation_id" ]] + +_firemud_smoke_unlock +export GITHUB_RUN_ATTEMPT=4 +export COMPOSE_PROJECT_NAME=smoke-full-801-4 +claim_run_owned_compose_project +_firemud_smoke_initial_admission_context +expected_attempt_run_id="$(python3 - <<'PY' +import hashlib +print("gha-" + hashlib.sha256(b"github:801:4:smoke").hexdigest()) +PY +)" +[[ "$FIREMUD_SMOKE_RUN_ID" == "$expected_attempt_run_id" ]] +[[ "$FIREMUD_SMOKE_COMPOSE_PROJECT_NAME" == smoke-full-801-4 ]] +attempt_run_id="$FIREMUD_SMOKE_RUN_ID" + +_firemud_smoke_unlock +export GITHUB_RUN_ID=802 +export COMPOSE_PROJECT_NAME=smoke-full-802-4 +claim_run_owned_compose_project +_firemud_smoke_initial_admission_context +expected_other_run_id="$(python3 - <<'PY' +import hashlib +print("gha-" + hashlib.sha256(b"github:802:4:smoke").hexdigest()) +PY +)" +[[ "$FIREMUD_SMOKE_RUN_ID" == "$expected_other_run_id" ]] +[[ "$FIREMUD_SMOKE_RUN_ID" != "$attempt_run_id" ]] +[[ "$FIREMUD_SMOKE_COMPOSE_PROJECT_NAME" == smoke-full-802-4 ]] + +for wrapper in verify-fresh-bootstrap.sh verify-smoke-images.sh verify-restart-state.sh; do + wrapper_path="$ROOT_DIR/dev-tools/$wrapper" + disabled_line="$(rg -n '^export FIREMUD_SMOKE_INITIAL_ADMISSION_FIXTURE_ENABLED=false$' "$wrapper_path" | cut -d: -f1)" + config_line="$(rg -n 'config(--format json| --services| >/dev/null)' "$wrapper_path" | head -n 1 | cut -d: -f1 || true)" + capability_line="$(rg -n 'ensure_run_owned_initial_admission_capability' "$wrapper_path" | cut -d: -f1)" + [[ -n "$disabled_line" && -n "$capability_line" ]] + if [[ -n "$config_line" ]]; then + ((disabled_line < config_line)) + if [[ "$wrapper" != verify-restart-state.sh ]]; then + ((config_line < capability_line)) + fi + fi +done + +echo "Run-owned initial-admission capability contract passed." diff --git a/dev-tools/verify-fresh-bootstrap.sh b/dev-tools/verify-fresh-bootstrap.sh index 5ef004a8d7..a5471ac095 100644 --- a/dev-tools/verify-fresh-bootstrap.sh +++ b/dev-tools/verify-fresh-bootstrap.sh @@ -15,6 +15,9 @@ ENSURE_CERTS_SCRIPT="$ROOT_DIR/dev-tools/certs/ensure-dev-certs.sh" ENSURE_ENV_SCRIPT="$ROOT_DIR/dev-tools/ensure-local-compose-env.sh" # shellcheck disable=SC1091 # The repository root is resolved at runtime. source "$ROOT_DIR/dev-tools/smoke/run-owned-compose.sh" +export FIREMUD_SMOKE_INITIAL_ADMISSION_FIXTURE_ENABLED=false +export FIREMUD_SMOKE_INITIAL_ADMISSION_CAPABILITY_PATH=/app/run-owned-initial-admission-capability.json +unset FIREMUD_SMOKE_INITIAL_ADMISSION_CAPABILITY_HOST_PATH # Prefer noninteractive compose output for AI/automation callers. PTY-backed runs # under Docker Desktop/WSL can hang in compose teardown even when the same command @@ -96,6 +99,7 @@ fi claim_run_owned_compose_project export FIREMUD_COMPOSE_GRPC_MTLS_CERT_ROOT="$FIREMUD_SMOKE_OWNERSHIP_DIR_RESOLVED/$FIREMUD_SMOKE_PROJECT_KEY.grpc-mtls" bash "$ENSURE_CERTS_SCRIPT" --compose-mtls "$FIREMUD_COMPOSE_GRPC_MTLS_CERT_ROOT" +ensure_run_owned_initial_admission_capability "$FIREMUD_COMPOSE_GRPC_MTLS_CERT_ROOT" create-or-verify docker compose "${COMPOSE_FILES[@]}" down -v --remove-orphans bash "$BUILD_JARS_SCRIPT" if [[ "$FIREMUD_SMOKE_SERIAL_BUILD" == "1" ]]; then diff --git a/dev-tools/verify-restart-state.sh b/dev-tools/verify-restart-state.sh index 318b5c61e7..90418518c1 100644 --- a/dev-tools/verify-restart-state.sh +++ b/dev-tools/verify-restart-state.sh @@ -15,6 +15,9 @@ ENSURE_CERTS_SCRIPT="$ROOT_DIR/dev-tools/certs/ensure-dev-certs.sh" ENSURE_ENV_SCRIPT="$ROOT_DIR/dev-tools/ensure-local-compose-env.sh" # shellcheck disable=SC1091 # The repository root is resolved at runtime. source "$ROOT_DIR/dev-tools/smoke/run-owned-compose.sh" +export FIREMUD_SMOKE_INITIAL_ADMISSION_FIXTURE_ENABLED=false +export FIREMUD_SMOKE_INITIAL_ADMISSION_CAPABILITY_PATH=/app/run-owned-initial-admission-capability.json +unset FIREMUD_SMOKE_INITIAL_ADMISSION_CAPABILITY_HOST_PATH export TERM="${TERM:-dumb}" export COMPOSE_PROGRESS="${COMPOSE_PROGRESS:-plain}" @@ -41,6 +44,7 @@ require_run_owned_compose_project export FIREMUD_COMPOSE_GRPC_MTLS_CERT_ROOT="$FIREMUD_SMOKE_OWNERSHIP_DIR_RESOLVED/$FIREMUD_SMOKE_PROJECT_KEY.grpc-mtls" bash "$ENSURE_ENV_SCRIPT" bash "$ENSURE_CERTS_SCRIPT" --compose-mtls "$FIREMUD_COMPOSE_GRPC_MTLS_CERT_ROOT" +ensure_run_owned_initial_admission_capability "$FIREMUD_COMPOSE_GRPC_MTLS_CERT_ROOT" reuse-only bash "$BUILD_JARS_SCRIPT" docker compose "${COMPOSE_FILES[@]}" up -d --build --remove-orphans docker compose "${COMPOSE_FILES[@]}" restart diff --git a/dev-tools/verify-smoke-images.sh b/dev-tools/verify-smoke-images.sh index f662aa4252..440ee73263 100644 --- a/dev-tools/verify-smoke-images.sh +++ b/dev-tools/verify-smoke-images.sh @@ -22,6 +22,9 @@ SMOKE_COMPOSE_UP_ATTEMPTS="${SMOKE_COMPOSE_UP_ATTEMPTS:-3}" SMOKE_COMPOSE_UP_RETRY_DELAY_SECONDS="${SMOKE_COMPOSE_UP_RETRY_DELAY_SECONDS:-5}" # shellcheck disable=SC1091 # The repository root is resolved at runtime. source "$ROOT_DIR/dev-tools/smoke/run-owned-compose.sh" +export FIREMUD_SMOKE_INITIAL_ADMISSION_FIXTURE_ENABLED=false +export FIREMUD_SMOKE_INITIAL_ADMISSION_CAPABILITY_PATH=/app/run-owned-initial-admission-capability.json +unset FIREMUD_SMOKE_INITIAL_ADMISSION_CAPABILITY_HOST_PATH export TERM="${TERM:-dumb}" export COMPOSE_PROGRESS="${COMPOSE_PROGRESS:-plain}" @@ -220,6 +223,7 @@ fi claim_run_owned_compose_project export FIREMUD_COMPOSE_GRPC_MTLS_CERT_ROOT="$FIREMUD_SMOKE_OWNERSHIP_DIR_RESOLVED/$FIREMUD_SMOKE_PROJECT_KEY.grpc-mtls" bash "$ENSURE_CERTS_SCRIPT" --compose-mtls "$FIREMUD_COMPOSE_GRPC_MTLS_CERT_ROOT" +ensure_run_owned_initial_admission_capability "$FIREMUD_COMPOSE_GRPC_MTLS_CERT_ROOT" create-or-verify docker compose "${COMPOSE_FILES[@]}" down -v --remove-orphans compose_up_with_retry bash "$HEALTH_CHECK_SCRIPT" "${COMPOSE_FILES[@]}" diff --git a/docker/docker-compose.grpc-mtls.override.yml b/docker/docker-compose.grpc-mtls.override.yml index b3039ac50c..ab79427c42 100644 --- a/docker/docker-compose.grpc-mtls.override.yml +++ b/docker/docker-compose.grpc-mtls.override.yml @@ -53,8 +53,19 @@ services: game-session-service: 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 volumes: - ${FIREMUD_COMPOSE_GRPC_MTLS_CERT_ROOT:?canonical smoke must set a run-owned mTLS certificate root}/workloads/game-session-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 logging-admin-service: environment: diff --git a/protos/game-session/v1/game_session_service.proto b/protos/game-session/v1/game_session_service.proto index 7d111009d8..d0a6f8dc3e 100644 --- a/protos/game-session/v1/game_session_service.proto +++ b/protos/game-session/v1/game_session_service.proto @@ -38,6 +38,9 @@ service GameSessionControlPlaneService { returns (GetGameSessionPinConvergenceResponse); rpc GetGameInstanceRuntimeState(GetGameInstanceRuntimeStateRequest) returns (GetGameInstanceRuntimeStateResponse); + // Read exact durable owner proof for a World-owned initial-admission hold. + rpc GetInitialAdmissionBindProof(GetInitialAdmissionBindProofRequest) + returns (GetInitialAdmissionBindProofResponse); rpc ValidateBuiltInCommandAlias(ValidateBuiltInCommandAliasRequest) returns (ValidateBuiltInCommandAliasResponse); rpc ListAdmissionPointers(ListAdmissionPointersRequest) @@ -441,6 +444,56 @@ message ListAdmissionPointerAuditResponse { shared.v1.ErrorDetail error = 2; } +enum InitialAdmissionBindOwnerProofOutcome { + INITIAL_ADMISSION_BIND_OWNER_PROOF_OUTCOME_UNSPECIFIED = 0; + INITIAL_ADMISSION_BIND_OWNER_PROOF_OUTCOME_COMMITTED = 1; + INITIAL_ADMISSION_BIND_OWNER_PROOF_OUTCOME_ABORTED = 2; + INITIAL_ADMISSION_BIND_OWNER_PROOF_OUTCOME_NOT_FOUND = 3; + INITIAL_ADMISSION_BIND_OWNER_PROOF_OUTCOME_PENDING = 4; + INITIAL_ADMISSION_BIND_OWNER_PROOF_OUTCOME_UNAVAILABLE = 5; + INITIAL_ADMISSION_BIND_OWNER_PROOF_OUTCOME_ERROR = 6; +} + +message GetInitialAdmissionBindProofRequest { + string hold_id = 1; + string hold_fence = 2; + string tenant_id = 3; + string realm_uuid = 4; + string playable_state_namespace_uuid = 5; + entity_management.v1.PlayableStateScope playable_state_scope = 6; + string game_instance_id = 7; + string version_id = 8; + int64 active_lifecycle_epoch = 9; + string initial_admission_request_id = 10; + string request_digest = 11; + bool expected_no_prior_pointer = 12; + int64 expected_catalog_revision = 13; +} + +message GetInitialAdmissionBindProofResponse { + // Echoes the complete request tuple so World can reject proof for another hold or target. + string hold_id = 1; + string hold_fence = 2; + string tenant_id = 3; + string realm_uuid = 4; + string playable_state_namespace_uuid = 5; + entity_management.v1.PlayableStateScope playable_state_scope = 6; + string game_instance_id = 7; + string version_id = 8; + int64 active_lifecycle_epoch = 9; + string initial_admission_request_id = 10; + string request_digest = 11; + bool expected_no_prior_pointer = 12; + int64 expected_catalog_revision = 13; + InitialAdmissionBindOwnerProofOutcome outcome = 14; + string owner_proof_id = 15; + string pointer_audit_id = 16; + int64 pointer_version = 17; + string pointer_audit_request_digest = 18; + bool future_commit_prevented = 19; + shared.v1.ErrorDetail error = 20; +} + message GetGameplayCommandStatusRequest { string command_id = 1; string tenant_id = 2; diff --git a/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/client/WorldManagementClient.java b/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/client/WorldManagementClient.java index f97efc97e8..caa6fbe87c 100644 --- a/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/client/WorldManagementClient.java +++ b/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/client/WorldManagementClient.java @@ -1,6 +1,7 @@ package net.firedevops.firemud.gamesession.client; import jakarta.annotation.PostConstruct; +import java.util.UUID; import java.util.concurrent.TimeUnit; import javax.net.ssl.SSLException; import net.firedevops.firemud.common.config.ServiceEndpointsProperties; @@ -8,6 +9,9 @@ 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.entitymanagement.v1.PlayableStateScope; +import net.firedevops.firemud.worldmanagement.v1.AcquireInitialAdmissionBindHoldRequest; +import net.firedevops.firemud.worldmanagement.v1.AcquireInitialAdmissionBindHoldResponse; import net.firedevops.firemud.worldmanagement.v1.ActivatePreparedWorldInstanceRequest; import net.firedevops.firemud.worldmanagement.v1.ActivatePreparedWorldInstanceResponse; import net.firedevops.firemud.worldmanagement.v1.FailPreparedWorldInstanceRequest; @@ -166,6 +170,74 @@ public GetWorldInstanceLifecycleResponse getWorldInstanceLifecycle( .build()); } + /** Acquires the one-shot World hold for an exact initial admission pointer bind. */ + public AcquireInitialAdmissionBindHoldResponse acquireInitialAdmissionBindHold( + long tenantId, + long gameInstanceId, + long versionId, + long activeLifecycleEpoch, + String initialAdmissionRequestId, + String requestDigest, + UUID realmId, + UUID playableStateNamespaceId, + PlayableStateScope playableStateScope, + long catalogRevision) { + return callStub() + .acquireInitialAdmissionBindHold( + buildAcquireInitialAdmissionBindHoldRequest( + tenantId, + gameInstanceId, + versionId, + activeLifecycleEpoch, + initialAdmissionRequestId, + requestDigest, + realmId, + playableStateNamespaceId, + playableStateScope, + catalogRevision)); + } + + static AcquireInitialAdmissionBindHoldRequest buildAcquireInitialAdmissionBindHoldRequest( + long tenantId, + long gameInstanceId, + long versionId, + long activeLifecycleEpoch, + String initialAdmissionRequestId, + String requestDigest, + UUID realmId, + UUID playableStateNamespaceId, + PlayableStateScope playableStateScope, + long catalogRevision) { + if (tenantId <= 0L + || gameInstanceId <= 0L + || versionId <= 0L + || activeLifecycleEpoch <= 0L + || catalogRevision <= 0L + || initialAdmissionRequestId == null + || initialAdmissionRequestId.isBlank() + || initialAdmissionRequestId.length() > 128 + || requestDigest == null + || !requestDigest.matches("[0-9a-f]{64}") + || realmId == null + || playableStateNamespaceId == null + || playableStateScope != PlayableStateScope.PLAYABLE_STATE_SCOPE_SHARED) { + throw new IllegalArgumentException("Initial admission bind request is incomplete"); + } + return AcquireInitialAdmissionBindHoldRequest.newBuilder() + .setTenantId(Long.toString(tenantId)) + .setGameInstanceId(Long.toString(gameInstanceId)) + .setVersionId(Long.toString(versionId)) + .setExpectedActiveLifecycleEpoch(activeLifecycleEpoch) + .setInitialAdmissionRequestId(initialAdmissionRequestId) + .setRequestDigest(requestDigest) + .setRealmUuid(realmId.toString()) + .setPlayableStateNamespaceUuid(playableStateNamespaceId.toString()) + .setPlayableStateScope(playableStateScope) + .setExpectedNoPriorPointer(true) + .setExpectedCatalogRevision(catalogRevision) + .build(); + } + public TerminateWorldInstanceResponse terminateWorldInstance( long tenantId, long gameInstanceId, diff --git a/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/command/text/GameplayWorldCatalog.java b/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/command/text/GameplayWorldCatalog.java index c64d2f7b74..f867346a5f 100644 --- a/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/command/text/GameplayWorldCatalog.java +++ b/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/command/text/GameplayWorldCatalog.java @@ -318,14 +318,24 @@ public List visibleWorldsFromAuthoritySnapshot() { throw new AuthorityPointerUnavailableException( "Authoritative gameplay pointer list is unavailable"); } + Set invalidTenants = new java.util.HashSet<>(); for (GameplayAdmissionPointerSnapshot pointer : pointers) { - if (!hasCompleteAuthorityPointer(pointer)) { + if (pointer == null) { + throw new AuthorityPointerUnavailableException( + "Authoritative gameplay pointer identity is unavailable"); + } + if (pointer.tenantId() <= 0L) { throw new AuthorityPointerUnavailableException( - "Authoritative gameplay pointer is incomplete"); + "Authoritative gameplay pointer tenant identity is unavailable"); + } + if (!hasCompleteAuthorityPointer(pointer)) { + invalidTenants.add(pointer.tenantId()); } } - requireExactlyOneVisiblePublicProductionRealmPerTenant(pointers); - return toWorlds(pointers).stream().filter(this::hasVisibleRealmEntries).toList(); + invalidTenants.addAll(tenantsWithoutExactlyOneVisiblePublicProductionRealm(pointers)); + List healthyTenantPointers = + pointers.stream().filter(pointer -> !invalidTenants.contains(pointer.tenantId())).toList(); + return toWorlds(healthyTenantPointers).stream().filter(this::hasVisibleRealmEntries).toList(); } /** @@ -479,7 +489,7 @@ private static List toWorlds(List p .toList()); } - private static void requireExactlyOneVisiblePublicProductionRealmPerTenant( + private static Set tenantsWithoutExactlyOneVisiblePublicProductionRealm( List pointers) { Set tenantIds = pointers.stream() @@ -491,12 +501,9 @@ private static void requireExactlyOneVisiblePublicProductionRealmPerTenant( publicRealmCounts.merge(pointer.tenantId(), 1L, Long::sum); } } - for (long tenantId : tenantIds) { - if (publicRealmCounts.getOrDefault(tenantId, 0L) != 1L) { - throw new AuthorityPointerUnavailableException( - "Authoritative public-production realm count is invalid for tenant " + tenantId); - } - } + return tenantIds.stream() + .filter(tenantId -> publicRealmCounts.getOrDefault(tenantId, 0L) != 1L) + .collect(Collectors.toUnmodifiableSet()); } private static boolean hasCompleteAuthorityPointer(GameplayAdmissionPointerSnapshot pointer) { diff --git a/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/data/GameplayAdmissionPointerBootstrapInitializer.java b/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/data/GameplayAdmissionPointerBootstrapInitializer.java index 7366638efa..ff20b08950 100644 --- a/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/data/GameplayAdmissionPointerBootstrapInitializer.java +++ b/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/data/GameplayAdmissionPointerBootstrapInitializer.java @@ -41,6 +41,12 @@ public void run(ApplicationArguments args) { } List pointers = bootstrapProperties.getPointers(); + if (pointers != null && pointers.isEmpty()) { + LOGGER.warn( + "Skipping gameplay admission pointer bootstrap because no pointer seeds are configured; " + + "admission remains closed"); + return; + } validateSeeds(pointers); LOGGER.warn( "Skipping configured gameplay admission pointer bootstrap because owner-validated " @@ -49,7 +55,7 @@ public void run(ApplicationArguments args) { private static void validateSeeds( List pointers) { - if (pointers == null || pointers.isEmpty()) { + if (pointers == null) { throw new IllegalArgumentException("Gameplay admission pointer bootstrap seeds are required"); } diff --git a/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/data/RunOwnedInitialAdmissionFixtureCapability.java b/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/data/RunOwnedInitialAdmissionFixtureCapability.java new file mode 100644 index 0000000000..663cca43de --- /dev/null +++ b/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/data/RunOwnedInitialAdmissionFixtureCapability.java @@ -0,0 +1,438 @@ +package net.firedevops.firemud.gamesession.data; + +import java.io.ByteArrayInputStream; +import java.io.ByteArrayOutputStream; +import java.io.IOException; +import java.io.InputStream; +import java.nio.channels.Channels; +import java.nio.channels.SeekableByteChannel; +import java.nio.charset.CharacterCodingException; +import java.nio.charset.CodingErrorAction; +import java.nio.charset.StandardCharsets; +import java.nio.file.Files; +import java.nio.file.LinkOption; +import java.nio.file.Path; +import java.nio.file.StandardOpenOption; +import java.nio.file.attribute.BasicFileAttributes; +import java.nio.file.attribute.PosixFilePermission; +import java.security.MessageDigest; +import java.security.NoSuchAlgorithmException; +import java.security.cert.Certificate; +import java.security.cert.CertificateFactory; +import java.security.cert.X509Certificate; +import java.util.Collection; +import java.util.HashSet; +import java.util.HexFormat; +import java.util.List; +import java.util.Set; +import java.util.UUID; +import java.util.regex.Pattern; +import net.firedevops.firemud.common.grpc.CommonGrpcClientProperties; +import net.firedevops.firemud.common.grpc.GrpcPeerIdentity; +import org.springframework.core.io.ClassPathResource; +import tools.jackson.core.JacksonException; +import tools.jackson.core.StreamReadFeature; +import tools.jackson.databind.JsonNode; +import tools.jackson.databind.ObjectMapper; +import tools.jackson.databind.json.JsonMapper; + +/** Strict, run-bound authority to activate the local initial-admission fixture coordinator. */ +record RunOwnedInitialAdmissionFixtureCapability( + String runId, + String composeProjectName, + String operationId, + long tenantId, + long gameTemplateId, + long ownerAccountId, + String worldSlug, + String worldDisplayName, + String realmSlug, + String realmDisplayName, + boolean visible, + boolean publicProductionRealm, + boolean requiresCharacterSelection, + String stateScope, + String characterCreationPolicy, + String gameSessionLeafSha256, + String gameSessionUriSan, + String caCertificateSha256) { + public static final String CAPABILITY_SCHEMA = "firemud.run-owned-initial-admission-fixture.v1"; + public static final String GAME_SESSION_URI_SAN = + "spiffe://firemud/ns/dev/sa/game-session-service"; + public static final String WORLD_SLUG = "demo"; + public static final String WORLD_DISPLAY_NAME = "Demo World"; + 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"; + + private static final int MAX_CAPABILITY_BYTES = 16 * 1024; + private static final int MAX_CERTIFICATE_FILE_BYTES = 1024 * 1024; + private static final Pattern SAFE_ID = Pattern.compile("[a-z0-9][a-z0-9-]{0,127}"); + private static final Pattern SHA_256 = Pattern.compile("[0-9a-f]{64}"); + private static final Set ALLOWED_FIELDS = + Set.of( + "schema", + "runId", + "composeProjectName", + "operationId", + "tenantId", + "gameTemplateId", + "ownerAccountId", + "worldSlug", + "worldDisplayName", + "realmSlug", + "realmDisplayName", + "visible", + "publicProductionRealm", + "requiresCharacterSelection", + "stateScope", + "characterCreationPolicy", + "gameSessionLeafSha256", + "gameSessionUriSan", + "caCertificateSha256"); + private static final ObjectMapper STRICT_JSON_MAPPER = + JsonMapper.builder().enable(StreamReadFeature.STRICT_DUPLICATE_DETECTION).build(); + + /** + * Loads and validates the declared local capability against the active run/project and the actual + * certificate files configured for this Game Session process. + */ + static RunOwnedInitialAdmissionFixtureCapability load( + Path capabilityPath, + String expectedRunId, + String expectedComposeProjectName, + CommonGrpcClientProperties grpcProperties) { + requireExpectedRunBinding(expectedRunId, expectedComposeProjectName); + byte[] capabilityBytes = readCapability(capabilityPath); + CertificatePins certificatePins = configuredCertificatePins(grpcProperties); + return parseAndValidate( + capabilityBytes, expectedRunId, expectedComposeProjectName, certificatePins); + } + + static RunOwnedInitialAdmissionFixtureCapability parseAndValidate( + byte[] capabilityBytes, + String expectedRunId, + String expectedComposeProjectName, + CertificatePins certificatePins) { + requireExpectedRunBinding(expectedRunId, expectedComposeProjectName); + if (capabilityBytes == null + || capabilityBytes.length == 0 + || capabilityBytes.length > MAX_CAPABILITY_BYTES + || certificatePins == null) { + throw invalidCapability(); + } + + JsonNode root; + try { + String json = decodeUtf8(capabilityBytes); + root = STRICT_JSON_MAPPER.readTree(json); + } catch (CharacterCodingException | JacksonException exception) { + throw invalidCapability(); + } + if (root == null || !root.isObject() || !exactFields(root)) { + throw invalidCapability(); + } + + String schema = requiredText(root, "schema"); + String runId = requiredText(root, "runId"); + String composeProjectName = requiredText(root, "composeProjectName"); + String operationId = requiredText(root, "operationId"); + long tenantId = requiredPositiveLong(root, "tenantId"); + long gameTemplateId = requiredPositiveLong(root, "gameTemplateId"); + long ownerAccountId = requiredPositiveLong(root, "ownerAccountId"); + String worldSlug = requiredText(root, "worldSlug"); + String worldDisplayName = requiredText(root, "worldDisplayName"); + String realmSlug = requiredText(root, "realmSlug"); + String realmDisplayName = requiredText(root, "realmDisplayName"); + JsonNode visible = root.get("visible"); + JsonNode publicProductionRealm = root.get("publicProductionRealm"); + JsonNode characterSelection = root.get("requiresCharacterSelection"); + String stateScope = requiredText(root, "stateScope"); + String characterCreationPolicy = requiredText(root, "characterCreationPolicy"); + String leafSha256 = requiredText(root, "gameSessionLeafSha256"); + String uriSan = requiredText(root, "gameSessionUriSan"); + String caSha256 = requiredText(root, "caCertificateSha256"); + + if (!CAPABILITY_SCHEMA.equals(schema) + || !runId.equals(expectedRunId) + || !composeProjectName.equals(expectedComposeProjectName) + || !SAFE_ID.matcher(runId).matches() + || !SAFE_ID.matcher(composeProjectName).matches() + || !isCanonicalUuid(operationId) + || !WORLD_SLUG.equals(worldSlug) + || !WORLD_DISPLAY_NAME.equals(worldDisplayName) + || !REALM_SLUG.equals(realmSlug) + || !REALM_DISPLAY_NAME.equals(realmDisplayName) + || visible == null + || !visible.isBoolean() + || !visible.booleanValue() + || publicProductionRealm == null + || !publicProductionRealm.isBoolean() + || !publicProductionRealm.booleanValue() + || characterSelection == null + || !characterSelection.isBoolean() + || characterSelection.booleanValue() + || !STATE_SCOPE.equals(stateScope) + || !CHARACTER_CREATION_POLICY.equals(characterCreationPolicy) + || !SHA_256.matcher(leafSha256).matches() + || !GAME_SESSION_URI_SAN.equals(uriSan) + || !SHA_256.matcher(caSha256).matches() + || !certificatePins.leafSha256().equals(leafSha256) + || !certificatePins.uriSan().equals(uriSan) + || !certificatePins.caSha256().equals(caSha256)) { + throw invalidCapability(); + } + + return new RunOwnedInitialAdmissionFixtureCapability( + runId, + composeProjectName, + operationId, + tenantId, + gameTemplateId, + ownerAccountId, + worldSlug, + worldDisplayName, + realmSlug, + realmDisplayName, + true, + true, + false, + stateScope, + characterCreationPolicy, + leafSha256, + uriSan, + caSha256); + } + + static CertificatePins certificatePins(X509Certificate leaf, X509Certificate ca) { + if (leaf == null || ca == null || ca.getBasicConstraints() < 0) { + throw invalidCapability(); + } + String uriSan = + GrpcPeerIdentity.fromCertificate(leaf) + .map(GrpcPeerIdentity::uri) + .filter(GAME_SESSION_URI_SAN::equals) + .orElseThrow(RunOwnedInitialAdmissionFixtureCapability::invalidCapability); + try { + leaf.checkValidity(); + ca.checkValidity(); + leaf.verify(ca.getPublicKey()); + return new CertificatePins(fingerprint(leaf), uriSan, fingerprint(ca)); + } catch (Exception exception) { + throw invalidCapability(); + } + } + + private static CertificatePins configuredCertificatePins( + CommonGrpcClientProperties grpcProperties) { + if (grpcProperties == null + || grpcProperties.isPlaintext() + || !hasText(grpcProperties.getCertChain()) + || !hasText(grpcProperties.getCaCert())) { + throw invalidCapability(); + } + try { + List chain = + certificates(readConfiguredTlsFile(grpcProperties.getCertChain())); + List authorities = + certificates(readConfiguredTlsFile(grpcProperties.getCaCert())); + if (chain.isEmpty() || authorities.size() != 1) { + throw invalidCapability(); + } + return certificatePins(chain.getFirst(), authorities.getFirst()); + } catch (IOException | RuntimeException exception) { + throw invalidCapability(); + } + } + + private static byte[] readConfiguredTlsFile(String configuredPath) throws IOException { + byte[] bytes; + if (configuredPath.startsWith("classpath:")) { + ClassPathResource resource = + new ClassPathResource(configuredPath.substring("classpath:".length())); + try (InputStream input = resource.getInputStream()) { + bytes = input.readNBytes(MAX_CERTIFICATE_FILE_BYTES + 1); + } + } else { + try (InputStream input = Files.newInputStream(Path.of(configuredPath))) { + bytes = input.readNBytes(MAX_CERTIFICATE_FILE_BYTES + 1); + } + } + if (bytes.length == 0 || bytes.length > MAX_CERTIFICATE_FILE_BYTES) { + throw new IOException("Configured TLS certificate material is not bounded"); + } + return bytes; + } + + private static List certificates(byte[] pemBytes) throws IOException { + try { + Collection certificates = + CertificateFactory.getInstance("X.509") + .generateCertificates(new ByteArrayInputStream(pemBytes)); + return certificates.stream() + .filter(X509Certificate.class::isInstance) + .map(X509Certificate.class::cast) + .toList(); + } catch (java.security.cert.CertificateException exception) { + throw new IOException("Configured TLS certificate material could not be parsed", exception); + } + } + + private static String fingerprint(X509Certificate certificate) { + try { + return HexFormat.of() + .formatHex(MessageDigest.getInstance("SHA-256").digest(certificate.getEncoded())); + } catch (NoSuchAlgorithmException | java.security.cert.CertificateEncodingException exception) { + throw invalidCapability(); + } + } + + private static byte[] readCapability(Path path) { + if (path == null || !path.isAbsolute()) { + throw invalidCapability(); + } + try { + BasicFileAttributes before = + Files.readAttributes(path, BasicFileAttributes.class, LinkOption.NOFOLLOW_LINKS); + if (!before.isRegularFile() + || Files.isSymbolicLink(path) + || before.size() <= 0L + || before.size() > MAX_CAPABILITY_BYTES + || !isReadOnly(path)) { + throw invalidCapability(); + } + + ByteArrayOutputStream bytes = new ByteArrayOutputStream((int) before.size()); + try (SeekableByteChannel channel = + Files.newByteChannel(path, StandardOpenOption.READ, LinkOption.NOFOLLOW_LINKS); + InputStream input = Channels.newInputStream(channel)) { + byte[] buffer = new byte[1024]; + int read; + while ((read = input.read(buffer)) >= 0) { + if (read == 0) { + continue; + } + if (bytes.size() + read > MAX_CAPABILITY_BYTES) { + throw invalidCapability(); + } + bytes.write(buffer, 0, read); + } + } + + BasicFileAttributes after = + Files.readAttributes(path, BasicFileAttributes.class, LinkOption.NOFOLLOW_LINKS); + if (!after.isRegularFile() + || Files.isSymbolicLink(path) + || before.size() != after.size() + || !before.lastModifiedTime().equals(after.lastModifiedTime()) + || !sameFileKey(before.fileKey(), after.fileKey()) + || !isReadOnly(path)) { + throw invalidCapability(); + } + return bytes.toByteArray(); + } catch (IOException | SecurityException exception) { + throw invalidCapability(); + } + } + + private static boolean isReadOnly(Path path) throws IOException { + try { + Set permissions = + Files.getPosixFilePermissions(path, LinkOption.NOFOLLOW_LINKS); + return permissions.contains(PosixFilePermission.OWNER_READ) + && !permissions.contains(PosixFilePermission.OWNER_WRITE) + && !permissions.contains(PosixFilePermission.GROUP_WRITE) + && !permissions.contains(PosixFilePermission.OTHERS_WRITE); + } catch (UnsupportedOperationException exception) { + Object readOnly = Files.getAttribute(path, "dos:readonly", LinkOption.NOFOLLOW_LINKS); + return Boolean.TRUE.equals(readOnly) && !Files.isWritable(path); + } + } + + private static boolean exactFields(JsonNode root) { + Set fields = new HashSet<>(); + root.properties().forEach(property -> fields.add(property.getKey())); + return fields.equals(ALLOWED_FIELDS); + } + + private static long requiredPositiveLong(JsonNode root, String field) { + JsonNode value = root.get(field); + if (value == null || !value.isIntegralNumber() || !value.canConvertToLong()) { + throw invalidCapability(); + } + long parsed = value.longValue(); + if (parsed <= 0L) { + throw invalidCapability(); + } + return parsed; + } + + private static String requiredText(JsonNode root, String field) { + JsonNode value = root.get(field); + if (value == null || !value.isString()) { + throw invalidCapability(); + } + String parsed = value.textValue(); + if (parsed.isBlank() + || parsed.length() > 256 + || !parsed.equals(parsed.trim()) + || parsed.indexOf('\n') >= 0 + || parsed.indexOf('\r') >= 0) { + throw invalidCapability(); + } + return parsed; + } + + private static String decodeUtf8(byte[] bytes) throws CharacterCodingException { + return StandardCharsets.UTF_8 + .newDecoder() + .onMalformedInput(CodingErrorAction.REPORT) + .onUnmappableCharacter(CodingErrorAction.REPORT) + .decode(java.nio.ByteBuffer.wrap(bytes)) + .toString(); + } + + private static void requireExpectedRunBinding(String runId, String projectName) { + if (runId == null + || projectName == null + || !SAFE_ID.matcher(runId).matches() + || !SAFE_ID.matcher(projectName).matches()) { + throw invalidCapability(); + } + } + + private static boolean isCanonicalUuid(String value) { + try { + return UUID.fromString(value).toString().equals(value); + } catch (IllegalArgumentException | NullPointerException exception) { + return false; + } + } + + private static boolean sameFileKey(Object before, Object after) { + return before == null || after == null || before.equals(after); + } + + private static boolean hasText(String value) { + return value != null && !value.isBlank(); + } + + private static InvalidCapabilityException invalidCapability() { + return new InvalidCapabilityException(); + } + + @Override + public String toString() { + return "RunOwnedInitialAdmissionFixtureCapability[verified]"; + } + + record CertificatePins(String leafSha256, String uriSan, String caSha256) {} + + /** Generic, content-free failure so callers cannot accidentally log capability contents. */ + public static final class InvalidCapabilityException extends IllegalArgumentException { + private InvalidCapabilityException() { + super("Run-owned initial-admission fixture capability is invalid"); + } + } +} 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 new file mode 100644 index 0000000000..ed548a8347 --- /dev/null +++ b/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/data/RunOwnedInitialAdmissionFixtureCoordinator.java @@ -0,0 +1,488 @@ +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 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<>(); + + public RunOwnedInitialAdmissionFixtureCoordinator( + @Value("${FIREMUD_SMOKE_INITIAL_ADMISSION_FIXTURE_ENABLED:false}") boolean enabled, + @Value("${FIREMUD_SMOKE_INITIAL_ADMISSION_CAPABILITY_PATH:}") String capabilityPath, + @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.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(); + } + BootstrapResult result = coordinate(capability); + 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) { + 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."); + } else { + logger.warn( + "Run-owned initial-admission fixture attempt {}/{} remains unresolved; the same" + + " stable operation identity will be retried.", + attempt, + MAX_ATTEMPTS); + } + } finally { + inProgress.set(false); + } + } + + BootstrapResult coordinate(RunOwnedInitialAdmissionFixtureCapability capability) { + Objects.requireNonNull(capability, "capability"); + RunOwnedInitialLaunchResult launch = + gameInstanceService.startRunOwnedInitialLaunch( + new StartSessionRequest( + capability.tenantId(), + capability.gameTemplateId(), + capability.operationId(), + capability.ownerAccountId())); + 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 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) { + try { + return UUID.fromString(value).toString().equals(value); + } catch (IllegalArgumentException | NullPointerException exception) { + return false; + } + } + + private static boolean isCanonicalPositiveLong(String value) { + try { + long parsed = Long.parseLong(value); + return parsed > 0L && Long.toString(parsed).equals(value); + } catch (NumberFormatException | NullPointerException exception) { + return false; + } + } + + private static RuntimeException unresolved() { + return new IllegalStateException("Run-owned initial-admission fixture remains unresolved"); + } + + enum BootstrapResult { + COMMITTED, + ABORTED + } +} diff --git a/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/data/TestDataSeeder.java b/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/data/TestDataSeeder.java index 7a961bc516..29f6017fd4 100644 --- a/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/data/TestDataSeeder.java +++ b/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/data/TestDataSeeder.java @@ -2,10 +2,8 @@ import lombok.RequiredArgsConstructor; import net.firedevops.firemud.gamesession.entity.FeatureFlag; -import net.firedevops.firemud.gamesession.entity.GameInstance; import net.firedevops.firemud.gamesession.entity.GameManifest; import net.firedevops.firemud.gamesession.repository.FeatureFlagRepository; -import net.firedevops.firemud.gamesession.repository.GameInstanceRepository; import net.firedevops.firemud.gamesession.repository.GameManifestRepository; import org.springframework.boot.ApplicationArguments; import org.springframework.boot.ApplicationRunner; @@ -13,7 +11,7 @@ import org.springframework.stereotype.Component; import org.springframework.transaction.annotation.Transactional; -/** Seeds deterministic smoke/runtime records when local compose explicitly enables them. */ +/** Seeds deterministic smoke metadata when local compose explicitly enables it. */ @Component @ConditionalOnProperty( prefix = "firemud.smoke.seed-demo-runtime", @@ -24,7 +22,6 @@ public class TestDataSeeder implements ApplicationRunner { private final GameManifestRepository gameManifestRepository; private final FeatureFlagRepository featureFlagRepository; - private final GameInstanceRepository gameInstanceRepository; @Override @Transactional @@ -44,15 +41,5 @@ public void run(ApplicationArguments args) { flag.setName("double_xp"); flag.setEnabled(true); featureFlagRepository.save(flag); - - GameInstance instance = - gameInstanceRepository - .findFirstByTenantIdAndOwnerAccountIdAndStatus(1L, 1L, "RUNNING") - .orElseGet(GameInstance::new); - instance.setTenantId(1L); - instance.setRuntimeVersion("v1.0.0"); - instance.setOwnerAccountId(1L); - instance.setStatus("RUNNING"); - gameInstanceRepository.save(instance); } } diff --git a/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/entity/GameInstance.java b/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/entity/GameInstance.java index 8c140100dc..ea0d5a26d1 100644 --- a/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/entity/GameInstance.java +++ b/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/entity/GameInstance.java @@ -25,4 +25,9 @@ public class GameInstance { private Long ownerAccountId; private String status; private Long rowVersion; + private String runOwnedStartRequestId; + private String runOwnedStartRequestDigest; + private String runOwnedStartPublishedReleaseBundleRef; + private Long runOwnedStartPreparingEpoch; + private Long runOwnedStartActiveEpoch; } diff --git a/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/repository/GameInstanceRepository.java b/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/repository/GameInstanceRepository.java index 8e886dc271..84907ee1a3 100644 --- a/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/repository/GameInstanceRepository.java +++ b/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/repository/GameInstanceRepository.java @@ -51,7 +51,12 @@ public class GameInstanceRepository { GAME_INSTANCES.SCRIPT_PATCH_PINNED_CONTROL_PLANE_REQUEST_ID, GAME_INSTANCES.OWNER_ACCOUNT_ID, GAME_INSTANCES.STATUS, - GAME_INSTANCES.ROW_VERSION + GAME_INSTANCES.ROW_VERSION, + GAME_INSTANCES.RUN_OWNED_START_REQUEST_ID, + GAME_INSTANCES.RUN_OWNED_START_REQUEST_DIGEST, + GAME_INSTANCES.RUN_OWNED_START_PUBLISHED_RELEASE_BUNDLE_REF, + GAME_INSTANCES.RUN_OWNED_START_PREPARING_EPOCH, + GAME_INSTANCES.RUN_OWNED_START_ACTIVE_EPOCH }; private final DSLContext dsl; @@ -64,6 +69,28 @@ public Optional findById(Long id) { return selectGameInstances().where(GAME_INSTANCES.ID.eq(id)).fetchOptional(this::toEntity); } + /** Serializes run-owned initial launch identity allocation within the caller's transaction. */ + @Transactional(propagation = Propagation.MANDATORY) + public void lockRunOwnedStartIdentity(long tenantId, String requestId) { + if (dsl.dialect().family() == org.jooq.SQLDialect.POSTGRES) { + String key = "run-owned-initial-launch:" + tenantId + ":" + requestId; + dsl.fetch("select pg_advisory_xact_lock(hashtextextended(cast(? as text), 0))", key); + } + } + + @Transactional(propagation = Propagation.MANDATORY) + public Optional findByTenantIdAndRunOwnedStartRequestIdForUpdate( + long tenantId, String requestId) { + return selectGameInstances() + .where( + GAME_INSTANCES + .TENANT_ID + .eq(tenantId) + .and(GAME_INSTANCES.RUN_OWNED_START_REQUEST_ID.eq(requestId))) + .forUpdate() + .fetchOptional(this::toEntity); + } + /** * Reads the authoritative game instance while holding its row lock. * @@ -163,6 +190,10 @@ public GameInstance save(GameInstance entity) { entity.getScriptPatchPinnedControlPlaneRequestId()) .set(GAME_INSTANCES.OWNER_ACCOUNT_ID, entity.getOwnerAccountId()) .set(GAME_INSTANCES.STATUS, entity.getStatus()) + .set( + GAME_INSTANCES.RUN_OWNED_START_PREPARING_EPOCH, + entity.getRunOwnedStartPreparingEpoch()) + .set(GAME_INSTANCES.RUN_OWNED_START_ACTIVE_EPOCH, entity.getRunOwnedStartActiveEpoch()) .set(GAME_INSTANCES.ROW_VERSION, nextRowVersion) .where( GAME_INSTANCES @@ -858,6 +889,12 @@ private void populate(GameInstancesRecord record, GameInstance entity) { entity.getScriptPatchPinnedControlPlaneRequestId()); record.setOwnerAccountId(entity.getOwnerAccountId()); record.setStatus(entity.getStatus()); + record.setRunOwnedStartRequestId(entity.getRunOwnedStartRequestId()); + record.setRunOwnedStartRequestDigest(entity.getRunOwnedStartRequestDigest()); + record.setRunOwnedStartPublishedReleaseBundleRef( + entity.getRunOwnedStartPublishedReleaseBundleRef()); + record.setRunOwnedStartPreparingEpoch(entity.getRunOwnedStartPreparingEpoch()); + record.setRunOwnedStartActiveEpoch(entity.getRunOwnedStartActiveEpoch()); } private GameInstance toEntity(Record record) { @@ -883,6 +920,13 @@ private GameInstance toEntity(Record record) { entity.setOwnerAccountId(record.get(GAME_INSTANCES.OWNER_ACCOUNT_ID)); entity.setStatus(record.get(GAME_INSTANCES.STATUS)); entity.setRowVersion(record.get(GAME_INSTANCES.ROW_VERSION)); + entity.setRunOwnedStartRequestId(record.get(GAME_INSTANCES.RUN_OWNED_START_REQUEST_ID)); + entity.setRunOwnedStartRequestDigest(record.get(GAME_INSTANCES.RUN_OWNED_START_REQUEST_DIGEST)); + entity.setRunOwnedStartPublishedReleaseBundleRef( + record.get(GAME_INSTANCES.RUN_OWNED_START_PUBLISHED_RELEASE_BUNDLE_REF)); + entity.setRunOwnedStartPreparingEpoch( + record.get(GAME_INSTANCES.RUN_OWNED_START_PREPARING_EPOCH)); + entity.setRunOwnedStartActiveEpoch(record.get(GAME_INSTANCES.RUN_OWNED_START_ACTIVE_EPOCH)); return entity; } } diff --git a/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/repository/GameplayAdmissionPointerRepository.java b/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/repository/GameplayAdmissionPointerRepository.java index 60748667ed..c9edce2d3a 100644 --- a/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/repository/GameplayAdmissionPointerRepository.java +++ b/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/repository/GameplayAdmissionPointerRepository.java @@ -14,6 +14,7 @@ import net.firedevops.firemud.gamesession.entity.GameplayAdmissionPointer; import net.firedevops.firemud.gamesession.jooq.tables.records.GameplayAdmissionPointerRecord; import net.firedevops.firemud.gamesession.service.AdmissionPointerVersionMismatchException; +import net.firedevops.firemud.gamesession.service.GameplayAdmissionCatalogPolicy; import org.jooq.DSLContext; import org.jooq.Record; import org.jooq.SQLDialect; @@ -130,7 +131,7 @@ public GameplayAdmissionPointer save(GameplayAdmissionPointer entity) { } boolean runtimeTargetChanged = !Objects.equals(entity.getGameInstanceId(), current.getGameInstanceId()); - boolean catalogChanged = !catalogPolicyMatches(current, entity); + boolean catalogChanged = !GameplayAdmissionCatalogPolicy.matches(current, entity); long expectedPointerVersion = runtimeTargetChanged ? Math.addExact(current.getPointerVersion(), 1L) @@ -318,20 +319,6 @@ private void populate(GameplayAdmissionPointerRecord record, GameplayAdmissionPo record.setUpdatedAt(toLocalDateTime(entity.getUpdatedAt())); } - private boolean catalogPolicyMatches( - GameplayAdmissionPointer current, GameplayAdmissionPointer requested) { - return Objects.equals(current.getWorldSlug(), requested.getWorldSlug()) - && Objects.equals(current.getWorldDisplayName(), requested.getWorldDisplayName()) - && Objects.equals(current.getRealmSlug(), requested.getRealmSlug()) - && Objects.equals(current.getRealmDisplayName(), requested.getRealmDisplayName()) - && current.isVisible() == requested.isVisible() - && current.isPublicProductionRealm() == requested.isPublicProductionRealm() - && current.isRequiresCharacterSelection() == requested.isRequiresCharacterSelection() - && Objects.equals(current.getStateScope(), requested.getStateScope()) - && Objects.equals( - current.getCharacterCreationPolicy(), requested.getCharacterCreationPolicy()); - } - private GameplayAdmissionPointer toEntity(Record record) { GameplayAdmissionPointer entity = new GameplayAdmissionPointer(); entity.setId(record.get(GAMEPLAY_ADMISSION_POINTER.ID)); diff --git a/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/repository/InitialAdmissionBindAttemptRepository.java b/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/repository/InitialAdmissionBindAttemptRepository.java index d7175c4f69..38184c7e6f 100644 --- a/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/repository/InitialAdmissionBindAttemptRepository.java +++ b/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/repository/InitialAdmissionBindAttemptRepository.java @@ -118,10 +118,17 @@ public InitialAdmissionBindAttempt attachHold( .set(GAMEPLAY_INITIAL_ADMISSION_BIND_ATTEMPT.HOLD_ID, holdId) .set(GAMEPLAY_INITIAL_ADMISSION_BIND_ATTEMPT.HOLD_FENCE, holdFence) .set(GAMEPLAY_INITIAL_ADMISSION_BIND_ATTEMPT.UPDATED_AT, toLocalDateTime(now)) - .where(GAMEPLAY_INITIAL_ADMISSION_BIND_ATTEMPT.ATTEMPT_ID.eq(attempt.attemptId())) + .where( + GAMEPLAY_INITIAL_ADMISSION_BIND_ATTEMPT + .ATTEMPT_ID + .eq(attempt.attemptId()) + .and(GAMEPLAY_INITIAL_ADMISSION_BIND_ATTEMPT.HOLD_ID.isNull()) + .and(GAMEPLAY_INITIAL_ADMISSION_BIND_ATTEMPT.HOLD_FENCE.isNull()) + .and(GAMEPLAY_INITIAL_ADMISSION_BIND_ATTEMPT.STATUS.eq(Status.PENDING.name()))) .execute(); if (updated != 1) { - throw new IllegalStateException("Initial admission attempt disappeared while attaching hold"); + throw new IllegalStateException( + "Initial admission attempt was not pending with an unattached hold"); } return findByTenantAndRequestId(attempt.tenantId(), attempt.initialAdmissionRequestId()) .orElseThrow(); diff --git a/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/service/GameInstanceService.java b/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/service/GameInstanceService.java index 361afe7f09..00770b63fa 100644 --- a/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/service/GameInstanceService.java +++ b/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/service/GameInstanceService.java @@ -11,6 +11,9 @@ default GameInstanceDto startSession(StartSessionRequest request) { GameInstanceDto startSession(StartSessionRequest request, boolean replaceExistingFirst); + /** Starts or resumes a non-replacing, run-owned local fixture launch. */ + RunOwnedInitialLaunchResult startRunOwnedInitialLaunch(StartSessionRequest request); + GameInstanceDto stopSession(long sessionId); GameInstanceDto restartSession(long sessionId); diff --git a/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/service/GameplayAdmissionCatalogPolicy.java b/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/service/GameplayAdmissionCatalogPolicy.java new file mode 100644 index 0000000000..752987f525 --- /dev/null +++ b/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/service/GameplayAdmissionCatalogPolicy.java @@ -0,0 +1,55 @@ +package net.firedevops.firemud.gamesession.service; + +import net.firedevops.firemud.gamesession.entity.GameplayAdmissionPointer; + +/** Compares the catalog-policy fields that determine an admission pointer's catalog revision. */ +public final class GameplayAdmissionCatalogPolicy { + private GameplayAdmissionCatalogPolicy() {} + + public static boolean matches( + GameplayAdmissionPointer current, GameplayAdmissionPointer requested) { + return fields(current).equals(fields(requested)); + } + + public static boolean matches( + GameplayAdmissionPointer current, GameplayAdmissionPointerMutation requested) { + return fields(current).equals(fields(requested)); + } + + private static CatalogFields fields(GameplayAdmissionPointer pointer) { + return new CatalogFields( + pointer.getWorldSlug(), + pointer.getWorldDisplayName(), + pointer.getRealmSlug(), + pointer.getRealmDisplayName(), + pointer.isVisible(), + pointer.isPublicProductionRealm(), + pointer.isRequiresCharacterSelection(), + pointer.getStateScope(), + pointer.getCharacterCreationPolicy()); + } + + private static CatalogFields fields(GameplayAdmissionPointerMutation mutation) { + return new CatalogFields( + mutation.worldSlug(), + mutation.worldDisplayName(), + mutation.realmSlug(), + mutation.realmDisplayName(), + mutation.visible(), + mutation.publicProductionRealm(), + mutation.requiresCharacterSelection(), + mutation.stateScope(), + mutation.characterCreationPolicy()); + } + + private record CatalogFields( + String worldSlug, + String worldDisplayName, + String realmSlug, + String realmDisplayName, + boolean visible, + boolean publicProductionRealm, + boolean requiresCharacterSelection, + String stateScope, + String characterCreationPolicy) {} +} diff --git a/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/service/RunOwnedInitialLaunchResult.java b/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/service/RunOwnedInitialLaunchResult.java new file mode 100644 index 0000000000..e914e27cf1 --- /dev/null +++ b/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/service/RunOwnedInitialLaunchResult.java @@ -0,0 +1,7 @@ +package net.firedevops.firemud.gamesession.service; + +import net.firedevops.firemud.gamesession.dto.GameInstanceDto; + +/** Exact Game Session target returned after World owner readback proves ACTIVE. */ +public record RunOwnedInitialLaunchResult( + GameInstanceDto gameInstance, long activeLifecycleEpoch) {} diff --git a/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/service/impl/DatabaseGameplayAdmissionPointerAuthorityService.java b/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/service/impl/DatabaseGameplayAdmissionPointerAuthorityService.java index e3a7b9d134..0672df32e0 100644 --- a/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/service/impl/DatabaseGameplayAdmissionPointerAuthorityService.java +++ b/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/service/impl/DatabaseGameplayAdmissionPointerAuthorityService.java @@ -10,6 +10,7 @@ import net.firedevops.firemud.gamesession.repository.GameplayAdmissionPointerEventRepository; import net.firedevops.firemud.gamesession.repository.GameplayAdmissionPointerRepository; import net.firedevops.firemud.gamesession.service.AdmissionPointerVersionMismatchException; +import net.firedevops.firemud.gamesession.service.GameplayAdmissionCatalogPolicy; import net.firedevops.firemud.gamesession.service.GameplayAdmissionPointerAuditEntry; import net.firedevops.firemud.gamesession.service.GameplayAdmissionPointerAuthorityService; import net.firedevops.firemud.gamesession.service.GameplayAdmissionPointerMutation; @@ -86,7 +87,7 @@ public GameplayAdmissionPointerSnapshot upsertPointer(GameplayAdmissionPointerMu enforceExpectedPointerVersion(pointer, mutation.expectedPointerVersion()); if (pointer.getId() != null && runtimeTargetMatches(pointer, mutation) - && catalogPolicyMatches(pointer, mutation)) { + && GameplayAdmissionCatalogPolicy.matches(pointer, mutation)) { return toSnapshot(pointer); } boolean runtimeTargetChanged = @@ -201,25 +202,12 @@ private long nextCatalogRevision( if (currentRevision == null || currentRevision <= 0L) { throw new IllegalStateException("Admission pointer catalog revision is missing or invalid"); } - if (!catalogPolicyMatches(pointer, mutation)) { + if (!GameplayAdmissionCatalogPolicy.matches(pointer, mutation)) { return Math.addExact(currentRevision, 1L); } return currentRevision; } - private boolean catalogPolicyMatches( - GameplayAdmissionPointer pointer, GameplayAdmissionPointerMutation mutation) { - return Objects.equals(pointer.getWorldSlug(), mutation.worldSlug()) - && Objects.equals(pointer.getWorldDisplayName(), mutation.worldDisplayName()) - && Objects.equals(pointer.getRealmSlug(), mutation.realmSlug()) - && Objects.equals(pointer.getRealmDisplayName(), mutation.realmDisplayName()) - && pointer.isVisible() == mutation.visible() - && pointer.isPublicProductionRealm() == mutation.publicProductionRealm() - && pointer.isRequiresCharacterSelection() == mutation.requiresCharacterSelection() - && Objects.equals(pointer.getStateScope(), mutation.stateScope()) - && Objects.equals(pointer.getCharacterCreationPolicy(), mutation.characterCreationPolicy()); - } - private boolean runtimeTargetMatches( GameplayAdmissionPointer pointer, GameplayAdmissionPointerMutation mutation) { return Objects.equals(pointer.getGameInstanceId(), mutation.gameInstanceId()); diff --git a/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/service/impl/GameInstanceServiceImpl.java b/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/service/impl/GameInstanceServiceImpl.java index e9ed0ced6b..b090816e15 100644 --- a/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/service/impl/GameInstanceServiceImpl.java +++ b/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/service/impl/GameInstanceServiceImpl.java @@ -2,7 +2,13 @@ import io.micrometer.core.annotation.Timed; import io.micrometer.core.instrument.MeterRegistry; +import java.nio.charset.StandardCharsets; +import java.security.MessageDigest; +import java.security.NoSuchAlgorithmException; import java.util.HashSet; +import java.util.HexFormat; +import java.util.Objects; +import java.util.Optional; import java.util.UUID; import net.firedevops.firemud.common.LoggingUtil; import net.firedevops.firemud.common.saga.SagaBuilder; @@ -21,6 +27,7 @@ import net.firedevops.firemud.gamesession.mapper.GameInstanceMapper; import net.firedevops.firemud.gamesession.repository.GameInstanceRepository; import net.firedevops.firemud.gamesession.service.GameInstanceService; +import net.firedevops.firemud.gamesession.service.RunOwnedInitialLaunchResult; import net.firedevops.firemud.gamesession.service.SessionStateService; import net.firedevops.firemud.worldmanagement.v1.ActivatePreparedWorldInstanceResponse; import net.firedevops.firemud.worldmanagement.v1.FailPreparedWorldInstanceResponse; @@ -47,6 +54,8 @@ public class GameInstanceServiceImpl implements GameInstanceService { private static final String STATUS_RUNNING = "RUNNING"; private static final String STATUS_STOPPING = "STOPPING"; private static final String STATUS_STOPPED = "STOPPED"; + private static final String RUN_OWNED_LAUNCH_DIGEST_SCHEMA = + "firemud.run-owned-initial-launch/v1"; private static final String SUPPORTED_RELEASE_ATTESTATION_SCHEMA_VERSION = "v1"; private static final String WORLD_ACTIVATION_AUTHORITY_UNAVAILABLE = "world activation authority unavailable"; @@ -227,6 +236,123 @@ public GameInstanceDto startSession(StartSessionRequest request, boolean replace return finalized; } + /** + * Starts or resumes a local fixture launch under a durable, tenant/request-bound owner identity. + * This method has no transport binding; the run-owned fixture coordinator is its only caller. + */ + @Override + @Timed(value = "gamesession.run_owned_initial_launch") + public RunOwnedInitialLaunchResult startRunOwnedInitialLaunch(StartSessionRequest request) { + validateRunOwnedLaunchRequest(request); + ResolvedLaunchDescriptor resolvedLaunchDescriptor = preflightLaunch(request); + requireDescriptorMatchesRequest(request, resolvedLaunchDescriptor); + String requestDigest = runOwnedLaunchRequestDigest(request); + GameInstance reserved = + inTransaction( + () -> reserveRunOwnedInitialLaunch(request, resolvedLaunchDescriptor, requestDigest), + "reserve run-owned initial launch"); + long gameInstanceId = reserved.getId(); + requireRunOwnedTargetCanResume(reserved); + + if (STATUS_RUNNING.equals(reserved.getStatus())) { + long activeEpoch = requireRunOwnedRecordedActiveEpoch(reserved); + WorldInstanceLifecycleSnapshot current = + readRunOwnedWorldLifecycle(reserved, request, resolvedLaunchDescriptor); + if (current.getStatus() + == WorldInstanceLifecycleStatus.WORLD_INSTANCE_LIFECYCLE_STATUS_PREPARING) { + throw new IllegalStateException( + "RUN_OWNED_INITIAL_LAUNCH_STATE_MISMATCH: running owner row is not ACTIVE in World"); + } + if (current.getStatus() + != WorldInstanceLifecycleStatus.WORLD_INSTANCE_LIFECYCLE_STATUS_ACTIVE) { + throw runOwnedWorldStatusFailure(current.getStatus()); + } + requireRunOwnedActiveEpoch(current, activeEpoch); + sessionStateService.saveState(withStatus(snapshot(reserved), STATUS_RUNNING)); + GameInstance completed = + inTransaction( + () -> + completeRunOwnedInitialLaunch( + request, + requestDigest, + resolvedLaunchDescriptor, + gameInstanceId, + activeEpoch), + "complete run-owned initial launch retry"); + return new RunOwnedInitialLaunchResult(snapshot(completed), activeEpoch); + } + + validateStartDependencies(); + + WorldInstanceLifecycleSnapshot prepared = + prepareRunOwnedWorldInstance(reserved, resolvedLaunchDescriptor, request); + if (prepared.getStatus() + == WorldInstanceLifecycleStatus.WORLD_INSTANCE_LIFECYCLE_STATUS_PREPARING) { + reserved = + inTransaction( + () -> + recordRunOwnedPreparingEpoch( + request, + requestDigest, + resolvedLaunchDescriptor, + gameInstanceId, + prepared.getLifecycleEpoch()), + "record run-owned preparing epoch"); + } else { + reserved = + reloadRunOwnedInitialLaunch( + request, requestDigest, resolvedLaunchDescriptor, gameInstanceId); + } + + WorldInstanceLifecycleSnapshot current = + readRunOwnedWorldLifecycle(reserved, request, resolvedLaunchDescriptor); + long activeEpoch; + if (current.getStatus() + == WorldInstanceLifecycleStatus.WORLD_INSTANCE_LIFECYCLE_STATUS_PREPARING) { + if (STATUS_RUNNING.equals(reserved.getStatus())) { + throw new IllegalStateException( + "RUN_OWNED_INITIAL_LAUNCH_STATE_MISMATCH: running owner row is not ACTIVE in World"); + } + if (reserved.getRunOwnedStartActiveEpoch() != null) { + throw new IllegalStateException( + "RUN_OWNED_INITIAL_LAUNCH_STATE_MISMATCH: starting owner row already has an active epoch"); + } + long preparingEpoch = requireRunOwnedPreparingEpoch(reserved); + activeEpoch = Math.addExact(preparingEpoch, 1L); + if (current.getLifecycleEpoch() != preparingEpoch) { + throw new IllegalStateException( + "WORLD_LIFECYCLE_EPOCH_MISMATCH: PREPARING epoch differs from the durable launch fence"); + } + if (STATUS_STARTING.equals(reserved.getStatus())) { + sessionStateService.saveState(withStatus(snapshot(reserved), STATUS_STARTING)); + } + activateAndReadBackRunOwnedWorld( + reserved, request, resolvedLaunchDescriptor, preparingEpoch, activeEpoch); + } else if (current.getStatus() + == WorldInstanceLifecycleStatus.WORLD_INSTANCE_LIFECYCLE_STATUS_ACTIVE) { + long preparingEpoch = requireRunOwnedPreparingEpoch(reserved); + activeEpoch = Math.addExact(preparingEpoch, 1L); + if (reserved.getRunOwnedStartActiveEpoch() != null + && reserved.getRunOwnedStartActiveEpoch() != activeEpoch) { + throw new IllegalStateException( + "WORLD_LIFECYCLE_EPOCH_MISMATCH: ACTIVE epoch differs from the durable activation result"); + } + requireRunOwnedActiveEpoch(current, activeEpoch); + } else { + throw runOwnedWorldStatusFailure(current.getStatus()); + } + + GameInstanceDto runningState = withStatus(snapshot(reserved), STATUS_RUNNING); + sessionStateService.saveState(runningState); + GameInstance completed = + inTransaction( + () -> + completeRunOwnedInitialLaunch( + request, requestDigest, resolvedLaunchDescriptor, gameInstanceId, activeEpoch), + "complete run-owned initial launch"); + return new RunOwnedInitialLaunchResult(snapshot(completed), activeEpoch); + } + @Override @Timed(value = "gamesession.stop") public GameInstanceDto stopSession(long sessionId) { @@ -589,6 +715,490 @@ private void restoreSessionSnapshot(GameInstance instance, GameInstanceDto snaps repository.save(instance); } + private void validateRunOwnedLaunchRequest(StartSessionRequest request) { + if (request == null) { + throw new IllegalArgumentException("run-owned initial launch request is required"); + } + RequestIdValidation.requirePositiveLong(request.tenantId(), "tenantId"); + RequestIdValidation.requirePositiveLong(request.gameTemplateId(), "gameTemplateId"); + RequestIdValidation.requirePositiveLong(request.ownerAccountId(), "ownerAccountId"); + if (request.controlPlaneRequestId() == null + || request.controlPlaneRequestId().isBlank() + || request.controlPlaneRequestId().length() > 128) { + throw new IllegalArgumentException( + "controlPlaneRequestId must contain 1 to 128 nonblank characters"); + } + } + + private static String runOwnedLaunchRequestDigest(StartSessionRequest request) { + StringBuilder preimage = new StringBuilder(); + appendDigestField(preimage, "schema", RUN_OWNED_LAUNCH_DIGEST_SCHEMA); + appendDigestField(preimage, "tenantId", Long.toString(request.tenantId())); + appendDigestField(preimage, "gameTemplateId", Long.toString(request.gameTemplateId())); + appendDigestField(preimage, "controlPlaneRequestId", request.controlPlaneRequestId()); + appendDigestField(preimage, "ownerAccountId", Long.toString(request.ownerAccountId())); + appendDigestField(preimage, "replaceExistingFirst", "false"); + try { + return HexFormat.of() + .formatHex( + MessageDigest.getInstance("SHA-256") + .digest(preimage.toString().getBytes(StandardCharsets.UTF_8))); + } catch (NoSuchAlgorithmException exception) { + throw new IllegalStateException("SHA-256 unavailable", exception); + } + } + + private static void appendDigestField(StringBuilder preimage, String name, String value) { + int nameByteLength = name.getBytes(StandardCharsets.UTF_8).length; + int valueByteLength = value.getBytes(StandardCharsets.UTF_8).length; + preimage + .append(nameByteLength) + .append(':') + .append(name) + .append(valueByteLength) + .append(':') + .append(value); + } + + private void requireDescriptorMatchesRequest( + StartSessionRequest request, ResolvedLaunchDescriptor descriptor) { + if (descriptor.tenantId() != request.tenantId() + || descriptor.gameTemplateId() != request.gameTemplateId() + || !request.controlPlaneRequestId().equals(descriptor.controlPlaneRequestId())) { + throw new IllegalArgumentException( + "LAUNCH_DESCRIPTOR_REQUEST_MISMATCH: resolved descriptor is not bound to this request"); + } + if (descriptor.launchDescriptorId() == null + || descriptor.launchDescriptorId().isBlank() + || descriptor.versionId() <= 0L + || descriptor.releaseBundleId() <= 0L + || descriptor.versionStateEpoch() <= 0L + || descriptor.generationConfigRevision() == null + || descriptor.generationConfigRevision().isBlank() + || descriptor.publishedReleaseBundleRef() == null + || descriptor.publishedReleaseBundleRef().isBlank() + || !releaseBundleRef( + request.tenantId(), descriptor.versionId(), descriptor.releaseBundleId()) + .equals(descriptor.publishedReleaseBundleRef())) { + throw new IllegalArgumentException( + "LAUNCH_DESCRIPTOR_INCOMPLETE: resolved descriptor is missing exact published inputs"); + } + } + + private GameInstance reserveRunOwnedInitialLaunch( + StartSessionRequest request, ResolvedLaunchDescriptor descriptor, String requestDigest) { + repository.lockRunOwnedStartIdentity(request.tenantId(), request.controlPlaneRequestId()); + Optional existing = + repository.findByTenantIdAndRunOwnedStartRequestIdForUpdate( + request.tenantId(), request.controlPlaneRequestId()); + if (existing.isPresent()) { + requireSameRunOwnedInitialLaunch(existing.get(), request, descriptor, requestDigest); + return existing.get(); + } + + GameInstance instance = new GameInstance(); + instance.setTenantId(request.tenantId()); + instance.setRuntimeVersion(Long.toString(descriptor.versionId())); + instance.setGameTemplateId(request.gameTemplateId()); + instance.setLaunchDescriptorId(descriptor.launchDescriptorId()); + instance.setVersionId(descriptor.versionId()); + instance.setReleaseBundleId(descriptor.releaseBundleId()); + instance.setVersionStateEpoch(descriptor.versionStateEpoch()); + instance.setGenerationConfigRevision(descriptor.generationConfigRevision()); + instance.setRemapSetId(descriptor.remapSetId()); + instance.setOwnerAccountId(request.ownerAccountId()); + instance.setStatus(STATUS_STARTING); + instance.setRunOwnedStartRequestId(request.controlPlaneRequestId()); + instance.setRunOwnedStartRequestDigest(requestDigest); + instance.setRunOwnedStartPublishedReleaseBundleRef(descriptor.publishedReleaseBundleRef()); + return repository.save(instance); + } + + private void requireSameRunOwnedInitialLaunch( + GameInstance instance, + StartSessionRequest request, + ResolvedLaunchDescriptor descriptor, + String requestDigest) { + if (!request.controlPlaneRequestId().equals(instance.getRunOwnedStartRequestId()) + || !requestDigest.equals(instance.getRunOwnedStartRequestDigest()) + || !Objects.equals(instance.getTenantId(), request.tenantId()) + || !Objects.equals(instance.getOwnerAccountId(), request.ownerAccountId()) + || !Objects.equals(instance.getGameTemplateId(), request.gameTemplateId()) + || !Objects.equals(instance.getRuntimeVersion(), Long.toString(descriptor.versionId())) + || !Objects.equals(instance.getLaunchDescriptorId(), descriptor.launchDescriptorId()) + || !Objects.equals(instance.getVersionId(), descriptor.versionId()) + || !Objects.equals(instance.getReleaseBundleId(), descriptor.releaseBundleId()) + || !Objects.equals(instance.getVersionStateEpoch(), descriptor.versionStateEpoch()) + || !Objects.equals( + instance.getGenerationConfigRevision(), descriptor.generationConfigRevision()) + || !Objects.equals(instance.getRemapSetId(), descriptor.remapSetId()) + || !Objects.equals( + instance.getRunOwnedStartPublishedReleaseBundleRef(), + descriptor.publishedReleaseBundleRef())) { + throw new IllegalStateException( + "RUN_OWNED_INITIAL_LAUNCH_IDENTITY_CONFLICT: request or resolved descriptor changed"); + } + } + + private void requireRunOwnedTargetCanResume(GameInstance instance) { + if (instance.getId() == null + || instance.getRunOwnedStartRequestId() == null + || instance.getRunOwnedStartRequestDigest() == null) { + throw new IllegalStateException( + "RUN_OWNED_INITIAL_LAUNCH_IDENTITY_UNAVAILABLE: durable request identity is incomplete"); + } + if (!STATUS_STARTING.equals(instance.getStatus()) + && !STATUS_RUNNING.equals(instance.getStatus())) { + throw new IllegalStateException( + "RUN_OWNED_INITIAL_LAUNCH_TARGET_NOT_RESUMABLE: existing instance is not starting or running"); + } + if (STATUS_RUNNING.equals(instance.getStatus())) { + requireRunOwnedRecordedActiveEpoch(instance); + } + } + + private long requireRunOwnedRecordedActiveEpoch(GameInstance instance) { + long preparingEpoch = requireRunOwnedPreparingEpoch(instance); + Long activeEpoch = instance.getRunOwnedStartActiveEpoch(); + if (activeEpoch == null || activeEpoch <= 0L) { + throw new IllegalStateException( + "RUN_OWNED_INITIAL_LAUNCH_EPOCH_UNAVAILABLE: running instance has no active epoch proof"); + } + if (activeEpoch != Math.addExact(preparingEpoch, 1L)) { + throw new IllegalStateException( + "WORLD_LIFECYCLE_EPOCH_MISMATCH: durable ACTIVE epoch differs from the prepare fence"); + } + return activeEpoch; + } + + private GameInstance recordRunOwnedPreparingEpoch( + StartSessionRequest request, + String requestDigest, + ResolvedLaunchDescriptor descriptor, + long gameInstanceId, + long preparingEpoch) { + if (preparingEpoch <= 0L) { + throw new IllegalStateException( + "WORLD_AUTHORITY_MALFORMED: lifecycle epoch must be positive"); + } + GameInstance instance = + repository + .findByTenantIdAndGameInstanceIdForUpdate(request.tenantId(), gameInstanceId) + .orElseThrow( + () -> + new IllegalStateException( + "RUN_OWNED_INITIAL_LAUNCH_IDENTITY_UNAVAILABLE: instance row is missing")); + requireSameRunOwnedInitialLaunch(instance, request, descriptor, requestDigest); + Long recordedEpoch = instance.getRunOwnedStartPreparingEpoch(); + if (recordedEpoch != null) { + if (recordedEpoch != preparingEpoch) { + throw new IllegalStateException( + "WORLD_LIFECYCLE_EPOCH_MISMATCH: PREPARING epoch changed across retries"); + } + return instance; + } + if (instance.getRunOwnedStartActiveEpoch() != null) { + throw new IllegalStateException( + "RUN_OWNED_INITIAL_LAUNCH_EPOCH_MISMATCH: active epoch exists without its prepare fence"); + } + instance.setRunOwnedStartPreparingEpoch(preparingEpoch); + return repository.save(instance); + } + + private GameInstance reloadRunOwnedInitialLaunch( + StartSessionRequest request, + String requestDigest, + ResolvedLaunchDescriptor descriptor, + long gameInstanceId) { + return inTransaction( + () -> { + GameInstance instance = + repository + .findByTenantIdAndGameInstanceIdForUpdate(request.tenantId(), gameInstanceId) + .orElseThrow( + () -> + new IllegalStateException( + "RUN_OWNED_INITIAL_LAUNCH_IDENTITY_UNAVAILABLE: instance row is missing")); + requireSameRunOwnedInitialLaunch(instance, request, descriptor, requestDigest); + return instance; + }, + "reload run-owned initial launch"); + } + + private GameInstance completeRunOwnedInitialLaunch( + StartSessionRequest request, + String requestDigest, + ResolvedLaunchDescriptor descriptor, + long gameInstanceId, + long activeEpoch) { + GameInstance instance = + repository + .findByTenantIdAndGameInstanceIdForUpdate(request.tenantId(), gameInstanceId) + .orElseThrow( + () -> + new IllegalStateException( + "RUN_OWNED_INITIAL_LAUNCH_IDENTITY_UNAVAILABLE: instance row is missing")); + requireSameRunOwnedInitialLaunch(instance, request, descriptor, requestDigest); + long expectedActiveEpoch = Math.addExact(requireRunOwnedPreparingEpoch(instance), 1L); + if (activeEpoch != expectedActiveEpoch) { + throw new IllegalStateException( + "WORLD_LIFECYCLE_EPOCH_MISMATCH: ACTIVE epoch differs from the durable activation fence"); + } + if (instance.getRunOwnedStartActiveEpoch() != null + && instance.getRunOwnedStartActiveEpoch() != activeEpoch) { + throw new IllegalStateException( + "WORLD_LIFECYCLE_EPOCH_MISMATCH: ACTIVE epoch changed across retries"); + } + if (!STATUS_STARTING.equals(instance.getStatus()) + && !STATUS_RUNNING.equals(instance.getStatus())) { + throw new IllegalStateException( + "RUN_OWNED_INITIAL_LAUNCH_TARGET_NOT_RESUMABLE: existing instance is not starting or running"); + } + instance.setRunOwnedStartActiveEpoch(activeEpoch); + instance.setStatus(STATUS_RUNNING); + return repository.save(instance); + } + + private long requireRunOwnedPreparingEpoch(GameInstance instance) { + Long epoch = instance.getRunOwnedStartPreparingEpoch(); + if (epoch == null || epoch <= 0L) { + throw new IllegalStateException( + "RUN_OWNED_INITIAL_LAUNCH_EPOCH_UNAVAILABLE: exact PREPARING epoch is not durable"); + } + return epoch; + } + + private WorldInstanceLifecycleSnapshot prepareRunOwnedWorldInstance( + GameInstance instance, ResolvedLaunchDescriptor descriptor, StartSessionRequest request) { + if (worldManagementClient == null) { + throw new IllegalStateException(WORLD_PREPARATION_AUTHORITY_UNAVAILABLE); + } + final PrepareWorldInstanceResponse response; + try { + response = + worldManagementClient.prepareWorldInstance( + request.tenantId(), + instance.getId(), + request.gameTemplateId(), + request.controlPlaneRequestId(), + descriptor.launchDescriptorId(), + descriptor.versionId(), + instance.getScriptPatchVersion(), + descriptor.runtimeFlagsJson(), + descriptor.generationConfigRevision(), + descriptor.releaseBundleId(), + descriptor.publishedReleaseBundleRef(), + descriptor.versionStateEpoch(), + descriptor.remapSetId()); + } catch (RuntimeException exception) { + throw new IllegalStateException(WORLD_PREPARATION_AUTHORITY_UNAVAILABLE, exception); + } + if (response == null) { + throw new IllegalStateException(WORLD_AUTHORITY_MALFORMED_RESPONSE_NULL); + } + if (response.hasError()) { + throw new IllegalStateException( + response.getError().getCode() + ": " + response.getError().getMessage()); + } + WorldInstanceLifecycleSnapshot snapshot = + requireWorldSnapshot( + response.hasWorldInstance(), + response.getWorldInstance(), + request.tenantId(), + instance.getId(), + null); + requireRunOwnedWorldDescriptor(snapshot, request, descriptor, instance.getId()); + requireKnownRunOwnedWorldStatus(snapshot.getStatus()); + return snapshot; + } + + private WorldInstanceLifecycleSnapshot readRunOwnedWorldLifecycle( + GameInstance instance, StartSessionRequest request, ResolvedLaunchDescriptor descriptor) { + if (worldManagementClient == null) { + throw new IllegalStateException(WORLD_LIFECYCLE_AUTHORITY_UNAVAILABLE); + } + final GetWorldInstanceLifecycleResponse response; + try { + response = + worldManagementClient.getWorldInstanceLifecycle(request.tenantId(), instance.getId()); + } catch (RuntimeException exception) { + throw new IllegalStateException(WORLD_LIFECYCLE_AUTHORITY_UNAVAILABLE, exception); + } + if (response == null) { + throw new IllegalStateException(WORLD_AUTHORITY_MALFORMED_RESPONSE_NULL); + } + if (response.hasError()) { + throw new IllegalStateException( + response.getError().getCode() + ": " + response.getError().getMessage()); + } + WorldInstanceLifecycleSnapshot snapshot = + requireWorldSnapshot( + response.hasWorldInstance(), + response.getWorldInstance(), + request.tenantId(), + instance.getId(), + null); + requireRunOwnedWorldDescriptor(snapshot, request, descriptor, instance.getId()); + requireKnownRunOwnedWorldStatus(snapshot.getStatus()); + return snapshot; + } + + private WorldInstanceLifecycleSnapshot activateAndReadBackRunOwnedWorld( + GameInstance instance, + StartSessionRequest request, + ResolvedLaunchDescriptor descriptor, + long preparingEpoch, + long activeEpoch) { + if (worldManagementClient == null) { + throw new IllegalStateException(WORLD_ACTIVATION_AUTHORITY_UNAVAILABLE); + } + final ActivatePreparedWorldInstanceResponse response; + try { + response = + worldManagementClient.activatePreparedWorldInstance( + request.tenantId(), instance.getId(), preparingEpoch); + } catch (RuntimeException activationFailure) { + return reconcileRunOwnedActivationFailure( + instance, request, descriptor, preparingEpoch, activeEpoch, activationFailure); + } + if (response == null) { + throw new IllegalStateException(WORLD_AUTHORITY_MALFORMED_RESPONSE_NULL); + } + if (response.hasError()) { + return reconcileRunOwnedActivationFailure( + instance, + request, + descriptor, + preparingEpoch, + activeEpoch, + new IllegalStateException( + response.getError().getCode() + ": " + response.getError().getMessage())); + } + WorldInstanceLifecycleSnapshot activated = + requireWorldSnapshot( + response.hasWorldInstance(), + response.getWorldInstance(), + request.tenantId(), + instance.getId(), + WorldInstanceLifecycleStatus.WORLD_INSTANCE_LIFECYCLE_STATUS_ACTIVE); + requireRunOwnedWorldDescriptor(activated, request, descriptor, instance.getId()); + requireRunOwnedActiveEpoch(activated, activeEpoch); + + WorldInstanceLifecycleSnapshot readback = + readRunOwnedWorldLifecycle(instance, request, descriptor); + if (readback.getStatus() + != WorldInstanceLifecycleStatus.WORLD_INSTANCE_LIFECYCLE_STATUS_ACTIVE) { + throw runOwnedWorldStatusFailure(readback.getStatus()); + } + requireRunOwnedActiveEpoch(readback, activeEpoch); + return readback; + } + + private WorldInstanceLifecycleSnapshot reconcileRunOwnedActivationFailure( + GameInstance instance, + StartSessionRequest request, + ResolvedLaunchDescriptor descriptor, + long preparingEpoch, + long activeEpoch, + RuntimeException activationFailure) { + WorldInstanceLifecycleSnapshot current = + readRunOwnedWorldLifecycle(instance, request, descriptor); + if (current.getStatus() + == WorldInstanceLifecycleStatus.WORLD_INSTANCE_LIFECYCLE_STATUS_ACTIVE) { + requireRunOwnedActiveEpoch(current, activeEpoch); + return current; + } + if (current.getStatus() + == WorldInstanceLifecycleStatus.WORLD_INSTANCE_LIFECYCLE_STATUS_PREPARING) { + if (current.getLifecycleEpoch() != preparingEpoch) { + throw new IllegalStateException( + "WORLD_LIFECYCLE_EPOCH_MISMATCH: PREPARING epoch differs from the durable launch fence", + activationFailure); + } + throw new IllegalStateException(WORLD_ACTIVATION_AUTHORITY_UNAVAILABLE, activationFailure); + } + throw runOwnedWorldStatusFailure(current.getStatus()); + } + + private void requireRunOwnedWorldDescriptor( + WorldInstanceLifecycleSnapshot snapshot, + StartSessionRequest request, + ResolvedLaunchDescriptor descriptor, + long gameInstanceId) { + final long tenantId; + final long instanceId; + final long templateId; + final long versionId; + final long releaseBundleId; + try { + tenantId = RequestIdValidation.requirePositiveLong(snapshot.getTenantId(), "tenantId"); + instanceId = + RequestIdValidation.requirePositiveLong(snapshot.getGameInstanceId(), "gameInstanceId"); + templateId = + RequestIdValidation.requirePositiveLong(snapshot.getGameTemplateId(), "gameTemplateId"); + versionId = RequestIdValidation.requirePositiveLong(snapshot.getVersionId(), "versionId"); + releaseBundleId = + RequestIdValidation.requirePositiveLong(snapshot.getReleaseBundleId(), "releaseBundleId"); + } catch (IllegalArgumentException exception) { + throw new IllegalStateException( + "WORLD_AUTHORITY_MALFORMED: " + exception.getMessage(), exception); + } + if (tenantId != request.tenantId() + || instanceId != gameInstanceId + || templateId != request.gameTemplateId() + || !request.controlPlaneRequestId().equals(snapshot.getControlPlaneRequestId()) + || !descriptor.launchDescriptorId().equals(snapshot.getLaunchDescriptorId()) + || versionId != descriptor.versionId() + || releaseBundleId != descriptor.releaseBundleId() + || !descriptor.generationConfigRevision().equals(snapshot.getGenerationConfigRevision()) + || !descriptor.publishedReleaseBundleRef().equals(snapshot.getPublishedReleaseBundleRef()) + || snapshot.getVersionStateEpoch() != descriptor.versionStateEpoch() + || !Objects.equals( + normalizeBlank(descriptor.remapSetId()), normalizeBlank(snapshot.getRemapSetId()))) { + throw new IllegalStateException( + "WORLD_AUTHORITY_DESCRIPTOR_MISMATCH: lifecycle readback differs from the resolved launch descriptor"); + } + } + + private void requireKnownRunOwnedWorldStatus(WorldInstanceLifecycleStatus status) { + if (status == null + || status == WorldInstanceLifecycleStatus.WORLD_INSTANCE_LIFECYCLE_STATUS_UNSPECIFIED + || status == WorldInstanceLifecycleStatus.UNRECOGNIZED) { + throw new IllegalStateException("WORLD_AUTHORITY_MALFORMED: lifecycle status is unavailable"); + } + } + + private void requireRunOwnedActiveEpoch( + WorldInstanceLifecycleSnapshot snapshot, long expectedActiveEpoch) { + if (snapshot.getLifecycleEpoch() != expectedActiveEpoch) { + throw new IllegalStateException( + "WORLD_LIFECYCLE_EPOCH_MISMATCH: ACTIVE epoch differs from the durable activation result"); + } + } + + private RuntimeException runOwnedWorldStatusFailure(WorldInstanceLifecycleStatus status) { + if (status + == WorldInstanceLifecycleStatus.WORLD_INSTANCE_LIFECYCLE_STATUS_FAILED_PRE_ACTIVATION) { + return new LifecycleOutcomeException( + "WORLD_INSTANCE_LIFECYCLE_FAILED_PRE_ACTIVATION", + "run-owned instance failed before activation and remains terminal for this request"); + } + if (status == WorldInstanceLifecycleStatus.WORLD_INSTANCE_LIFECYCLE_STATUS_TERMINATING) { + return new LifecycleOutcomeException( + "WORLD_TERMINATION_IN_PROGRESS", "run-owned instance termination is in progress"); + } + if (status == WorldInstanceLifecycleStatus.WORLD_INSTANCE_LIFECYCLE_STATUS_TERMINATED) { + return new LifecycleOutcomeException( + "WORLD_INSTANCE_TERMINATED", "run-owned instance is already terminated"); + } + return new IllegalStateException( + "WORLD_AUTHORITY_MALFORMED: lifecycle status cannot resume initial launch"); + } + + private String normalizeBlank(String value) { + return value == null || value.isBlank() ? null : value; + } + private GameInstanceDto withStatus(GameInstanceDto snapshot, String status) { return new GameInstanceDto( snapshot.id(), diff --git a/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/service/impl/GameSessionControlPlaneGrpcService.java b/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/service/impl/GameSessionControlPlaneGrpcService.java index a355e5def8..277694ac44 100644 --- a/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/service/impl/GameSessionControlPlaneGrpcService.java +++ b/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/service/impl/GameSessionControlPlaneGrpcService.java @@ -4,11 +4,17 @@ import io.grpc.stub.StreamObserver; import io.micrometer.core.annotation.Timed; import io.micrometer.core.instrument.MeterRegistry; +import java.util.Objects; +import java.util.UUID; +import java.util.regex.Pattern; import net.firedevops.firemud.common.grpc.GrpcAppErrors; import net.firedevops.firemud.common.security.AdminAuthorizationException; import net.firedevops.firemud.common.security.AdminRoleGuard; import net.firedevops.firemud.common.security.SessionContext; import net.firedevops.firemud.gamesession.service.AdmissionPointerVersionMismatchException; +import net.firedevops.firemud.gamesession.service.InitialAdmissionBindHoldBinding; +import net.firedevops.firemud.gamesession.service.InitialAdmissionBindOwnerProof; +import net.firedevops.firemud.gamesession.service.InitialAdmissionBindOwnerProofReader; import net.firedevops.firemud.gamesession.service.impl.GameSessionAdmissionPointerControlPlaneService.AdmissionPointerMutationPreconditionException; import net.firedevops.firemud.gamesession.v1.EnqueueAutomationCommandIfAbsentRequest; import net.firedevops.firemud.gamesession.v1.EnqueueAutomationCommandIfAbsentResponse; @@ -21,6 +27,8 @@ import net.firedevops.firemud.gamesession.v1.GetGameSessionPinConvergenceResponse; import net.firedevops.firemud.gamesession.v1.GetGameplayCommandStatusRequest; import net.firedevops.firemud.gamesession.v1.GetGameplayCommandStatusResponse; +import net.firedevops.firemud.gamesession.v1.GetInitialAdmissionBindProofRequest; +import net.firedevops.firemud.gamesession.v1.GetInitialAdmissionBindProofResponse; import net.firedevops.firemud.gamesession.v1.GetPinnedScriptPatchVersionRequest; import net.firedevops.firemud.gamesession.v1.GetPinnedScriptPatchVersionResponse; import net.firedevops.firemud.gamesession.v1.GetPreparedVersionUpgradeRequest; @@ -33,6 +41,7 @@ import net.firedevops.firemud.gamesession.v1.GetRemoteFollowupResultResponse; import net.firedevops.firemud.gamesession.v1.GetRuntimeOwnershipStatusRequest; import net.firedevops.firemud.gamesession.v1.GetRuntimeOwnershipStatusResponse; +import net.firedevops.firemud.gamesession.v1.InitialAdmissionBindOwnerProofOutcome; import net.firedevops.firemud.gamesession.v1.ListAdmissionPointerAuditRequest; import net.firedevops.firemud.gamesession.v1.ListAdmissionPointerAuditResponse; import net.firedevops.firemud.gamesession.v1.ListAdmissionPointersRequest; @@ -92,6 +101,10 @@ public final class GameSessionControlPlaneGrpcService private final GameSessionOperatorControlPlaneService operatorControlPlaneService; private final GameSessionVersionUpgradeControlPlaneService versionUpgradeControlPlaneService; private final MeterRegistry meterRegistry; + private InitialAdmissionBindOwnerProofReader initialAdmissionBindOwnerProofReader; + private InitialAdmissionBindOwnerReadWorkloadGuard initialAdmissionBindOwnerReadWorkloadGuard; + + private static final Pattern SHA_256 = Pattern.compile("[0-9a-f]{64}"); @Value("${game.tick-duration-ms:1000}") private long tickDurationMs = 1000L; @@ -114,6 +127,15 @@ public GameSessionControlPlaneGrpcService( this.meterRegistry = meterRegistry; } + @Autowired + public void configureInitialAdmissionBindOwnerReadBoundary( + InitialAdmissionBindOwnerProofReader proofReader, + @Value("${firemud.grpc.workload-namespace:}") String workloadNamespace) { + this.initialAdmissionBindOwnerProofReader = proofReader; + this.initialAdmissionBindOwnerReadWorkloadGuard = + new InitialAdmissionBindOwnerReadWorkloadGuard(workloadNamespace); + } + private long parseTenantId(String tenantId) { return ControlPlaneRequestParser.parsePositiveLong(tenantId, "tenant_id"); } @@ -157,6 +179,169 @@ private ErrorDetail automationAdmissionReceiverFenceUnavailable(String operation AUTOMATION_ADMISSION_RECEIVER_FENCE_UNAVAILABLE); } + @Override + @Timed(value = "gamesessionGrpc.controlPlane.getInitialAdmissionBindProof") + public void getInitialAdmissionBindProof( + GetInitialAdmissionBindProofRequest request, + StreamObserver responseObserver) { + GetInitialAdmissionBindProofResponse.Builder response = + request == null + ? GetInitialAdmissionBindProofResponse.newBuilder() + : echoInitialAdmissionBindTuple(request); + try { + if (request == null) { + throw new IllegalArgumentException("request is required"); + } + if (initialAdmissionBindOwnerProofReader == null + || initialAdmissionBindOwnerReadWorkloadGuard == null) { + throw new AdminAuthorizationException( + "Initial admission owner proof boundary is not configured"); + } + initialAdmissionBindOwnerReadWorkloadGuard.requireWorldManagementOwnerReadCaller(); + InitialAdmissionBindHoldBinding binding = parseInitialAdmissionBindTuple(request); + InitialAdmissionBindOwnerProof proof = initialAdmissionBindOwnerProofReader.read(binding); + if (proof == null) { + throw new IllegalStateException("Initial admission owner proof read returned no result"); + } + if (!matchesExactInitialAdmissionBindTuple(binding, proof)) { + throw new IllegalStateException( + "Initial admission owner proof did not match the requested hold tuple"); + } + response + .setOutcome(toWireOutcome(proof.outcome())) + .setOwnerProofId(nullToEmpty(proof.ownerProofId())) + .setPointerAuditId(nullToEmpty(proof.pointerAuditId())) + .setPointerVersion(proof.pointerVersion()) + .setPointerAuditRequestDigest(nullToEmpty(proof.pointerAuditRequestDigest())) + .setFutureCommitPrevented(proof.futureCommitPrevented()); + } catch (AdminAuthorizationException exception) { + response.setError(authorizationError("GetInitialAdmissionBindProof", exception)); + } catch (IllegalArgumentException exception) { + response.setError(invalidArgumentError("GetInitialAdmissionBindProof", exception)); + } catch (Exception exception) { + logger.error("GetInitialAdmissionBindProof failed", exception); + response.setError(GrpcAppErrors.error(meterRegistry, "INTERNAL", "Internal error")); + } + responseObserver.onNext(response.build()); + responseObserver.onCompleted(); + } + + private GetInitialAdmissionBindProofResponse.Builder echoInitialAdmissionBindTuple( + GetInitialAdmissionBindProofRequest request) { + return GetInitialAdmissionBindProofResponse.newBuilder() + .setHoldId(request.getHoldId()) + .setHoldFence(request.getHoldFence()) + .setTenantId(request.getTenantId()) + .setRealmUuid(request.getRealmUuid()) + .setPlayableStateNamespaceUuid(request.getPlayableStateNamespaceUuid()) + .setPlayableStateScopeValue(request.getPlayableStateScopeValue()) + .setGameInstanceId(request.getGameInstanceId()) + .setVersionId(request.getVersionId()) + .setActiveLifecycleEpoch(request.getActiveLifecycleEpoch()) + .setInitialAdmissionRequestId(request.getInitialAdmissionRequestId()) + .setRequestDigest(request.getRequestDigest()) + .setExpectedNoPriorPointer(request.getExpectedNoPriorPointer()) + .setExpectedCatalogRevision(request.getExpectedCatalogRevision()); + } + + private InitialAdmissionBindHoldBinding parseInitialAdmissionBindTuple( + GetInitialAdmissionBindProofRequest request) { + if (request == null) { + throw new IllegalArgumentException("request is required"); + } + String scope = + switch (request.getPlayableStateScope()) { + case PLAYABLE_STATE_SCOPE_SHARED -> "SHARED"; + case PLAYABLE_STATE_SCOPE_ISOLATED -> "ISOLATED"; + case PLAYABLE_STATE_SCOPE_UNSPECIFIED, UNRECOGNIZED -> + throw new IllegalArgumentException("playable_state_scope is unsupported"); + }; + if (request.getInitialAdmissionRequestId().isBlank() + || request.getInitialAdmissionRequestId().length() > 128) { + throw new IllegalArgumentException("initial_admission_request_id is invalid"); + } + if (!SHA_256.matcher(request.getRequestDigest()).matches()) { + throw new IllegalArgumentException("request_digest must be lowercase SHA-256 hex"); + } + if (!request.getExpectedNoPriorPointer()) { + throw new IllegalArgumentException("expected_no_prior_pointer must be true"); + } + return new InitialAdmissionBindHoldBinding( + requireCanonicalUuid(request.getHoldId(), "hold_id"), + requireCanonicalUuid(request.getHoldFence(), "hold_fence"), + ControlPlaneRequestParser.parsePositiveLong(request.getTenantId(), "tenant_id"), + requireCanonicalUuid(request.getRealmUuid(), "realm_uuid"), + requireCanonicalUuid( + request.getPlayableStateNamespaceUuid(), "playable_state_namespace_uuid"), + scope, + ControlPlaneRequestParser.parsePositiveLong( + request.getGameInstanceId(), "game_instance_id"), + ControlPlaneRequestParser.parsePositiveLong(request.getVersionId(), "version_id"), + ControlPlaneRequestParser.requirePositive( + request.getActiveLifecycleEpoch(), "active_lifecycle_epoch"), + request.getInitialAdmissionRequestId(), + request.getRequestDigest(), + true, + ControlPlaneRequestParser.requirePositive( + request.getExpectedCatalogRevision(), "expected_catalog_revision")); + } + + private boolean matchesExactInitialAdmissionBindTuple( + InitialAdmissionBindHoldBinding binding, InitialAdmissionBindOwnerProof proof) { + return Objects.equals(binding.holdId(), proof.holdId()) + && Objects.equals(binding.holdFence(), proof.holdFence()) + && binding.tenantId() == proof.tenantId() + && Objects.equals(binding.realmUuid(), proof.realmUuid()) + && Objects.equals(binding.playableStateNamespaceUuid(), proof.playableStateNamespaceUuid()) + && Objects.equals(binding.playableStateScope(), proof.playableStateScope()) + && binding.gameInstanceId() == proof.gameInstanceId() + && binding.versionId() == proof.versionId() + && binding.activeLifecycleEpoch() == proof.activeLifecycleEpoch() + && Objects.equals(binding.initialAdmissionRequestId(), proof.initialAdmissionRequestId()) + && Objects.equals(binding.requestDigest(), proof.requestDigest()) + && binding.expectedNoPriorPointer() == proof.expectedNoPriorPointer() + && binding.expectedCatalogRevision() == proof.expectedCatalogRevision(); + } + + private String requireCanonicalUuid(String value, String fieldName) { + try { + if (value == null || !UUID.fromString(value).toString().equals(value)) { + throw new IllegalArgumentException(fieldName + " must be a canonical UUID"); + } + return value; + } catch (IllegalArgumentException exception) { + throw new IllegalArgumentException(fieldName + " must be a canonical UUID", exception); + } + } + + private InitialAdmissionBindOwnerProofOutcome toWireOutcome( + InitialAdmissionBindOwnerProof.Outcome outcome) { + if (outcome == null) { + return InitialAdmissionBindOwnerProofOutcome.INITIAL_ADMISSION_BIND_OWNER_PROOF_OUTCOME_ERROR; + } + return switch (outcome) { + case COMMITTED -> + InitialAdmissionBindOwnerProofOutcome + .INITIAL_ADMISSION_BIND_OWNER_PROOF_OUTCOME_COMMITTED; + case ABORTED -> + InitialAdmissionBindOwnerProofOutcome.INITIAL_ADMISSION_BIND_OWNER_PROOF_OUTCOME_ABORTED; + case NOT_FOUND -> + InitialAdmissionBindOwnerProofOutcome + .INITIAL_ADMISSION_BIND_OWNER_PROOF_OUTCOME_NOT_FOUND; + case PENDING -> + InitialAdmissionBindOwnerProofOutcome.INITIAL_ADMISSION_BIND_OWNER_PROOF_OUTCOME_PENDING; + case UNAVAILABLE -> + InitialAdmissionBindOwnerProofOutcome + .INITIAL_ADMISSION_BIND_OWNER_PROOF_OUTCOME_UNAVAILABLE; + case ERROR -> + InitialAdmissionBindOwnerProofOutcome.INITIAL_ADMISSION_BIND_OWNER_PROOF_OUTCOME_ERROR; + }; + } + + private String nullToEmpty(String value) { + return value == null ? "" : value; + } + @Override @Timed(value = "gamesessionGrpc.controlPlane.listAdmissionPointers") public void listAdmissionPointers( diff --git a/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/service/impl/InitialAdmissionBindOwnerReadWorkloadGuard.java b/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/service/impl/InitialAdmissionBindOwnerReadWorkloadGuard.java new file mode 100644 index 0000000000..c75d67af71 --- /dev/null +++ b/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/service/impl/InitialAdmissionBindOwnerReadWorkloadGuard.java @@ -0,0 +1,37 @@ +package net.firedevops.firemud.gamesession.service.impl; + +import net.firedevops.firemud.common.grpc.GrpcPeerIdentity; +import net.firedevops.firemud.common.security.AdminAuthorizationException; +import net.firedevops.firemud.common.security.SessionContext; +import net.firedevops.firemud.gamesession.v1.GameSessionControlPlaneServiceGrpc; + +/** Exact method-local World Management workload authorization for owner-proof readback. */ +public final class InitialAdmissionBindOwnerReadWorkloadGuard { + private static final String METHOD_NAME = + "game_session.v1.GameSessionControlPlaneService/GetInitialAdmissionBindProof"; + private static final String WORLD_MANAGEMENT_SERVICE = "world-management-service"; + + private final String trustedNamespace; + + public InitialAdmissionBindOwnerReadWorkloadGuard(String trustedNamespace) { + this.trustedNamespace = trustedNamespace; + } + + public void requireWorldManagementOwnerReadCaller() { + GrpcPeerIdentity peerIdentity = GrpcPeerIdentity.current(); + if (!METHOD_NAME.equals( + GameSessionControlPlaneServiceGrpc.getGetInitialAdmissionBindProofMethod() + .getFullMethodName()) + || trustedNamespace == null + || !GrpcPeerIdentity.isValidNamespace(trustedNamespace) + || peerIdentity == null + || !WORLD_MANAGEMENT_SERVICE.equals(peerIdentity.service()) + || !trustedNamespace.equals(peerIdentity.namespace()) + || !("spiffe://firemud/ns/" + trustedNamespace + "/sa/" + WORLD_MANAGEMENT_SERVICE) + .equals(peerIdentity.uri()) + || SessionContext.hasAuthenticatedCallerContext()) { + throw new AdminAuthorizationException( + "Initial admission owner proof requires the authenticated World Management workload peer identity"); + } + } +} diff --git a/services/game-session-service/src/main/resources/application.yml b/services/game-session-service/src/main/resources/application.yml index 3591f95ac9..085467d1a1 100644 --- a/services/game-session-service/src/main/resources/application.yml +++ b/services/game-session-service/src/main/resources/application.yml @@ -133,6 +133,7 @@ firemud: 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} + workload-namespace: ${FIREMUD_GRPC_WORKLOAD_NAMESPACE:} server: compression: diff --git a/services/game-session-service/src/main/resources/db/migration/V9__run_owned_initial_launch_identity.sql b/services/game-session-service/src/main/resources/db/migration/V9__run_owned_initial_launch_identity.sql new file mode 100644 index 0000000000..e4a45fdc02 --- /dev/null +++ b/services/game-session-service/src/main/resources/db/migration/V9__run_owned_initial_launch_identity.sql @@ -0,0 +1,34 @@ +ALTER TABLE game_instances + ADD COLUMN run_owned_start_request_id character varying(128), + ADD COLUMN run_owned_start_request_digest character varying(64), + ADD COLUMN run_owned_start_published_release_bundle_ref character varying(256), + ADD COLUMN run_owned_start_preparing_epoch bigint, + ADD COLUMN run_owned_start_active_epoch bigint; + +ALTER TABLE game_instances + ADD CONSTRAINT game_instances_run_owned_start_identity_pair + CHECK ((run_owned_start_request_id IS NULL) = (run_owned_start_request_digest IS NULL)), + ADD CONSTRAINT game_instances_run_owned_start_digest_sha256 + CHECK (run_owned_start_request_digest IS NULL + OR run_owned_start_request_digest ~ '^[0-9a-f]{64}$'), + ADD CONSTRAINT game_instances_run_owned_start_descriptor_binding + CHECK ((run_owned_start_request_id IS NULL + AND run_owned_start_published_release_bundle_ref IS NULL) + OR (run_owned_start_request_id IS NOT NULL + AND run_owned_start_published_release_bundle_ref IS NOT NULL + AND game_template_id IS NOT NULL + AND launch_descriptor_id IS NOT NULL + AND version_id IS NOT NULL + AND release_bundle_id IS NOT NULL + AND version_state_epoch IS NOT NULL + AND generation_config_revision IS NOT NULL)), + ADD CONSTRAINT game_instances_run_owned_start_preparing_epoch_positive + CHECK (run_owned_start_preparing_epoch IS NULL OR run_owned_start_preparing_epoch > 0), + ADD CONSTRAINT game_instances_run_owned_start_active_epoch_exact + CHECK (run_owned_start_active_epoch IS NULL + OR (run_owned_start_preparing_epoch IS NOT NULL + AND run_owned_start_active_epoch = run_owned_start_preparing_epoch + 1)); + +ALTER TABLE game_instances + ADD CONSTRAINT game_instances_run_owned_start_request_unique + UNIQUE (tenant_id, run_owned_start_request_id); diff --git a/services/game-session-service/src/test/java/integration/net/firedevops/firemud/gamesession/service/RunOwnedInitialLaunchPostgresIntegrationTest.java b/services/game-session-service/src/test/java/integration/net/firedevops/firemud/gamesession/service/RunOwnedInitialLaunchPostgresIntegrationTest.java new file mode 100644 index 0000000000..cbb92efe3b --- /dev/null +++ b/services/game-session-service/src/test/java/integration/net/firedevops/firemud/gamesession/service/RunOwnedInitialLaunchPostgresIntegrationTest.java @@ -0,0 +1,177 @@ +package net.firedevops.firemud.gamesession.service; + +import static org.assertj.core.api.Assertions.assertThat; +import static org.assertj.core.api.Assertions.assertThatThrownBy; + +import java.nio.file.Path; +import java.util.concurrent.CountDownLatch; +import java.util.concurrent.Executors; +import java.util.concurrent.TimeUnit; +import net.firedevops.firemud.gamesession.entity.GameInstance; +import net.firedevops.firemud.gamesession.repository.GameInstanceRepository; +import org.flywaydb.core.Flyway; +import org.jooq.DSLContext; +import org.jooq.SQLDialect; +import org.jooq.exception.DataAccessException; +import org.jooq.impl.DSL; +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.support.TransactionTemplate; +import org.testcontainers.containers.PostgreSQLContainer; +import org.testcontainers.junit.jupiter.Container; +import org.testcontainers.junit.jupiter.Testcontainers; + +@Testcontainers(disabledWithoutDocker = true) +@SuppressWarnings("resource") +class RunOwnedInitialLaunchPostgresIntegrationTest { + private static final String MIGRATION_LOCATION = + "filesystem:" + Path.of("src/main/resources/db/migration").toAbsolutePath().normalize(); + private static final long TENANT_ID = 41L; + private static final String REQUEST_ID = "run-owned-pg-race"; + private static final String REQUEST_DIGEST = "c".repeat(64); + + @Container + static PostgreSQLContainer postgres = new PostgreSQLContainer<>("postgres:16-alpine"); + + @Test + void concurrentExactIdentityAllocationConvergesAndOrdinaryRowsRemainNullable() throws Exception { + DriverManagerDataSource dataSource = dataSource(); + Flyway.configure().dataSource(dataSource).locations(MIGRATION_LOCATION).load().migrate(); + DSLContext dsl = + DSL.using(new TransactionAwareDataSourceProxy(dataSource), SQLDialect.POSTGRES); + TransactionTemplate transactions = + new TransactionTemplate(new DataSourceTransactionManager(dataSource)); + GameInstanceRepository repository = new GameInstanceRepository(dsl); + CountDownLatch ready = new CountDownLatch(2); + CountDownLatch start = new CountDownLatch(1); + + try (var executor = Executors.newFixedThreadPool(2)) { + var first = + executor.submit( + () -> allocateOrReadSameRunOwnedInstance(repository, transactions, ready, start)); + var second = + executor.submit( + () -> allocateOrReadSameRunOwnedInstance(repository, transactions, ready, start)); + assertThat(ready.await(10, TimeUnit.SECONDS)).isTrue(); + start.countDown(); + + long firstId = first.get(15, TimeUnit.SECONDS); + long secondId = second.get(15, TimeUnit.SECONDS); + assertThat(firstId).isEqualTo(secondId); + assertThat( + dsl.fetchValue( + "SELECT count(*) FROM game_instances WHERE tenant_id = ? " + + "AND run_owned_start_request_id = ?", + Integer.class, + TENANT_ID, + REQUEST_ID)) + .isEqualTo(1); + assertThat( + dsl.fetchValue( + "SELECT run_owned_start_request_digest FROM game_instances WHERE id = ?", + String.class, + firstId)) + .isEqualTo(REQUEST_DIGEST); + + assertThatThrownBy(() -> insertDuplicateIdentity(dsl, firstId + 1L)) + .isInstanceOf(DataAccessException.class); + + GameInstance ordinaryOne = ordinaryInstance(1001L); + GameInstance ordinaryTwo = ordinaryInstance(1002L); + repository.save(ordinaryOne); + repository.save(ordinaryTwo); + assertThat(ordinaryOne.getRunOwnedStartRequestId()).isNull(); + assertThat(ordinaryTwo.getRunOwnedStartRequestId()).isNull(); + assertThat( + dsl.fetchValue( + "SELECT count(*) FROM game_instances WHERE tenant_id = ? " + + "AND run_owned_start_request_id IS NULL", + Integer.class, + TENANT_ID)) + .isEqualTo(2); + } + } + + private static long allocateOrReadSameRunOwnedInstance( + GameInstanceRepository repository, + TransactionTemplate transactions, + CountDownLatch ready, + CountDownLatch start) + throws InterruptedException { + ready.countDown(); + if (!start.await(10, TimeUnit.SECONDS)) { + throw new IllegalStateException("concurrent allocation start gate timed out"); + } + Long id = + transactions.execute( + status -> { + repository.lockRunOwnedStartIdentity(TENANT_ID, REQUEST_ID); + var existing = + repository.findByTenantIdAndRunOwnedStartRequestIdForUpdate( + TENANT_ID, REQUEST_ID); + if (existing.isPresent()) { + assertThat(existing.get().getRunOwnedStartRequestDigest()) + .isEqualTo(REQUEST_DIGEST); + return existing.get().getId(); + } + GameInstance instance = runOwnedInstance(); + return repository.save(instance).getId(); + }); + if (id == null) { + throw new IllegalStateException("run-owned instance allocation returned no id"); + } + return id; + } + + private static void insertDuplicateIdentity(DSLContext dsl, long id) { + dsl.execute( + "INSERT INTO game_instances (id, tenant_id, runtime_version, game_template_id, " + + "launch_descriptor_id, version_id, release_bundle_id, version_state_epoch, " + + "generation_config_revision, owner_account_id, status, run_owned_start_request_id, " + + "run_owned_start_request_digest, run_owned_start_published_release_bundle_ref) " + + "VALUES (?, ?, '902', 810, 'ld-run-owned-pg', 902, 20, 13, 'genrev-1', " + + "1001, 'STARTING', ?, ?, 'prb:41:902:20')", + id, + TENANT_ID, + REQUEST_ID, + REQUEST_DIGEST); + } + + private static DriverManagerDataSource dataSource() { + DriverManagerDataSource dataSource = new DriverManagerDataSource(); + dataSource.setDriverClassName("org.postgresql.Driver"); + dataSource.setUrl(postgres.getJdbcUrl()); + dataSource.setUsername(postgres.getUsername()); + dataSource.setPassword(postgres.getPassword()); + return dataSource; + } + + private static GameInstance runOwnedInstance() { + GameInstance instance = new GameInstance(); + instance.setTenantId(TENANT_ID); + instance.setRuntimeVersion("902"); + instance.setGameTemplateId(810L); + instance.setLaunchDescriptorId("ld-run-owned-pg"); + instance.setVersionId(902L); + instance.setReleaseBundleId(20L); + instance.setVersionStateEpoch(13L); + instance.setGenerationConfigRevision("genrev-1"); + instance.setOwnerAccountId(1001L); + instance.setStatus("STARTING"); + instance.setRunOwnedStartRequestId(REQUEST_ID); + instance.setRunOwnedStartRequestDigest(REQUEST_DIGEST); + instance.setRunOwnedStartPublishedReleaseBundleRef("prb:41:902:20"); + return instance; + } + + private static GameInstance ordinaryInstance(long ownerAccountId) { + GameInstance instance = new GameInstance(); + instance.setTenantId(TENANT_ID); + instance.setRuntimeVersion("ordinary-runtime"); + instance.setOwnerAccountId(ownerAccountId); + instance.setStatus("STARTING"); + return instance; + } +} diff --git a/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/client/WorldManagementClientTest.java b/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/client/WorldManagementClientTest.java index a98b979202..36d16b3615 100644 --- a/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/client/WorldManagementClientTest.java +++ b/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/client/WorldManagementClientTest.java @@ -1,15 +1,19 @@ package net.firedevops.firemud.gamesession.client; import static org.assertj.core.api.Assertions.assertThat; +import static org.assertj.core.api.Assertions.assertThatThrownBy; import static org.mockito.Mockito.mock; import io.grpc.ManagedChannel; import java.lang.reflect.Method; +import java.util.UUID; import java.util.concurrent.atomic.AtomicInteger; import net.firedevops.firemud.common.config.ServiceEndpointsProperties; 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.entitymanagement.v1.PlayableStateScope; +import net.firedevops.firemud.worldmanagement.v1.AcquireInitialAdmissionBindHoldRequest; import org.junit.jupiter.api.Test; class WorldManagementClientTest { @@ -36,6 +40,70 @@ public > T customize(T candidate) { assertThat(customizeCalls.get()).isEqualTo(1); } + @Test + void initialAdmissionHoldRequestCarriesExactTypedNoPriorPointerTuple() { + UUID realmId = UUID.fromString("23d39978-9d44-4e1a-8659-998ff9239b01"); + UUID namespaceId = UUID.fromString("ed1b4d88-81f8-4404-af7c-9a5dc91d3043"); + AcquireInitialAdmissionBindHoldRequest request = + WorldManagementClient.buildAcquireInitialAdmissionBindHoldRequest( + 7L, + 42L, + 11L, + 4L, + "d2db8478-9c56-42ab-99c2-9fbead6841ba", + "a".repeat(64), + realmId, + namespaceId, + PlayableStateScope.PLAYABLE_STATE_SCOPE_SHARED, + 3L); + + assertThat(request.getTenantId()).isEqualTo("7"); + assertThat(request.getGameInstanceId()).isEqualTo("42"); + assertThat(request.getVersionId()).isEqualTo("11"); + assertThat(request.getExpectedActiveLifecycleEpoch()).isEqualTo(4L); + assertThat(request.getInitialAdmissionRequestId()) + .isEqualTo("d2db8478-9c56-42ab-99c2-9fbead6841ba"); + assertThat(request.getRequestDigest()).isEqualTo("a".repeat(64)); + assertThat(request.getRealmUuid()).isEqualTo(realmId.toString()); + assertThat(request.getPlayableStateNamespaceUuid()).isEqualTo(namespaceId.toString()); + assertThat(request.getPlayableStateScope()) + .isEqualTo(PlayableStateScope.PLAYABLE_STATE_SCOPE_SHARED); + assertThat(request.getExpectedNoPriorPointer()).isTrue(); + assertThat(request.getExpectedCatalogRevision()).isEqualTo(3L); + } + + @Test + void initialAdmissionHoldRequestRejectsUnspecifiedScopeAndIncompleteTuple() { + assertThatThrownBy( + () -> + WorldManagementClient.buildAcquireInitialAdmissionBindHoldRequest( + 7L, + 42L, + 11L, + 4L, + "request-id", + "a".repeat(64), + UUID.randomUUID(), + UUID.randomUUID(), + PlayableStateScope.PLAYABLE_STATE_SCOPE_UNSPECIFIED, + 3L)) + .isInstanceOf(IllegalArgumentException.class); + assertThatThrownBy( + () -> + WorldManagementClient.buildAcquireInitialAdmissionBindHoldRequest( + 7L, + 42L, + 11L, + 4L, + "request-id", + "a".repeat(64), + null, + UUID.randomUUID(), + PlayableStateScope.PLAYABLE_STATE_SCOPE_SHARED, + 3L)) + .isInstanceOf(IllegalArgumentException.class); + } + private static void invokeBuildStub(WorldManagementClient client, ManagedChannel channel) { try { Method method = diff --git a/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/command/text/GameplayWorldCatalogTest.java b/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/command/text/GameplayWorldCatalogTest.java index b72acabbe4..245db26f2d 100644 --- a/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/command/text/GameplayWorldCatalogTest.java +++ b/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/command/text/GameplayWorldCatalogTest.java @@ -5,6 +5,7 @@ import static org.mockito.Mockito.when; import java.nio.charset.StandardCharsets; +import java.util.Arrays; import java.util.List; import java.util.UUID; import java.util.concurrent.atomic.AtomicInteger; @@ -85,29 +86,101 @@ void visibleWorldsDropIncompleteAuthorityPointers() { } @Test - void authoritySnapshotRejectsPublicRealmsAcrossDifferentWorldsForOneTenant() { + void authoritySnapshotSuppressesTenantWithMultiplePublicRealmsAndKeepsHealthyTenant() { when(authorityService.listPointers()) .thenReturn( List.of( publicPointer("alpha", "Alpha World", 1L, 11L), - publicPointer("beta", "Beta World", 1L, 12L))); + publicPointer("beta", "Beta World", 1L, 12L), + publicPointer("healthy", "Healthy World", 2L, 21L))); + GameplayWorldCatalog catalog = new GameplayWorldCatalog(authorityService); + + assertThat(catalog.visibleWorldsFromAuthoritySnapshot()) + .extracting(GameplayWorldCatalog.WorldView::slug) + .containsExactly("healthy"); + assertThat(catalog.resolveWorldFromAuthoritySnapshot("alpha")).isEmpty(); + assertThat(catalog.resolveWorldFromAuthoritySnapshot("healthy")).isPresent(); + } + + @Test + void authoritySnapshotSuppressesTenantWithoutPublicRealmAndKeepsHealthyTenant() { + when(authorityService.listPointers()) + .thenReturn( + List.of( + pointer("private", "Private World", "preview", "Preview", 1L, 11L, 7L), + publicPointer("healthy", "Healthy World", 2L, 21L))); + GameplayWorldCatalog catalog = new GameplayWorldCatalog(authorityService); + + assertThat(catalog.visibleWorldsFromAuthoritySnapshot()) + .extracting(GameplayWorldCatalog.WorldView::slug) + .containsExactly("healthy"); + assertThat(catalog.resolveWorldFromAuthoritySnapshot("private")).isEmpty(); + assertThat(catalog.resolveWorldFromAuthoritySnapshot("healthy")).isPresent(); + } + + @Test + void authoritySnapshotSuppressesTenantWithIncompletePointerAndKeepsHealthyTenant() { + when(authorityService.listPointers()) + .thenReturn( + List.of( + publicPointer("invalid", "Invalid World", 1L, 11L), + new GameplayAdmissionPointerSnapshot( + "broken", + "Broken World", + "production", + "Live Realm", + 1L, + 12L, + 0L, + true, + true, + false, + "SHARED", + "ALLOW_NEW"), + publicPointer("healthy", "Healthy World", 2L, 21L))); + GameplayWorldCatalog catalog = new GameplayWorldCatalog(authorityService); + + assertThat(catalog.visibleWorldsFromAuthoritySnapshot()) + .extracting(GameplayWorldCatalog.WorldView::slug) + .containsExactly("healthy"); + assertThat(catalog.resolveWorldFromAuthoritySnapshot("invalid")).isEmpty(); + assertThat(catalog.resolveWorldFromAuthoritySnapshot("broken")).isEmpty(); + assertThat(catalog.resolveWorldFromAuthoritySnapshot("healthy")).isPresent(); + } + + @Test + void authoritySnapshotFailsClosedWhenPointerTenantCannotBeIdentified() { + when(authorityService.listPointers()) + .thenReturn( + List.of( + publicPointer("healthy", "Healthy World", 2L, 21L), + pointer("unknown", "Unknown Tenant", "production", "Live Realm", 0L, 11L, 1L))); GameplayWorldCatalog catalog = new GameplayWorldCatalog(authorityService); assertThatThrownBy(catalog::visibleWorldsFromAuthoritySnapshot) .isInstanceOf(GameplayWorldCatalog.AuthorityPointerUnavailableException.class) - .hasMessageContaining("public-production realm count is invalid"); + .hasMessageContaining("tenant identity is unavailable"); } @Test - void authoritySnapshotRejectsTenantWithoutVisiblePublicRealm() { + void authoritySnapshotFailsClosedWhenPointerEntryIsNull() { when(authorityService.listPointers()) - .thenReturn( - List.of(pointer("demo", "Demo World", "private", "Private Realm", 1L, 11L, 7L))); + .thenReturn(Arrays.asList(publicPointer("healthy", "Healthy World", 2L, 21L), null)); + GameplayWorldCatalog catalog = new GameplayWorldCatalog(authorityService); + + assertThatThrownBy(catalog::visibleWorldsFromAuthoritySnapshot) + .isInstanceOf(GameplayWorldCatalog.AuthorityPointerUnavailableException.class) + .hasMessageContaining("pointer identity is unavailable"); + } + + @Test + void authoritySnapshotFailsClosedWhenPointerListIsUnavailable() { + when(authorityService.listPointers()).thenReturn(null); GameplayWorldCatalog catalog = new GameplayWorldCatalog(authorityService); assertThatThrownBy(catalog::visibleWorldsFromAuthoritySnapshot) .isInstanceOf(GameplayWorldCatalog.AuthorityPointerUnavailableException.class) - .hasMessageContaining("public-production realm count is invalid"); + .hasMessageContaining("pointer list is unavailable"); } @Test diff --git a/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/command/text/PlayCommandHandlerTest.java b/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/command/text/PlayCommandHandlerTest.java index 41565c7545..4c00ec76cb 100644 --- a/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/command/text/PlayCommandHandlerTest.java +++ b/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/command/text/PlayCommandHandlerTest.java @@ -81,6 +81,8 @@ void setUp() { List.of( realm("production", "Live Realm", 22L, 2L, true, true), realm("preview", "Preview Realm", 22L, 41L, true, true))))); + // Demo is this tenant's sole public-production realm; sandbox remains explicitly selectable. + gameplayCatalogProperties.getWorlds().get(1).getRealms().get(0).setPublicProductionRealm(false); handler = new PlayCommandHandler( sessionAuthenticationService, diff --git a/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/command/text/SessionResumptionFlowTest.java b/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/command/text/SessionResumptionFlowTest.java index be1ea72488..a72f9bd3a6 100644 --- a/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/command/text/SessionResumptionFlowTest.java +++ b/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/command/text/SessionResumptionFlowTest.java @@ -9,9 +9,11 @@ import static org.mockito.Mockito.when; import io.micrometer.core.instrument.simple.SimpleMeterRegistry; +import java.nio.charset.StandardCharsets; import java.util.List; import java.util.Map; import java.util.Optional; +import java.util.UUID; import java.util.concurrent.ConcurrentHashMap; import net.firedevops.firemud.account.AuthenticationErrorCodes; import net.firedevops.firemud.account.v1.AuthenticateResponse; @@ -74,7 +76,7 @@ @SuppressWarnings("unchecked") class SessionResumptionFlowTest { private static final String LOGIN_PAYLOAD = "LOGIN demo@example.com swordfish"; - private static final String PLAY_PAYLOAD = "PLAY demo"; + private static final String PLAY_PAYLOAD = "PLAY demo production"; private static final String LOOK_PAYLOAD = "LOOK"; private final CommandService commandService = Mockito.mock(CommandService.class); @@ -476,7 +478,7 @@ void deniedReconnectPlayClearsStaleGameplayBinding() { assertTrue(secondLogin.commandResult().accepted()); TextCommandInterpretationResult deniedPlay = interpreter.interpret("1", PLAY_PAYLOAD, false); assertFalse(deniedPlay.commandResult().accepted()); - assertEquals("WORLD_ACCESS_DENIED", deniedPlay.commandResult().errorCode()); + assertEquals("JOIN_REQUIRED", deniedPlay.commandResult().errorCode()); TextCommandInterpretationResult lookAfterDeniedReconnect = interpreter.interpret("1", LOOK_PAYLOAD, false); @@ -556,7 +558,10 @@ void staleIdentityMappingFallsBackToFreshSession() { interpreter.interpret("1", command, false); interpreter.interpret( - "1", new TextCommand(TextCommandType.PLAY, List.of("demo"), "PLAY demo"), false); + "1", + new TextCommand( + TextCommandType.PLAY, List.of("demo", "production"), "PLAY demo production"), + false); sessionContextService.evictIdentity(22L, 1L, 7001L); TextCommandInterpretationResult staleRetry = interpreter.interpret("2", command, false); @@ -578,6 +583,7 @@ private static GameplayCatalogProperties.World world( realm.setTenantId(tenantId); realm.setGameInstanceId(gameInstanceId); realm.setVisible(true); + realm.setPublicProductionRealm("demo".equals(slug)); realm.setRequiresCharacterSelection(requiresCharacterSelection); world.setRealms(List.of(realm)); return world; @@ -594,10 +600,17 @@ private static GameplayAdmissionPointerSnapshot pointer( gameInstanceId, pointerVersion, true, - true, + "demo".equals(worldSlug) && "production".equals(realmSlug), false, "SHARED", - "ALLOW_NEW"); + "ALLOW_NEW", + 1L, + stableUuid("realm:" + tenantId + ":" + worldSlug + ":" + realmSlug), + stableUuid("shared-namespace:" + tenantId)); + } + + private static UUID stableUuid(String value) { + return UUID.nameUUIDFromBytes(value.getBytes(StandardCharsets.UTF_8)); } private static SessionContext bootstrapShell(long sessionId, long bootstrapGameInstanceId) { diff --git a/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/command/text/TextCommandInterpreterTest.java b/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/command/text/TextCommandInterpreterTest.java index 954be4a473..1758e01f5b 100644 --- a/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/command/text/TextCommandInterpreterTest.java +++ b/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/command/text/TextCommandInterpreterTest.java @@ -12,9 +12,11 @@ import static org.mockito.Mockito.when; import io.micrometer.core.instrument.simple.SimpleMeterRegistry; +import java.nio.charset.StandardCharsets; import java.util.List; import java.util.Map; import java.util.Optional; +import java.util.UUID; import java.util.concurrent.ConcurrentHashMap; import net.firedevops.firemud.account.v1.AuthenticateResponse; import net.firedevops.firemud.account.v1.GetRealmAccessGrantForRuntimeResponse; @@ -87,6 +89,8 @@ @SuppressWarnings("unchecked") class TextCommandInterpreterTest { + private static final String PLAY_DEMO_PRODUCTION = "PLAY demo production"; + private final CommandService commandService = Mockito.mock(CommandService.class); private final GameLogicClient gameLogicClient = Mockito.mock(GameLogicClient.class); private final EntityManagementClient entityManagementClient = @@ -575,7 +579,7 @@ void helpIsVisibleBeforeLogin() { @Test void whoAfterPlayShowsCurrentPlayerList() { interpreter.interpret("1", "LOGIN demo@example.com swordfish", false); - interpreter.interpret("1", "PLAY demo", false); + interpreter.interpret("1", PLAY_DEMO_PRODUCTION, false); TextCommandInterpretationResult interpretation = interpreter.interpret("1", "WHO", false); @@ -599,7 +603,7 @@ void whoBeforePlayReturnsPlayRequired() { @Test void inventoryIsVisibleAfterPlay() { interpreter.interpret("1", "LOGIN demo@example.com swordfish", false); - interpreter.interpret("1", "PLAY demo", false); + interpreter.interpret("1", PLAY_DEMO_PRODUCTION, false); TextCommandInterpretationResult interpretation = interpreter.interpret("1", "INVENTORY", false); @@ -626,7 +630,7 @@ void inventoryBeforeLoginReturnsLoginRequired() { @Test void equipmentIsVisibleAfterPlay() { interpreter.interpret("1", "LOGIN demo@example.com swordfish", false); - interpreter.interpret("1", "PLAY demo", false); + interpreter.interpret("1", PLAY_DEMO_PRODUCTION, false); TextCommandInterpretationResult interpretation = interpreter.interpret("1", "EQ", false); @@ -642,7 +646,7 @@ void equipmentIsVisibleAfterPlay() { @Test void containerIsVisibleAfterPlay() { interpreter.interpret("1", "LOGIN demo@example.com swordfish", false); - interpreter.interpret("1", "PLAY demo", false); + interpreter.interpret("1", PLAY_DEMO_PRODUCTION, false); TextCommandInterpretationResult interpretation = interpreter.interpret("1", "CONTAINER Torch", false); @@ -678,7 +682,7 @@ void wearBeforeLoginReturnsLoginRequired() { @Test void wearAfterPlayEnqueuesDurableMutation() { interpreter.interpret("1", "LOGIN demo@example.com swordfish", false); - interpreter.interpret("1", "PLAY demo", false); + interpreter.interpret("1", PLAY_DEMO_PRODUCTION, false); TextCommandInterpretationResult interpretation = interpreter.interpret("1", "WEAR Torch", false); @@ -696,7 +700,7 @@ void wearAfterPlayEnqueuesDurableMutation() { @Test void removeAfterPlayEnqueuesDurableMutation() { interpreter.interpret("1", "LOGIN demo@example.com swordfish", false); - interpreter.interpret("1", "PLAY demo", false); + interpreter.interpret("1", PLAY_DEMO_PRODUCTION, false); TextCommandInterpretationResult interpretation = interpreter.interpret("1", "REMOVE Torch", false); @@ -714,7 +718,7 @@ void removeAfterPlayEnqueuesDurableMutation() { @Test void getAfterPlayEnqueuesDurableMutation() { interpreter.interpret("1", "LOGIN demo@example.com swordfish", false); - interpreter.interpret("1", "PLAY demo", false); + interpreter.interpret("1", PLAY_DEMO_PRODUCTION, false); TextCommandInterpretationResult interpretation = interpreter.interpret("1", "GET Torch", false); @@ -738,7 +742,7 @@ void getAfterPlayEnqueuesDurableMutation() { @Test void dropAfterPlayEnqueuesDurableMutation() { interpreter.interpret("1", "LOGIN demo@example.com swordfish", false); - interpreter.interpret("1", "PLAY demo", false); + interpreter.interpret("1", PLAY_DEMO_PRODUCTION, false); TextCommandInterpretationResult interpretation = interpreter.interpret("1", "DROP Torch", false); @@ -763,7 +767,7 @@ void dropAfterPlayEnqueuesDurableMutation() { @Test void putAfterPlayEnqueuesDurableMutation() { interpreter.interpret("1", "LOGIN demo@example.com swordfish", false); - interpreter.interpret("1", "PLAY demo", false); + interpreter.interpret("1", PLAY_DEMO_PRODUCTION, false); TextCommandInterpretationResult interpretation = interpreter.interpret("1", "PUT Ration INTO Torch", false); @@ -787,7 +791,7 @@ void putAfterPlayEnqueuesDurableMutation() { @Test void takeAfterPlayEnqueuesDurableMutation() { interpreter.interpret("1", "LOGIN demo@example.com swordfish", false); - interpreter.interpret("1", "PLAY demo", false); + interpreter.interpret("1", PLAY_DEMO_PRODUCTION, false); TextCommandInterpretationResult interpretation = interpreter.interpret("1", "TAKE Ration FROM Torch", false); @@ -873,7 +877,7 @@ void unknownCommandReturnsStructuredErrorOutput() { @Test void lookAfterPlayAppendsPromptOutput() { interpreter.interpret("1", "LOGIN demo@example.com swordfish", false); - interpreter.interpret("1", "PLAY demo", false); + interpreter.interpret("1", PLAY_DEMO_PRODUCTION, false); TextCommandInterpretationResult look = interpreter.interpret("1", "LOOK", false); @@ -890,7 +894,7 @@ void lookAfterPlayAppendsPromptOutput() { @Test void quickLookAfterPlayUsesShortVariantAndAppendsPrompt() { interpreter.interpret("1", "LOGIN demo@example.com swordfish", false); - interpreter.interpret("1", "PLAY demo", false); + interpreter.interpret("1", PLAY_DEMO_PRODUCTION, false); TextCommandInterpretationResult quickLook = interpreter.interpret("1", "QUICKLOOK", false); @@ -932,7 +936,7 @@ void directionalAliasBeforeLoginStillHitsInterpreterStageGate() { @Test void directionalAliasAfterPlayDelegatesToMoveHandler() { interpreter.interpret("1", "LOGIN demo@example.com swordfish", false); - interpreter.interpret("1", "PLAY demo", false); + interpreter.interpret("1", PLAY_DEMO_PRODUCTION, false); when(commandService.enqueue("1", "s", false)) .thenReturn(CommandEnqueueResult.success("cmd-77")); @@ -949,7 +953,7 @@ void directionalAliasAfterPlayDelegatesToMoveHandler() { @Test void malformedMovementAfterPlayReturnsInvalidArgumentWithoutEnqueueing() { interpreter.interpret("1", "LOGIN demo@example.com swordfish", false); - interpreter.interpret("1", "PLAY demo", false); + interpreter.interpret("1", PLAY_DEMO_PRODUCTION, false); Mockito.clearInvocations(commandService); for (String rawLine : List.of("north extra", "go west extra", "move sideways")) { @@ -969,13 +973,14 @@ void malformedMovementAfterPlayReturnsInvalidArgumentWithoutEnqueueing() { void loginPlayAndLookFlowWorks() { TextCommandInterpretationResult login = interpreter.interpret("1", "LOGIN demo@example.com swordfish", false); - TextCommandInterpretationResult play = interpreter.interpret("1", "PLAY demo", false); + TextCommandInterpretationResult play = interpreter.interpret("1", PLAY_DEMO_PRODUCTION, false); TextCommandInterpretationResult look = interpreter.interpret("1", "LOOK", false); assertTrue(login.commandResult().accepted()); assertTrue(play.commandResult().accepted()); assertEquals( - "OK PLAY Entered world: demo as demo\ndemo> ", renderedResponse("PLAY demo", play)); + "OK PLAY Entered world: demo as demo\ndemo> ", + renderedResponse(PLAY_DEMO_PRODUCTION, play)); assertTrue(look.commandResult().accepted()); assertEquals( List.of(PlayerOutputKind.VIEW, PlayerOutputKind.PROMPT), @@ -989,7 +994,7 @@ void loginPlayAndLookFlowWorks() { void sayAfterPlayDelegatesToHandler() { TextCommandInterpretationResult login = interpreter.interpret("1", "LOGIN demo@example.com swordfish", false); - TextCommandInterpretationResult play = interpreter.interpret("1", "PLAY demo", false); + TextCommandInterpretationResult play = interpreter.interpret("1", PLAY_DEMO_PRODUCTION, false); assertTrue(login.commandResult().accepted()); assertTrue(play.commandResult().accepted()); @@ -1009,7 +1014,7 @@ void sayAfterPlayDelegatesToHandler() { @Test void moveAfterPlayReturnsStructuredViewAndPrompt() { interpreter.interpret("1", "LOGIN demo@example.com swordfish", false); - interpreter.interpret("1", "PLAY demo", false); + interpreter.interpret("1", PLAY_DEMO_PRODUCTION, false); when(commandService.enqueue("1", "MOVE north", false)) .thenReturn(CommandEnqueueResult.success("cmd-move-1")); @@ -1048,6 +1053,7 @@ private static GameplayCatalogProperties.World world( realm.setTenantId(tenantId); realm.setGameInstanceId(gameInstanceId); realm.setVisible(true); + realm.setPublicProductionRealm("demo".equals(slug)); realm.setRequiresCharacterSelection(requiresCharacterSelection); world.setRealms(List.of(realm)); return world; @@ -1064,10 +1070,17 @@ private static GameplayAdmissionPointerSnapshot pointer( gameInstanceId, pointerVersion, true, - true, + "demo".equals(worldSlug) && "production".equals(realmSlug), false, "SHARED", - "ALLOW_NEW"); + "ALLOW_NEW", + 1L, + stableUuid("realm:" + tenantId + ":" + worldSlug + ":" + realmSlug), + stableUuid("shared-namespace:" + tenantId)); + } + + private static UUID stableUuid(String value) { + return UUID.nameUUIDFromBytes(value.getBytes(StandardCharsets.UTF_8)); } private static SessionContext bootstrapShell(long sessionId, long bootstrapGameInstanceId) { diff --git a/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/command/text/WorldsCommandHandlerTest.java b/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/command/text/WorldsCommandHandlerTest.java index 223d2a85d2..1ce40adc43 100644 --- a/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/command/text/WorldsCommandHandlerTest.java +++ b/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/command/text/WorldsCommandHandlerTest.java @@ -12,6 +12,7 @@ import net.firedevops.firemud.gamesession.presentation.WorldsViewOutput; import net.firedevops.firemud.gamesession.service.SessionContext; import net.firedevops.firemud.gamesession.support.TestGameplayWorldCatalogs; +import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.Test; import org.mockito.Mockito; @@ -25,6 +26,17 @@ class WorldsCommandHandlerTest { TestGameplayWorldCatalogs.fromProperties(gameplayCatalogProperties), entityManagementClient); + @BeforeEach + void setUp() { + // The default demo realm is the tenant's sole public-production target. + gameplayCatalogProperties + .getWorlds() + .get(1) + .getRealms() + .getFirst() + .setPublicProductionRealm(false); + } + @Test void browseViewReturnsStructuredWorldList() { WorldsViewOutput response = handler.browseView(); @@ -71,6 +83,12 @@ void browseRealmsToleratesNullRealmEnums() { void browseCharactersReturnsStructuredCharacterList() { gameplayCatalogProperties.setWorlds( List.of(world("demo", 22L, 1L, false), world("sandbox", 22L, 2L, true))); + gameplayCatalogProperties + .getWorlds() + .get(1) + .getRealms() + .getFirst() + .setPublicProductionRealm(false); Mockito.when( entityManagementClient.listCharactersByAccount( "22", "123", "1", PlayableStateScope.PLAYABLE_STATE_SCOPE_SHARED)) @@ -179,6 +197,7 @@ private static GameplayCatalogProperties.World world( realm.setTenantId(tenantId); realm.setGameInstanceId(gameInstanceId); realm.setVisible(true); + realm.setPublicProductionRealm(true); realm.setRequiresCharacterSelection(requiresCharacterSelection); realm.setStateScope(GameplayCatalogProperties.RealmStateScope.SHARED); realm.setCharacterCreationPolicy(GameplayCatalogProperties.CharacterCreationPolicy.ALLOW_NEW); diff --git a/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/command/text/WorldsTextCommandDispatchHandlerTest.java b/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/command/text/WorldsTextCommandDispatchHandlerTest.java index 1b955207e9..30db1cce01 100644 --- a/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/command/text/WorldsTextCommandDispatchHandlerTest.java +++ b/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/command/text/WorldsTextCommandDispatchHandlerTest.java @@ -155,6 +155,7 @@ private static GameplayCatalogProperties.World world( realm.setTenantId(tenantId); realm.setGameInstanceId(gameInstanceId); realm.setVisible(true); + realm.setPublicProductionRealm(true); realm.setRequiresCharacterSelection(requiresCharacterSelection); realm.setStateScope(GameplayCatalogProperties.RealmStateScope.SHARED); realm.setCharacterCreationPolicy(GameplayCatalogProperties.CharacterCreationPolicy.ALLOW_NEW); diff --git a/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/data/GameplayAdmissionPointerBootstrapInitializerTest.java b/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/data/GameplayAdmissionPointerBootstrapInitializerTest.java index e64deb86b0..cd05a5c705 100644 --- a/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/data/GameplayAdmissionPointerBootstrapInitializerTest.java +++ b/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/data/GameplayAdmissionPointerBootstrapInitializerTest.java @@ -69,9 +69,14 @@ void runPreservesExistingPointerAuthorityOnRestart() throws Exception { } @Test - void runRejectsMissingBootstrapPointerSeedsBeforeAnyMutation() throws Exception { - assertRejectedBeforeMutation( - List.of(), "Gameplay admission pointer bootstrap seeds are required"); + void runTreatsEmptyBootstrapPointerSeedsAsExplicitOptOutWithoutMutation() throws Exception { + when(pointerRepository.count()).thenReturn(0L); + properties.setPointers(List.of()); + + initializer.run(new DefaultApplicationArguments(new String[] {})); + + verify(pointerRepository).count(); + verifyNoMoreInteractions(pointerRepository); } @Test 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 new file mode 100644 index 0000000000..f0f59f5d88 --- /dev/null +++ b/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/data/RunOwnedInitialAdmissionFixtureCapabilityTest.java @@ -0,0 +1,170 @@ +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.Mockito.mock; +import static org.mockito.Mockito.when; + +import java.nio.file.Files; +import java.nio.file.Path; +import java.security.PublicKey; +import java.security.cert.X509Certificate; +import java.util.List; +import net.firedevops.firemud.gamesession.data.RunOwnedInitialAdmissionFixtureCapability.CertificatePins; +import org.junit.jupiter.api.Test; +import org.junit.jupiter.api.io.TempDir; + +class RunOwnedInitialAdmissionFixtureCapabilityTest { + private static final String RUN_ID = "compose-smoke-2939"; + private static final String PROJECT_NAME = "firemud-smoke-compose-smoke-2939"; + private static final String OPERATION_ID = "d2db8478-9c56-42ab-99c2-9fbead6841ba"; + private static final String LEAF_SHA = "a".repeat(64); + private static final String CA_SHA = "b".repeat(64); + + @Test + void parsesExactCapabilityAndBindsRunProjectSelectorsAndTlsPins() { + RunOwnedInitialAdmissionFixtureCapability capability = + RunOwnedInitialAdmissionFixtureCapability.parseAndValidate( + validJson().getBytes(java.nio.charset.StandardCharsets.UTF_8), + RUN_ID, + PROJECT_NAME, + pins()); + + assertThat(capability.runId()).isEqualTo(RUN_ID); + assertThat(capability.composeProjectName()).isEqualTo(PROJECT_NAME); + assertThat(capability.operationId()).isEqualTo(OPERATION_ID); + assertThat(capability.tenantId()).isEqualTo(7L); + assertThat(capability.gameTemplateId()).isEqualTo(17L); + assertThat(capability.ownerAccountId()).isEqualTo(27L); + assertThat(capability.worldSlug()).isEqualTo("demo"); + assertThat(capability.realmSlug()).isEqualTo("production"); + assertThat(capability.visible()).isTrue(); + assertThat(capability.publicProductionRealm()).isTrue(); + assertThat(capability.requiresCharacterSelection()).isFalse(); + assertThat(capability.stateScope()).isEqualTo("SHARED"); + assertThat(capability.characterCreationPolicy()).isEqualTo("ALLOW_NEW"); + } + + @Test + void rejectsUnknownDuplicateMismatchedAndNoncanonicalCapabilityFields() { + assertInvalid(validJson().replace("\"schema\":", "\"extra\":true,\"schema\":")); + assertInvalid(validJson().replace("\"schema\":", "\"schema\":\"wrong\",\"schema\":")); + assertInvalid(validJson().replace(RUN_ID, "different-run")); + assertInvalid(validJson().replace("\"tenantId\": 7", "\"tenantId\": \"7\"")); + assertInvalid( + validJson().replace("\"stateScope\": \"SHARED\"", "\"stateScope\": \"ISOLATED\"")); + assertInvalid(validJson().replace(LEAF_SHA, "c".repeat(64))); + assertThatThrownBy( + () -> + RunOwnedInitialAdmissionFixtureCapability.parseAndValidate( + validJson().getBytes(java.nio.charset.StandardCharsets.UTF_8), + RUN_ID, + "other-project", + pins())) + .isInstanceOf(RunOwnedInitialAdmissionFixtureCapability.InvalidCapabilityException.class); + } + + @Test + void rejectsWritableCapabilityFile(@TempDir Path directory) throws Exception { + Path capabilityFile = + Files.writeString(directory.resolve("fixture-capability.json"), validJson()); + + assertThatThrownBy( + () -> + RunOwnedInitialAdmissionFixtureCapability.load( + capabilityFile, RUN_ID, PROJECT_NAME, null)) + .isInstanceOf(RunOwnedInitialAdmissionFixtureCapability.InvalidCapabilityException.class); + } + + @Test + void derivesPinsFromActualLeafAndCaCertificatesAndRequiresOneExactUriSan() throws Exception { + X509Certificate leaf = + certificate( + RunOwnedInitialAdmissionFixtureCapability.GAME_SESSION_URI_SAN, new byte[] {1}, -1); + X509Certificate ca = certificate(null, new byte[] {2}, 1); + PublicKey publicKey = mock(PublicKey.class); + when(ca.getPublicKey()).thenReturn(publicKey); + when(leaf.getSubjectAlternativeNames()) + .thenReturn( + List.of(List.of(6, RunOwnedInitialAdmissionFixtureCapability.GAME_SESSION_URI_SAN))); + + CertificatePins pins = RunOwnedInitialAdmissionFixtureCapability.certificatePins(leaf, ca); + + assertThat(pins.leafSha256()).hasSize(64).matches("[0-9a-f]{64}"); + assertThat(pins.uriSan()) + .isEqualTo(RunOwnedInitialAdmissionFixtureCapability.GAME_SESSION_URI_SAN); + assertThat(pins.caSha256()).hasSize(64).matches("[0-9a-f]{64}"); + + when(leaf.getSubjectAlternativeNames()) + .thenReturn( + List.of( + List.of(6, RunOwnedInitialAdmissionFixtureCapability.GAME_SESSION_URI_SAN), + List.of(6, "spiffe://firemud/ns/dev/sa/other-service"))); + assertThatThrownBy(() -> RunOwnedInitialAdmissionFixtureCapability.certificatePins(leaf, ca)) + .isInstanceOf(RunOwnedInitialAdmissionFixtureCapability.InvalidCapabilityException.class); + } + + private static CertificatePins pins() { + return new CertificatePins( + LEAF_SHA, RunOwnedInitialAdmissionFixtureCapability.GAME_SESSION_URI_SAN, CA_SHA); + } + + private static String validJson() { + 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" + } + """ + .formatted( + RunOwnedInitialAdmissionFixtureCapability.CAPABILITY_SCHEMA, + RUN_ID, + PROJECT_NAME, + OPERATION_ID, + LEAF_SHA, + RunOwnedInitialAdmissionFixtureCapability.GAME_SESSION_URI_SAN, + CA_SHA); + } + + private static X509Certificate certificate(String san, byte[] der, int basicConstraints) + throws Exception { + X509Certificate certificate = mock(X509Certificate.class); + when(certificate.getBasicConstraints()).thenReturn(basicConstraints); + when(certificate.getEncoded()).thenReturn(der); + when(certificate.getPublicKey()).thenReturn(mock(PublicKey.class)); + if (san == null) { + when(certificate.getSubjectAlternativeNames()).thenReturn(List.of()); + } else { + when(certificate.getSubjectAlternativeNames()).thenReturn(List.of(List.of(6, san))); + } + return certificate; + } + + private static void assertInvalid(String json) { + assertThatThrownBy( + () -> + RunOwnedInitialAdmissionFixtureCapability.parseAndValidate( + json.getBytes(java.nio.charset.StandardCharsets.UTF_8), + RUN_ID, + PROJECT_NAME, + pins())) + .isInstanceOf(RunOwnedInitialAdmissionFixtureCapability.InvalidCapabilityException.class); + } +} 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 new file mode 100644 index 0000000000..c30a776360 --- /dev/null +++ b/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/data/RunOwnedInitialAdmissionFixtureCoordinatorTest.java @@ -0,0 +1,396 @@ +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.inOrder; +import static org.mockito.Mockito.never; +import static org.mockito.Mockito.verify; +import static org.mockito.Mockito.verifyNoInteractions; +import static org.mockito.Mockito.when; + +import java.time.Instant; +import java.util.UUID; +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.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.mockito.InOrder; + +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 OPERATION_ID = "d2db8478-9c56-42ab-99c2-9fbead6841ba"; + 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); + + assertThat(result) + .isEqualTo(RunOwnedInitialAdmissionFixtureCoordinator.BootstrapResult.COMMITTED); + InOrder order = inOrder(fixture.gameInstanceService, fixture.ownerService, fixture.worldClient); + order.verify(fixture.gameInstanceService).startRunOwnedInitialLaunch(any()); + 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)) + .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)) + .isInstanceOf(IllegalStateException.class); + + verify(fixture.ownerService, never()).attachHold(any()); + verify(fixture.ownerService, never()).commit(any()); + verify(fixture.ownerService, never()).abort(any()); + } + + @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)) + .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); + } + + 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", + "a".repeat(64), + RunOwnedInitialAdmissionFixtureCapability.GAME_SESSION_URI_SAN, + "b".repeat(64)); + 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())) + .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, + "/unused-for-direct-coordination.json", + RUN_ID, + PROJECT_NAME, + grpc, + gameInstanceService, + ownerService, + worldClient); + return new Fixture( + coordinator, capability, gameInstanceService, ownerService, worldClient, request); + } + + 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 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, + GameInstanceService gameInstanceService, + InitialAdmissionBindOwnerService ownerService, + WorldManagementClient worldClient, + AtomicReference request) {} +} diff --git a/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/data/TestDataSeederTest.java b/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/data/TestDataSeederTest.java index 0ec9ea647c..aa2a4bd832 100644 --- a/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/data/TestDataSeederTest.java +++ b/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/data/TestDataSeederTest.java @@ -2,10 +2,10 @@ import static org.mockito.ArgumentMatchers.any; import static org.mockito.Mockito.verify; +import static org.mockito.Mockito.verifyNoInteractions; import static org.mockito.Mockito.when; import net.firedevops.firemud.gamesession.entity.FeatureFlag; -import net.firedevops.firemud.gamesession.entity.GameInstance; import net.firedevops.firemud.gamesession.entity.GameManifest; import net.firedevops.firemud.gamesession.repository.FeatureFlagRepository; import net.firedevops.firemud.gamesession.repository.GameInstanceRepository; @@ -27,22 +27,19 @@ class TestDataSeederTest { @BeforeEach void setup() { - seeder = - new TestDataSeeder(gameManifestRepository, featureFlagRepository, gameInstanceRepository); + seeder = new TestDataSeeder(gameManifestRepository, featureFlagRepository); } @Test - void runSeedsAndReassertsCanonicalRuntimeData() throws Exception { + void runSeedsCanonicalNonRuntimeData() throws Exception { when(gameManifestRepository.findAll()).thenReturn(java.util.List.of()); when(featureFlagRepository.findByTenantIdAndName(1L, "double_xp")) .thenReturn(java.util.Optional.empty()); - when(gameInstanceRepository.findFirstByTenantIdAndOwnerAccountIdAndStatus(1L, 1L, "RUNNING")) - .thenReturn(java.util.Optional.empty()); seeder.run(new DefaultApplicationArguments(new String[] {})); verify(gameManifestRepository).save(any(GameManifest.class)); verify(featureFlagRepository).save(any(FeatureFlag.class)); - verify(gameInstanceRepository).save(any(GameInstance.class)); + verifyNoInteractions(gameInstanceRepository); } } diff --git a/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/repository/InitialAdmissionBindAttemptRepositoryTest.java b/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/repository/InitialAdmissionBindAttemptRepositoryTest.java new file mode 100644 index 0000000000..919ab297cb --- /dev/null +++ b/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/repository/InitialAdmissionBindAttemptRepositoryTest.java @@ -0,0 +1,122 @@ +package net.firedevops.firemud.gamesession.repository; + +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertNull; +import static org.junit.jupiter.api.Assertions.assertThrows; + +import java.sql.Connection; +import java.sql.DriverManager; +import java.time.Instant; +import java.util.UUID; +import net.firedevops.firemud.gamesession.entity.InitialAdmissionBindAttempt; +import net.firedevops.firemud.gamesession.entity.InitialAdmissionBindAttempt.Status; +import org.jooq.DSLContext; +import org.jooq.SQLDialect; +import org.jooq.impl.DSL; +import org.junit.jupiter.api.Test; + +class InitialAdmissionBindAttemptRepositoryTest { + @Test + void attachHoldOnlyAttachesToPendingAttemptWithNoExistingHold() throws Exception { + try (Connection connection = + DriverManager.getConnection( + "jdbc:h2:mem:initial-admission-attach-hold;MODE=PostgreSQL;DATABASE_TO_LOWER=TRUE;DB_CLOSE_DELAY=-1")) { + DSLContext dsl = DSL.using(connection, SQLDialect.H2); + createSchema(dsl); + InitialAdmissionBindAttemptRepository repository = + new InitialAdmissionBindAttemptRepository(dsl); + + InitialAdmissionBindAttempt pending = + repository.insertPending(attempt("request-attached", UUID.randomUUID())); + UUID firstHoldId = UUID.randomUUID(); + UUID firstHoldFence = UUID.randomUUID(); + Instant attachedAt = Instant.parse("2026-10-02T00:00:00Z"); + + InitialAdmissionBindAttempt attached = + repository.attachHold(pending, firstHoldId, firstHoldFence, attachedAt); + + assertEquals(firstHoldId, attached.holdId()); + assertEquals(firstHoldFence, attached.holdFence()); + assertEquals(attachedAt, attached.updatedAt()); + assertThrows( + IllegalStateException.class, + () -> repository.attachHold(pending, UUID.randomUUID(), UUID.randomUUID(), attachedAt)); + + InitialAdmissionBindAttempt unchanged = + repository.findByTenantAndRequestId(17L, "request-attached").orElseThrow(); + assertEquals(firstHoldId, unchanged.holdId()); + assertEquals(firstHoldFence, unchanged.holdFence()); + assertEquals(attachedAt, unchanged.updatedAt()); + + InitialAdmissionBindAttempt secondPending = + repository.insertPending(attempt("request-terminal", UUID.randomUUID())); + Instant terminalAt = Instant.parse("2026-10-02T00:01:00Z"); + InitialAdmissionBindAttempt aborted = repository.markAborted(secondPending, terminalAt); + + assertThrows( + IllegalStateException.class, + () -> repository.attachHold(aborted, UUID.randomUUID(), UUID.randomUUID(), attachedAt)); + + InitialAdmissionBindAttempt terminalReadback = + repository.findByTenantAndRequestId(17L, "request-terminal").orElseThrow(); + assertEquals(Status.ABORTED, terminalReadback.status()); + assertNull(terminalReadback.holdId()); + assertNull(terminalReadback.holdFence()); + assertEquals(terminalAt, terminalReadback.terminalAt()); + } + } + + private static InitialAdmissionBindAttempt attempt(String requestId, UUID realmId) { + Instant createdAt = Instant.parse("2026-10-01T00:00:00Z"); + return new InitialAdmissionBindAttempt( + UUID.randomUUID(), + 17L, + requestId, + "a".repeat(64), + realmId, + UUID.randomUUID(), + "SHARED", + true, + 1L, + 93L, + 44L, + 8L, + null, + null, + Status.PENDING, + null, + null, + createdAt, + createdAt, + null); + } + + private static void createSchema(DSLContext dsl) { + dsl.execute( + """ + CREATE TABLE gameplay_initial_admission_bind_attempt ( + attempt_id UUID PRIMARY KEY, + tenant_id BIGINT NOT NULL, + initial_admission_request_id VARCHAR(128) NOT NULL, + request_digest VARCHAR(64) NOT NULL, + realm_id UUID NOT NULL, + playable_state_namespace_id UUID NOT NULL, + playable_state_scope VARCHAR(32) NOT NULL, + expected_no_prior_pointer BOOLEAN NOT NULL, + catalog_revision BIGINT NOT NULL, + game_instance_id BIGINT NOT NULL, + version_id BIGINT NOT NULL, + active_lifecycle_epoch BIGINT NOT NULL, + hold_id UUID, + hold_fence UUID, + status VARCHAR(16) NOT NULL, + pointer_id BIGINT, + audit_event_id BIGINT, + created_at TIMESTAMP NOT NULL, + updated_at TIMESTAMP NOT NULL, + terminal_at TIMESTAMP, + UNIQUE (tenant_id, initial_admission_request_id) + ) + """); + } +} diff --git a/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/service/impl/DatabaseGameplayAdmissionPointerAuthorityServiceTest.java b/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/service/impl/DatabaseGameplayAdmissionPointerAuthorityServiceTest.java index e00918d460..3b3cd915d6 100644 --- a/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/service/impl/DatabaseGameplayAdmissionPointerAuthorityServiceTest.java +++ b/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/service/impl/DatabaseGameplayAdmissionPointerAuthorityServiceTest.java @@ -177,6 +177,40 @@ void upsertPointerAdvancesCatalogRevisionWithoutAdvancingPointerVersion() { eventCaptor.getValue().getPlayableStateNamespaceId()); } + @Test + void upsertPointerRuntimeTargetChangeAdvancesPointerVersionWithoutCatalogRevision() { + GameplayAdmissionPointer existing = existingPointer(); + when(pointerRepository.findByTenantIdAndWorldSlugAndRealmSlug(1L, "demo", "production")) + .thenReturn(Optional.of(existing)); + when(pointerRepository.save(any(GameplayAdmissionPointer.class))) + .thenAnswer(invocation -> invocation.getArgument(0)); + + GameplayAdmissionPointerSnapshot snapshot = + service.upsertPointer( + new GameplayAdmissionPointerMutation( + "demo", + "Demo World", + "production", + "Live Realm", + 1L, + 8L, + true, + true, + false, + "SHARED", + "ALLOW_NEW", + "tester", + "runtime target change", + "req-runtime-target", + 1L, + null)); + + assertEquals(2L, snapshot.pointerVersion()); + assertEquals(1L, snapshot.catalogRevision()); + verify(pointerRepository).save(any(GameplayAdmissionPointer.class)); + verify(eventRepository).save(any(GameplayAdmissionPointerEvent.class)); + } + @Test void upsertPointerExactNoOpDoesNotAdvanceOrPersistVersions() { GameplayAdmissionPointer existing = existingPointer(); diff --git a/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/service/impl/GameInstanceServiceImplTest.java b/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/service/impl/GameInstanceServiceImplTest.java index 8fe731a62a..f3f26bc9b6 100644 --- a/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/service/impl/GameInstanceServiceImplTest.java +++ b/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/service/impl/GameInstanceServiceImplTest.java @@ -8,6 +8,7 @@ import static org.mockito.ArgumentMatchers.anyString; import static org.mockito.ArgumentMatchers.argThat; import static org.mockito.ArgumentMatchers.eq; +import static org.mockito.Mockito.clearInvocations; import static org.mockito.Mockito.doAnswer; import static org.mockito.Mockito.doReturn; import static org.mockito.Mockito.doThrow; @@ -15,6 +16,8 @@ import static org.mockito.Mockito.never; import static org.mockito.Mockito.times; import static org.mockito.Mockito.verify; +import static org.mockito.Mockito.verifyNoInteractions; +import static org.mockito.Mockito.verifyNoMoreInteractions; import static org.mockito.Mockito.when; import io.micrometer.core.instrument.MeterRegistry; @@ -25,6 +28,7 @@ import java.util.Optional; import java.util.concurrent.atomic.AtomicInteger; import java.util.concurrent.atomic.AtomicLong; +import java.util.concurrent.atomic.AtomicReference; import net.firedevops.firemud.gamedesign.v1.GetPublishedReleaseBundleResponse; import net.firedevops.firemud.gamedesign.v1.GetVersionAssetArtifactStateResponse; import net.firedevops.firemud.gamedesign.v1.ResolveLaunchDescriptorResponse; @@ -37,6 +41,7 @@ import net.firedevops.firemud.gamesession.repository.GameInstanceRepository; import net.firedevops.firemud.gamesession.service.SessionStateService; import net.firedevops.firemud.worldmanagement.v1.GetWorldInstanceLifecycleResponse; +import net.firedevops.firemud.worldmanagement.v1.PrepareWorldInstanceResponse; import net.firedevops.firemud.worldmanagement.v1.WorldInstanceLifecycleSnapshot; import net.firedevops.firemud.worldmanagement.v1.WorldInstanceLifecycleStatus; import org.junit.jupiter.api.BeforeEach; @@ -125,6 +130,243 @@ void startSessionSavesState() { assertNull(store.get(10L).getScriptPinEpoch()); } + @Test + void runOwnedInitialLaunchExactRetryReturnsSameActiveTargetWithoutReplayingActivation() { + StartSessionRequest request = new StartSessionRequest(1L, 3L, "run-owned-1", 42L); + configureRunOwnedWorld(request); + + var first = service.startRunOwnedInitialLaunch(request); + clearInvocations(stateService, worldManagementClient); + var retry = service.startRunOwnedInitialLaunch(request); + + assertEquals(first.gameInstance().id(), retry.gameInstance().id()); + assertEquals(10L, retry.gameInstance().id()); + assertEquals(11L, retry.gameInstance().versionId()); + assertEquals(2L, retry.activeLifecycleEpoch()); + assertEquals("RUNNING", store.get(10L).getStatus()); + assertEquals(1L, store.get(10L).getRunOwnedStartPreparingEpoch()); + assertEquals(2L, store.get(10L).getRunOwnedStartActiveEpoch()); + assertEquals( + "edb9ae538f4a9c8e74053c2a7f6d0bc251353b64afc367defab5b5369785e708", + store.get(10L).getRunOwnedStartRequestDigest()); + ArgumentCaptor repairedState = ArgumentCaptor.forClass(GameInstanceDto.class); + verify(stateService).saveState(repairedState.capture()); + assertEquals("RUNNING", repairedState.getValue().status()); + verify(worldManagementClient).getWorldInstanceLifecycle(1L, 10L); + verifyNoMoreInteractions(worldManagementClient); + } + + @Test + void runOwnedRunningRetryRejectsContradictoryPreparingWorldWithoutRuntimeMutation() { + StartSessionRequest request = new StartSessionRequest(1L, 3L, "run-owned-preparing", 42L); + AtomicReference worldState = configureRunOwnedWorld(request); + service.startRunOwnedInitialLaunch(request); + clearInvocations(stateService, worldManagementClient); + worldState.set( + runOwnedWorldSnapshot( + request, + 10L, + 1L, + WorldInstanceLifecycleStatus.WORLD_INSTANCE_LIFECYCLE_STATUS_PREPARING)); + + IllegalStateException error = + assertThrows( + IllegalStateException.class, () -> service.startRunOwnedInitialLaunch(request)); + + assertEquals( + "RUN_OWNED_INITIAL_LAUNCH_STATE_MISMATCH: running owner row is not ACTIVE in World", + error.getMessage()); + assertEquals("RUNNING", store.get(10L).getStatus()); + assertEquals(2L, store.get(10L).getRunOwnedStartActiveEpoch()); + verifyNoInteractions(stateService); + verify(worldManagementClient).getWorldInstanceLifecycle(1L, 10L); + verifyNoMoreInteractions(worldManagementClient); + } + + @Test + void runOwnedInitialLaunchRetryReconcilesAmbiguousPrepareOnTheSameInstance() { + StartSessionRequest request = new StartSessionRequest(1L, 3L, "run-owned-prepare-timeout", 42L); + AtomicReference worldState = configureRunOwnedWorld(request); + AtomicInteger prepareCalls = new AtomicInteger(); + when(worldManagementClient.prepareWorldInstance( + anyLong(), + anyLong(), + anyLong(), + anyString(), + anyString(), + anyLong(), + any(), + any(), + anyString(), + anyLong(), + anyString(), + anyLong(), + any())) + .thenAnswer( + invocation -> { + if (prepareCalls.getAndIncrement() == 0) { + worldState.set( + runOwnedWorldSnapshot( + request, + invocation.getArgument(1, Long.class), + 1L, + WorldInstanceLifecycleStatus.WORLD_INSTANCE_LIFECYCLE_STATUS_PREPARING)); + throw new IllegalStateException("prepare response timed out"); + } + return net.firedevops.firemud.worldmanagement.v1.PrepareWorldInstanceResponse + .newBuilder() + .setWorldInstance(worldState.get()) + .build(); + }); + + IllegalStateException pending = + assertThrows( + IllegalStateException.class, () -> service.startRunOwnedInitialLaunch(request)); + + assertEquals("world preparation authority unavailable", pending.getMessage()); + assertEquals(1, store.size()); + assertEquals(10L, store.get(10L).getId()); + assertNull(store.get(10L).getRunOwnedStartPreparingEpoch()); + + var resumed = service.startRunOwnedInitialLaunch(request); + + assertEquals(10L, resumed.gameInstance().id()); + assertEquals(2L, resumed.activeLifecycleEpoch()); + assertEquals(1, store.size()); + assertEquals("RUNNING", store.get(10L).getStatus()); + verify(worldManagementClient, times(2)) + .prepareWorldInstance( + anyLong(), + anyLong(), + anyLong(), + anyString(), + anyString(), + anyLong(), + any(), + any(), + anyString(), + anyLong(), + anyString(), + anyLong(), + any()); + } + + @Test + void runOwnedInitialLaunchRetryReconcilesAmbiguousActivationOnTheSameInstance() { + StartSessionRequest request = new StartSessionRequest(1L, 3L, "run-owned-timeout", 42L); + AtomicReference worldState = configureRunOwnedWorld(request); + doThrow(new IllegalStateException("activation response timed out")) + .when(worldManagementClient) + .activatePreparedWorldInstance(1L, 10L, 1L); + + IllegalStateException pending = + assertThrows( + IllegalStateException.class, () -> service.startRunOwnedInitialLaunch(request)); + + assertEquals("world activation authority unavailable", pending.getMessage()); + assertEquals("STARTING", store.get(10L).getStatus()); + assertEquals(1L, store.get(10L).getRunOwnedStartPreparingEpoch()); + assertNull(store.get(10L).getRunOwnedStartActiveEpoch()); + worldState.set( + runOwnedWorldSnapshot( + request, 10L, 2L, WorldInstanceLifecycleStatus.WORLD_INSTANCE_LIFECYCLE_STATUS_ACTIVE)); + + var resumed = service.startRunOwnedInitialLaunch(request); + + assertEquals(10L, resumed.gameInstance().id()); + assertEquals(2L, resumed.activeLifecycleEpoch()); + assertEquals(1, store.size()); + assertEquals("RUNNING", store.get(10L).getStatus()); + verify(worldManagementClient, times(1)).activatePreparedWorldInstance(1L, 10L, 1L); + verify(repository, never()).deleteById(10L); + } + + @Test + void runOwnedInitialLaunchRequestIdConflictsOnChangedOwnerOrTemplate() { + StartSessionRequest request = new StartSessionRequest(1L, 3L, "run-owned-conflict", 42L); + configureRunOwnedWorld(request); + service.startRunOwnedInitialLaunch(request); + + assertThrows( + IllegalStateException.class, + () -> + service.startRunOwnedInitialLaunch( + new StartSessionRequest(1L, 3L, "run-owned-conflict", 43L))); + assertThrows( + IllegalStateException.class, + () -> + service.startRunOwnedInitialLaunch( + new StartSessionRequest(1L, 4L, "run-owned-conflict", 42L))); + + assertEquals(1, store.size()); + assertEquals(10L, store.get(10L).getId()); + verify(worldManagementClient, times(1)) + .prepareWorldInstance( + anyLong(), + anyLong(), + anyLong(), + anyString(), + anyString(), + anyLong(), + any(), + any(), + anyString(), + anyLong(), + anyString(), + anyLong(), + any()); + } + + @Test + void runOwnedInitialLaunchRejectsWorldDescriptorMismatchAndRetainsIdentity() { + StartSessionRequest request = new StartSessionRequest(1L, 3L, "run-owned-mismatch", 42L); + AtomicReference worldState = configureRunOwnedWorld(request); + doAnswer( + invocation -> + GetWorldInstanceLifecycleResponse.newBuilder() + .setWorldInstance( + worldState.get().toBuilder() + .setPublishedReleaseBundleRef("prb:1:11:78") + .build()) + .build()) + .when(worldManagementClient) + .getWorldInstanceLifecycle(anyLong(), anyLong()); + + IllegalStateException error = + assertThrows( + IllegalStateException.class, () -> service.startRunOwnedInitialLaunch(request)); + + assertEquals( + "WORLD_AUTHORITY_DESCRIPTOR_MISMATCH: lifecycle readback differs from the resolved launch descriptor", + error.getMessage()); + assertEquals(1, store.size()); + assertEquals("STARTING", store.get(10L).getStatus()); + assertEquals(1L, store.get(10L).getRunOwnedStartPreparingEpoch()); + verify(worldManagementClient, never()) + .activatePreparedWorldInstance(anyLong(), anyLong(), anyLong()); + } + + @Test + void runOwnedInitialLaunchRetainsTerminalIdentityAfterPreActivationFailure() { + StartSessionRequest request = new StartSessionRequest(1L, 3L, "run-owned-failed", 42L); + AtomicReference worldState = configureRunOwnedWorld(request); + worldState.set( + runOwnedWorldSnapshot( + request, + 10L, + 2L, + WorldInstanceLifecycleStatus.WORLD_INSTANCE_LIFECYCLE_STATUS_FAILED_PRE_ACTIVATION)); + + assertThrows(IllegalStateException.class, () -> service.startRunOwnedInitialLaunch(request)); + assertThrows(IllegalStateException.class, () -> service.startRunOwnedInitialLaunch(request)); + + assertEquals(1, store.size()); + assertEquals("run-owned-failed", store.get(10L).getRunOwnedStartRequestId()); + assertEquals("STARTING", store.get(10L).getStatus()); + verify(worldManagementClient, never()) + .activatePreparedWorldInstance(anyLong(), anyLong(), anyLong()); + } + @Test void startSessionLeavesScriptPinTupleAbsentUntilOwnerPinTransition() { doReturn( @@ -1092,6 +1334,27 @@ private void configureRepositoryPersistence() { GameInstance stored = store.get(id); return stored == null ? Optional.empty() : Optional.of(copyOf(stored)); }); + when(repository.findByTenantIdAndRunOwnedStartRequestIdForUpdate(anyLong(), anyString())) + .thenAnswer( + invocation -> { + Long tenantId = invocation.getArgument(0); + String requestId = invocation.getArgument(1); + return store.values().stream() + .filter(instance -> tenantId.equals(instance.getTenantId())) + .filter(instance -> requestId.equals(instance.getRunOwnedStartRequestId())) + .findFirst() + .map(GameInstanceServiceImplTest::copyOf); + }); + when(repository.findByTenantIdAndGameInstanceIdForUpdate(anyLong(), anyLong())) + .thenAnswer( + invocation -> { + Long tenantId = invocation.getArgument(0); + Long gameInstanceId = invocation.getArgument(1); + GameInstance stored = store.get(gameInstanceId); + return stored != null && tenantId.equals(stored.getTenantId()) + ? Optional.of(copyOf(stored)) + : Optional.empty(); + }); when(repository.findFirstByTenantIdAndOwnerAccountIdAndStatus( any(Long.class), any(Long.class), any())) .thenAnswer( @@ -1504,6 +1767,82 @@ private void configureWorldActivation() { .build()); } + private AtomicReference configureRunOwnedWorld( + StartSessionRequest request) { + AtomicReference worldState = new AtomicReference<>(); + when(worldManagementClient.prepareWorldInstance( + anyLong(), + anyLong(), + anyLong(), + anyString(), + anyString(), + anyLong(), + any(), + any(), + anyString(), + anyLong(), + anyString(), + anyLong(), + any())) + .thenAnswer( + invocation -> { + if (worldState.get() == null) { + worldState.set( + runOwnedWorldSnapshot( + request, + invocation.getArgument(1, Long.class), + 1L, + WorldInstanceLifecycleStatus.WORLD_INSTANCE_LIFECYCLE_STATUS_PREPARING)); + } + return PrepareWorldInstanceResponse.newBuilder() + .setWorldInstance(worldState.get()) + .build(); + }); + when(worldManagementClient.getWorldInstanceLifecycle(anyLong(), anyLong())) + .thenAnswer( + invocation -> + GetWorldInstanceLifecycleResponse.newBuilder() + .setWorldInstance(worldState.get()) + .build()); + when(worldManagementClient.activatePreparedWorldInstance(anyLong(), anyLong(), anyLong())) + .thenAnswer( + invocation -> { + WorldInstanceLifecycleSnapshot active = + runOwnedWorldSnapshot( + request, + invocation.getArgument(1, Long.class), + invocation.getArgument(2, Long.class) + 1L, + WorldInstanceLifecycleStatus.WORLD_INSTANCE_LIFECYCLE_STATUS_ACTIVE); + worldState.set(active); + return net.firedevops.firemud.worldmanagement.v1.ActivatePreparedWorldInstanceResponse + .newBuilder() + .setWorldInstance(active) + .build(); + }); + return worldState; + } + + private static WorldInstanceLifecycleSnapshot runOwnedWorldSnapshot( + StartSessionRequest request, + long gameInstanceId, + long lifecycleEpoch, + WorldInstanceLifecycleStatus status) { + return WorldInstanceLifecycleSnapshot.newBuilder() + .setTenantId(Long.toString(request.tenantId())) + .setGameInstanceId(Long.toString(gameInstanceId)) + .setGameTemplateId(Long.toString(request.gameTemplateId())) + .setControlPlaneRequestId(request.controlPlaneRequestId()) + .setLaunchDescriptorId("ld-" + request.controlPlaneRequestId()) + .setVersionId("11") + .setReleaseBundleId("77") + .setGenerationConfigRevision("genrev-11") + .setPublishedReleaseBundleRef("prb:" + request.tenantId() + ":11:77") + .setVersionStateEpoch(77L) + .setLifecycleEpoch(lifecycleEpoch) + .setStatus(status) + .build(); + } + private GameInstance persistExisting( Long id, Long tenantId, @@ -1570,8 +1909,23 @@ private static GameInstance copyOf(GameInstance instance) { copy.setScriptPinEpoch(instance.getScriptPinEpoch()); copy.setScriptPatchPinnedControlPlaneRequestId( instance.getScriptPatchPinnedControlPlaneRequestId()); + copy.setScriptPatchBaseVersionId(instance.getScriptPatchBaseVersionId()); + copy.setGameTemplateId(instance.getGameTemplateId()); + copy.setLaunchDescriptorId(instance.getLaunchDescriptorId()); + copy.setVersionId(instance.getVersionId()); + copy.setReleaseBundleId(instance.getReleaseBundleId()); + copy.setVersionStateEpoch(instance.getVersionStateEpoch()); + copy.setGenerationConfigRevision(instance.getGenerationConfigRevision()); + copy.setRemapSetId(instance.getRemapSetId()); copy.setOwnerAccountId(instance.getOwnerAccountId()); copy.setStatus(instance.getStatus()); + copy.setRowVersion(instance.getRowVersion()); + copy.setRunOwnedStartRequestId(instance.getRunOwnedStartRequestId()); + copy.setRunOwnedStartRequestDigest(instance.getRunOwnedStartRequestDigest()); + copy.setRunOwnedStartPublishedReleaseBundleRef( + instance.getRunOwnedStartPublishedReleaseBundleRef()); + copy.setRunOwnedStartPreparingEpoch(instance.getRunOwnedStartPreparingEpoch()); + copy.setRunOwnedStartActiveEpoch(instance.getRunOwnedStartActiveEpoch()); return copy; } diff --git a/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/service/impl/GameSessionGrpcServiceTest.java b/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/service/impl/GameSessionGrpcServiceTest.java index ebe7a5b73a..82d24771a9 100644 --- a/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/service/impl/GameSessionGrpcServiceTest.java +++ b/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/service/impl/GameSessionGrpcServiceTest.java @@ -570,7 +570,7 @@ void listGameplayWorldsAllowsAnEmptyAuthorityStore() { } @Test - void listGameplayWorldsRejectsAnIncompleteAuthorityPointer() { + void listGameplayWorldsSuppressesTenantWithIncompleteAuthorityPointer() { GameplayAdmissionPointerAuthorityService pointerAuthorityService = Mockito.mock(GameplayAdmissionPointerAuthorityService.class); GameplayAdmissionPointerSnapshot incompleteSnapshot = @@ -604,7 +604,7 @@ void listGameplayWorldsRejectsAnIncompleteAuthorityPointer() { ListGameplayWorldsResponse response = listGameplayWorlds(service); - assertEquals("ADMISSION_POINTER_UNAVAILABLE", response.getError().getCode()); + assertFalse(response.hasError()); assertEquals(0, response.getWorldsCount()); Mockito.verify(pointerAuthorityService).listPointers(); } @@ -657,7 +657,7 @@ public void onCompleted() { } @Test - void gameplayDiscoveryRejectsPublicRealmsAcrossDifferentWorldsForOneTenant() { + void gameplayDiscoverySuppressesTenantWithPublicRealmsAcrossDifferentWorlds() { GameplayAdmissionPointerAuthorityService pointerAuthorityService = Mockito.mock(GameplayAdmissionPointerAuthorityService.class); Mockito.when(pointerAuthorityService.listPointers()) @@ -670,9 +670,9 @@ void gameplayDiscoveryRejectsPublicRealmsAcrossDifferentWorldsForOneTenant() { ListGameplayWorldsResponse worlds = listGameplayWorlds(service); ListGameplayRealmsResponse realms = listGameplayRealms(service, "alpha"); - assertEquals("ADMISSION_POINTER_UNAVAILABLE", worlds.getError().getCode()); + assertFalse(worlds.hasError()); assertEquals(0, worlds.getWorldsCount()); - assertEquals("ADMISSION_POINTER_UNAVAILABLE", realms.getError().getCode()); + assertEquals("INVALID_ARGUMENT", realms.getError().getCode()); assertEquals(0, realms.getRealmsCount()); Mockito.verify(pointerAuthorityService, Mockito.times(2)).listPointers(); } @@ -913,7 +913,7 @@ public void onCompleted() {} } @Test - void missingCatalogRevisionFailsClosedForCatalogAndAdmissionPointerReads() { + void missingCatalogRevisionIsSuppressedFromBrowseButPointerReadFailsClosed() { PingService pingService = Mockito.mock(PingService.class); GameInstanceService gameInstanceService = Mockito.mock(GameInstanceService.class); FeatureFlagService featureFlagService = Mockito.mock(FeatureFlagService.class); @@ -973,7 +973,7 @@ public void onError(Throwable t) { public void onCompleted() {} }); - assertEquals("ADMISSION_POINTER_UNAVAILABLE", realmsRef.get().getError().getCode()); + assertEquals("INVALID_ARGUMENT", realmsRef.get().getError().getCode()); assertEquals(0, realmsRef.get().getRealmsCount()); AtomicReference pointerRef = new AtomicReference<>(); @@ -1046,7 +1046,7 @@ public void onCompleted() {} } @Test - void missingStableRealmIdentityFailsClosedForCatalogReads() { + void missingStableRealmIdentityIsSuppressedFromBrowseButPointerReadFailsClosed() { GameplayAdmissionPointerAuthorityService pointerAuthorityService = Mockito.mock(GameplayAdmissionPointerAuthorityService.class); GameplayAdmissionPointerSnapshot missingIdentity = @@ -1098,7 +1098,7 @@ public void onError(Throwable t) { public void onCompleted() {} }); - assertEquals("ADMISSION_POINTER_UNAVAILABLE", response.get().getError().getCode()); + assertEquals("INVALID_ARGUMENT", response.get().getError().getCode()); assertEquals(0, response.get().getRealmsCount()); AtomicReference pointerResponse = new AtomicReference<>(); diff --git a/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/service/impl/InitialAdmissionBindOwnerReadTest.java b/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/service/impl/InitialAdmissionBindOwnerReadTest.java new file mode 100644 index 0000000000..546815a95e --- /dev/null +++ b/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/service/impl/InitialAdmissionBindOwnerReadTest.java @@ -0,0 +1,288 @@ +package net.firedevops.firemud.gamesession.service.impl; + +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.mockito.Mockito.mock; +import static org.mockito.Mockito.verify; +import static org.mockito.Mockito.verifyNoInteractions; +import static org.mockito.Mockito.when; + +import io.grpc.Context; +import io.grpc.stub.StreamObserver; +import io.micrometer.core.instrument.simple.SimpleMeterRegistry; +import java.util.List; +import java.util.Map; +import java.util.concurrent.atomic.AtomicReference; +import net.firedevops.firemud.common.grpc.GrpcPeerIdentity; +import net.firedevops.firemud.common.security.SessionContext; +import net.firedevops.firemud.entitymanagement.v1.PlayableStateScope; +import net.firedevops.firemud.gamesession.service.InitialAdmissionBindHoldBinding; +import net.firedevops.firemud.gamesession.service.InitialAdmissionBindOwnerProof; +import net.firedevops.firemud.gamesession.service.InitialAdmissionBindOwnerProofReader; +import net.firedevops.firemud.gamesession.v1.GetInitialAdmissionBindProofRequest; +import net.firedevops.firemud.gamesession.v1.GetInitialAdmissionBindProofResponse; +import net.firedevops.firemud.gamesession.v1.InitialAdmissionBindOwnerProofOutcome; +import org.junit.jupiter.api.AfterEach; +import org.junit.jupiter.api.Test; + +class InitialAdmissionBindOwnerReadTest { + private static final String NAMESPACE = "dev"; + private static final String HOLD_ID = "00000000-0000-0000-0000-000000000003"; + private static final String HOLD_FENCE = "00000000-0000-0000-0000-000000000004"; + private static final String REALM_UUID = "00000000-0000-0000-0000-000000000001"; + private static final String PLAYABLE_NAMESPACE_UUID = "00000000-0000-0000-0000-000000000002"; + private static final String REQUEST_ID = "initial-admission-1"; + private static final String REQUEST_DIGEST = "a".repeat(64); + + @AfterEach + void clearContext() { + SessionContext.clear(); + } + + @Test + void exactWorldManagementPeerReadsAndReceivesCompleteTypedOwnerProof() { + InitialAdmissionBindOwnerProofReader reader = mock(InitialAdmissionBindOwnerProofReader.class); + InitialAdmissionBindHoldBinding binding = binding(); + when(reader.read(binding)).thenReturn(committedProof()); + GameSessionControlPlaneGrpcService service = service(reader, NAMESPACE); + AtomicReference response = new AtomicReference<>(); + + runAsWorldManagement(() -> response.set(invoke(service, request()))); + + assertEquals("", response.get().getError().getCode()); + assertEquals( + InitialAdmissionBindOwnerProofOutcome.INITIAL_ADMISSION_BIND_OWNER_PROOF_OUTCOME_COMMITTED, + response.get().getOutcome()); + assertEquals(HOLD_ID, response.get().getHoldId()); + assertEquals(HOLD_FENCE, response.get().getHoldFence()); + assertEquals("42", response.get().getTenantId()); + assertEquals(REALM_UUID, response.get().getRealmUuid()); + assertEquals(PLAYABLE_NAMESPACE_UUID, response.get().getPlayableStateNamespaceUuid()); + assertEquals( + PlayableStateScope.PLAYABLE_STATE_SCOPE_SHARED, response.get().getPlayableStateScope()); + assertEquals("101", response.get().getGameInstanceId()); + assertEquals("11", response.get().getVersionId()); + assertEquals(7L, response.get().getActiveLifecycleEpoch()); + assertEquals(REQUEST_ID, response.get().getInitialAdmissionRequestId()); + assertEquals(REQUEST_DIGEST, response.get().getRequestDigest()); + assertEquals(true, response.get().getExpectedNoPriorPointer()); + assertEquals(1L, response.get().getExpectedCatalogRevision()); + assertEquals("gs-ledger-100", response.get().getOwnerProofId()); + assertEquals("audit-100", response.get().getPointerAuditId()); + assertEquals(1L, response.get().getPointerVersion()); + assertEquals(REQUEST_DIGEST, response.get().getPointerAuditRequestDigest()); + verify(reader).read(binding); + } + + @Test + void refusesToReturnPositiveProofWhenOwnerTupleDiffersFromRequestedHold() { + InitialAdmissionBindOwnerProofReader reader = mock(InitialAdmissionBindOwnerProofReader.class); + when(reader.read(binding())) + .thenReturn(withHoldId(committedProof(), "00000000-0000-0000-0000-000000000099")); + GameSessionControlPlaneGrpcService service = service(reader, NAMESPACE); + + AtomicReference response = new AtomicReference<>(); + runAsWorldManagement(() -> response.set(invoke(service, request()))); + + assertEquals("INTERNAL", response.get().getError().getCode()); + assertEquals(0, response.get().getOutcomeValue()); + assertEquals("", response.get().getOwnerProofId()); + verify(reader).read(binding()); + } + + @Test + void rejectsMissingWrongServiceWrongNamespaceAndEmptyConfiguredNamespace() { + InitialAdmissionBindOwnerProofReader reader = mock(InitialAdmissionBindOwnerProofReader.class); + GameSessionControlPlaneGrpcService service = service(reader, NAMESPACE); + + var noPeer = invoke(service, request()); + assertEquals("PERMISSION_DENIED", noPeer.getError().getCode()); + + AtomicReference wrongService = new AtomicReference<>(); + runAsPeer( + "entity-management-service", NAMESPACE, () -> wrongService.set(invoke(service, request()))); + assertEquals("PERMISSION_DENIED", wrongService.get().getError().getCode()); + + AtomicReference wrongNamespace = new AtomicReference<>(); + runAsPeer( + "world-management-service", "other", () -> wrongNamespace.set(invoke(service, request()))); + assertEquals("PERMISSION_DENIED", wrongNamespace.get().getError().getCode()); + + AtomicReference emptyConfiguration = + new AtomicReference<>(); + runAsPeer( + "world-management-service", + NAMESPACE, + () -> emptyConfiguration.set(invoke(service(reader, ""), request()))); + assertEquals("PERMISSION_DENIED", emptyConfiguration.get().getError().getCode()); + + verifyNoInteractions(reader); + } + + @Test + void headerOnlyCallerCannotReadOwnerProof() { + InitialAdmissionBindOwnerProofReader reader = mock(InitialAdmissionBindOwnerProofReader.class); + GameSessionControlPlaneGrpcService service = service(reader, NAMESPACE); + SessionContext.setContext(null, List.of(), Map.of(), true, "world-management-service", "wms-1"); + + var response = invoke(service, request()); + + assertEquals("PERMISSION_DENIED", response.getError().getCode()); + verifyNoInteractions(reader); + } + + @Test + void rejectsUnspecifiedAndUnrecognizedScopeBeforeOwnerRead() { + InitialAdmissionBindOwnerProofReader reader = mock(InitialAdmissionBindOwnerProofReader.class); + GameSessionControlPlaneGrpcService service = service(reader, NAMESPACE); + AtomicReference unspecified = new AtomicReference<>(); + runAsWorldManagement( + () -> + unspecified.set( + invoke( + service, + request().toBuilder() + .setPlayableStateScope(PlayableStateScope.PLAYABLE_STATE_SCOPE_UNSPECIFIED) + .build()))); + assertEquals("INVALID_ARGUMENT", unspecified.get().getError().getCode()); + + AtomicReference unrecognized = new AtomicReference<>(); + runAsWorldManagement( + () -> + unrecognized.set( + invoke(service, request().toBuilder().setPlayableStateScopeValue(999).build()))); + assertEquals("INVALID_ARGUMENT", unrecognized.get().getError().getCode()); + verifyNoInteractions(reader); + } + + private static InitialAdmissionBindOwnerProof committedProof() { + return new InitialAdmissionBindOwnerProof( + InitialAdmissionBindOwnerProof.Outcome.COMMITTED, + HOLD_ID, + HOLD_FENCE, + 42L, + REALM_UUID, + PLAYABLE_NAMESPACE_UUID, + "SHARED", + 101L, + 11L, + 7L, + REQUEST_ID, + REQUEST_DIGEST, + true, + 1L, + "gs-ledger-100", + "audit-100", + 1L, + REQUEST_DIGEST, + false); + } + + private static InitialAdmissionBindOwnerProof withHoldId( + InitialAdmissionBindOwnerProof proof, String holdId) { + return new InitialAdmissionBindOwnerProof( + proof.outcome(), + holdId, + proof.holdFence(), + proof.tenantId(), + proof.realmUuid(), + proof.playableStateNamespaceUuid(), + proof.playableStateScope(), + proof.gameInstanceId(), + proof.versionId(), + proof.activeLifecycleEpoch(), + proof.initialAdmissionRequestId(), + proof.requestDigest(), + proof.expectedNoPriorPointer(), + proof.expectedCatalogRevision(), + proof.ownerProofId(), + proof.pointerAuditId(), + proof.pointerVersion(), + proof.pointerAuditRequestDigest(), + proof.futureCommitPrevented()); + } + + private static InitialAdmissionBindHoldBinding binding() { + return new InitialAdmissionBindHoldBinding( + HOLD_ID, + HOLD_FENCE, + 42L, + REALM_UUID, + PLAYABLE_NAMESPACE_UUID, + "SHARED", + 101L, + 11L, + 7L, + REQUEST_ID, + REQUEST_DIGEST, + true, + 1L); + } + + private static GetInitialAdmissionBindProofRequest request() { + return GetInitialAdmissionBindProofRequest.newBuilder() + .setHoldId(HOLD_ID) + .setHoldFence(HOLD_FENCE) + .setTenantId("42") + .setRealmUuid(REALM_UUID) + .setPlayableStateNamespaceUuid(PLAYABLE_NAMESPACE_UUID) + .setPlayableStateScope(PlayableStateScope.PLAYABLE_STATE_SCOPE_SHARED) + .setGameInstanceId("101") + .setVersionId("11") + .setActiveLifecycleEpoch(7L) + .setInitialAdmissionRequestId(REQUEST_ID) + .setRequestDigest(REQUEST_DIGEST) + .setExpectedNoPriorPointer(true) + .setExpectedCatalogRevision(1L) + .build(); + } + + private static GameSessionControlPlaneGrpcService service( + InitialAdmissionBindOwnerProofReader reader, String trustedNamespace) { + GameSessionControlPlaneGrpcService service = + new GameSessionControlPlaneGrpcService( + mock(GameSessionCommandControlPlaneService.class), + mock(GameSessionRemoteControlPlaneService.class), + mock(GameSessionRuntimeControlPlaneReadService.class), + mock(GameSessionAdmissionPointerControlPlaneService.class), + mock(GameSessionOperatorControlPlaneService.class), + mock(GameSessionVersionUpgradeControlPlaneService.class), + new SimpleMeterRegistry()); + service.configureInitialAdmissionBindOwnerReadBoundary(reader, trustedNamespace); + return service; + } + + private static GetInitialAdmissionBindProofResponse invoke( + GameSessionControlPlaneGrpcService service, GetInitialAdmissionBindProofRequest request) { + AtomicReference response = new AtomicReference<>(); + service.getInitialAdmissionBindProof( + request, + new StreamObserver<>() { + @Override + public void onNext(GetInitialAdmissionBindProofResponse value) { + response.set(value); + } + + @Override + public void onError(Throwable throwable) { + throw new AssertionError("Owner proof RPC failed", throwable); + } + + @Override + public void onCompleted() {} + }); + return response.get(); + } + + private static void runAsWorldManagement(Runnable action) { + runAsPeer("world-management-service", NAMESPACE, action); + } + + private static void runAsPeer(String service, String namespace, Runnable action) { + Context.current() + .withValue( + GrpcPeerIdentity.CONTEXT_KEY, + new GrpcPeerIdentity( + "spiffe://firemud/ns/" + namespace + "/sa/" + service, namespace, service)) + .run(action); + } +} diff --git a/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/websocket/GameSessionWebSocketHandlerTest.java b/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/websocket/GameSessionWebSocketHandlerTest.java index d5f2dfb33c..2f00f84011 100644 --- a/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/websocket/GameSessionWebSocketHandlerTest.java +++ b/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/websocket/GameSessionWebSocketHandlerTest.java @@ -8,9 +8,11 @@ import static org.mockito.Mockito.verify; import static org.mockito.Mockito.when; +import java.nio.charset.StandardCharsets; import java.util.List; import java.util.Map; import java.util.Optional; +import java.util.UUID; import net.firedevops.firemud.cache.ScreenBufferService; import net.firedevops.firemud.common.runtime.RuntimeIdentity; import net.firedevops.firemud.gamesession.command.text.LookCommandHandler; @@ -139,7 +141,7 @@ void afterConnectionEstablishedRegistersValidFirstPartyConnectContext() { when(gameplayAdmissionPointerAuthorityService.listByRuntimeTarget(22L, 7L)) .thenReturn( List.of( - new GameplayAdmissionPointerSnapshot( + pointer( "demo", "Demo", "production", @@ -239,7 +241,7 @@ void afterConnectionEstablishedRepairsGenericBootstrapShellFromSingularRuntimeAu when(gameplayAdmissionPointerAuthorityService.listByRuntimeTarget(22L, 7L)) .thenReturn( List.of( - new GameplayAdmissionPointerSnapshot( + pointer( "demo", "Demo", "production", @@ -287,7 +289,7 @@ void afterConnectionEstablishedRepairsPartialRoutingTupleFromSingularRuntimeAuth when(gameplayAdmissionPointerAuthorityService.listByRuntimeTarget(22L, 7L)) .thenReturn( List.of( - new GameplayAdmissionPointerSnapshot( + pointer( "demo", "Demo", "production", @@ -327,7 +329,7 @@ void afterConnectionEstablishedDropsGenericBootstrapRoutingWhenRuntimeAuthorityI when(gameplayAdmissionPointerAuthorityService.listByRuntimeTarget(22L, 7L)) .thenReturn( List.of( - new GameplayAdmissionPointerSnapshot( + pointer( "demo", "Demo", "production", @@ -340,7 +342,7 @@ void afterConnectionEstablishedDropsGenericBootstrapRoutingWhenRuntimeAuthorityI false, "SHARED", "ALLOW_NEW"), - new GameplayAdmissionPointerSnapshot( + pointer( "demo", "Demo", "preview", @@ -390,7 +392,7 @@ void afterConnectionEstablishedDropsPartialRoutingTupleWhenRuntimeAuthorityIsAmb when(gameplayAdmissionPointerAuthorityService.listByRuntimeTarget(22L, 7L)) .thenReturn( List.of( - new GameplayAdmissionPointerSnapshot( + pointer( "demo", "Demo", "production", @@ -403,7 +405,7 @@ void afterConnectionEstablishedDropsPartialRoutingTupleWhenRuntimeAuthorityIsAmb false, "SHARED", "ALLOW_NEW"), - new GameplayAdmissionPointerSnapshot( + pointer( "demo", "Demo", "preview", @@ -447,7 +449,7 @@ void afterConnectionEstablishedDropsPartialRoutingTupleWhenRuntimeAuthorityIsAmb when(gameplayAdmissionPointerAuthorityService.listByRuntimeTarget(22L, 7L)) .thenReturn( List.of( - new GameplayAdmissionPointerSnapshot( + pointer( "demo", "Demo", "production", @@ -528,7 +530,7 @@ void afterConnectionEstablishedSkipsGenericBootstrapWhenBootstrapGameInstanceIsN when(gameplayAdmissionPointerAuthorityService.listByRuntimeTarget(22L, 7L)) .thenReturn( List.of( - new GameplayAdmissionPointerSnapshot( + pointer( "demo", "Demo", "production", @@ -622,7 +624,7 @@ void afterConnectionEstablishedClearsGenericBootstrapRoutingWhenRuntimeAuthority when(gameplayAdmissionPointerAuthorityService.listByRuntimeTarget(22L, 7L)) .thenReturn( List.of( - new GameplayAdmissionPointerSnapshot( + pointer( "demo", "Demo", "production", @@ -686,7 +688,7 @@ void afterConnectionEstablishedClearsGenericBootstrapRoutingWhenRuntimeAuthority when(gameplayAdmissionPointerAuthorityService.listByRuntimeTarget(22L, 7L)) .thenReturn( List.of( - new GameplayAdmissionPointerSnapshot( + pointer( "demo", "Demo", "production", @@ -699,7 +701,7 @@ void afterConnectionEstablishedClearsGenericBootstrapRoutingWhenRuntimeAuthority false, "SHARED", "ALLOW_NEW"), - new GameplayAdmissionPointerSnapshot( + pointer( "demo", "Demo", "preview", @@ -1160,7 +1162,7 @@ void handleMessageRepairsPartialGenericBootstrapRoutingFromSingularRuntimeAuthor when(gameplayAdmissionPointerAuthorityService.listByRuntimeTarget(22L, 7L)) .thenReturn( List.of( - new GameplayAdmissionPointerSnapshot( + pointer( "demo", "Demo", "production", @@ -1291,7 +1293,7 @@ void handleMessageClearsPartialGenericBootstrapRoutingWhenAuthorityIsAmbiguous() when(gameplayAdmissionPointerAuthorityService.listByRuntimeTarget(22L, 7L)) .thenReturn( List.of( - new GameplayAdmissionPointerSnapshot( + pointer( "demo", "Demo", "production", @@ -1304,7 +1306,7 @@ void handleMessageClearsPartialGenericBootstrapRoutingWhenAuthorityIsAmbiguous() false, "SHARED", "ALLOW_NEW"), - new GameplayAdmissionPointerSnapshot( + pointer( "demo", "Demo", "preview", @@ -1346,4 +1348,43 @@ void handleMessageClearsPartialGenericBootstrapRoutingWhenAuthorityIsAmbiguous() && context.realmSlug() == null && context.pointerVersion() == 0L)); } + + private static GameplayAdmissionPointerSnapshot pointer( + String worldSlug, + String worldDisplayName, + String realmSlug, + String realmDisplayName, + long tenantId, + long gameInstanceId, + long pointerVersion, + boolean visible, + boolean publicProductionRealm, + boolean requiresCharacterSelection, + String stateScope, + String characterCreationPolicy) { + String namespaceIdentity = + "SHARED".equals(stateScope) + ? "shared-namespace:" + tenantId + : "isolated-namespace:" + tenantId + ":" + worldSlug + ":" + realmSlug; + return new GameplayAdmissionPointerSnapshot( + worldSlug, + worldDisplayName, + realmSlug, + realmDisplayName, + tenantId, + gameInstanceId, + pointerVersion, + visible, + publicProductionRealm, + requiresCharacterSelection, + stateScope, + characterCreationPolicy, + 1L, + stableUuid("realm:" + tenantId + ":" + worldSlug + ":" + realmSlug), + stableUuid(namespaceIdentity)); + } + + private static UUID stableUuid(String value) { + return UUID.nameUUIDFromBytes(value.getBytes(StandardCharsets.UTF_8)); + } } diff --git a/services/game-session-service/src/testFixtures/java/net/firedevops/firemud/gamesession/CrossServiceAppHarness.java b/services/game-session-service/src/testFixtures/java/net/firedevops/firemud/gamesession/CrossServiceAppHarness.java index 050c62a4e0..d2fc5c62ff 100644 --- a/services/game-session-service/src/testFixtures/java/net/firedevops/firemud/gamesession/CrossServiceAppHarness.java +++ b/services/game-session-service/src/testFixtures/java/net/firedevops/firemud/gamesession/CrossServiceAppHarness.java @@ -24,6 +24,8 @@ import net.firedevops.firemud.gamesession.dto.GameInstanceDto; import net.firedevops.firemud.gamesession.dto.StartSessionRequest; import net.firedevops.firemud.gamesession.service.GameInstanceService; +import net.firedevops.firemud.gamesession.service.RunOwnedInitialLaunchResult; +import org.springframework.beans.factory.annotation.Qualifier; import org.springframework.boot.builder.SpringApplicationBuilder; import org.springframework.boot.test.context.TestConfiguration; import org.springframework.boot.web.server.context.WebServerApplicationContext; @@ -317,9 +319,10 @@ public void clear(long tenantId, long gameInstanceId, long characterId) { }; } - @Bean(name = "gameInstanceServiceImpl") + @Bean(name = "crossServiceTestGameInstanceService") @Primary - GameInstanceService gameInstanceService() { + GameInstanceService gameInstanceService( + @Qualifier("gameInstanceServiceImpl") GameInstanceService actualGameInstanceService) { return new GameInstanceService() { @Override public GameInstanceDto startSession( @@ -350,6 +353,11 @@ public GameInstanceDto restartSession(long sessionId) { return new GameInstanceDto( sessionId, 0L, "stub", null, null, null, null, null, null, null, 0L, "RUNNING"); } + + @Override + public RunOwnedInitialLaunchResult startRunOwnedInitialLaunch(StartSessionRequest request) { + return actualGameInstanceService.startRunOwnedInitialLaunch(request); + } }; } } diff --git a/services/world-management-service/src/main/java/net/firedevops/firemud/worldmanagement/client/GrpcGameSessionInitialAdmissionBindProofClient.java b/services/world-management-service/src/main/java/net/firedevops/firemud/worldmanagement/client/GrpcGameSessionInitialAdmissionBindProofClient.java new file mode 100644 index 0000000000..c344930c2c --- /dev/null +++ b/services/world-management-service/src/main/java/net/firedevops/firemud/worldmanagement/client/GrpcGameSessionInitialAdmissionBindProofClient.java @@ -0,0 +1,163 @@ +package net.firedevops.firemud.worldmanagement.client; + +import jakarta.annotation.PostConstruct; +import java.io.IOException; +import java.util.concurrent.TimeUnit; +import javax.net.ssl.SSLException; +import net.firedevops.firemud.common.config.ServiceEndpointsProperties; +import net.firedevops.firemud.common.grpc.AbstractReloadingBlockingGrpcClient; +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.entitymanagement.v1.PlayableStateScope; +import net.firedevops.firemud.gamesession.v1.GameSessionControlPlaneServiceGrpc; +import net.firedevops.firemud.gamesession.v1.GetInitialAdmissionBindProofRequest; +import net.firedevops.firemud.gamesession.v1.GetInitialAdmissionBindProofResponse; +import net.firedevops.firemud.gamesession.v1.InitialAdmissionBindOwnerProofOutcome; +import net.firedevops.firemud.worldmanagement.dto.InitialAdmissionBindOwnerProof; +import net.firedevops.firemud.worldmanagement.dto.InitialAdmissionBindOwnerProof.Outcome; +import net.firedevops.firemud.worldmanagement.entity.InitialAdmissionBindHold; +import org.springframework.stereotype.Component; + +/** Authenticated gRPC readback from the Game Session owner ledger. */ +@Component +public class GrpcGameSessionInitialAdmissionBindProofClient + extends AbstractReloadingBlockingGrpcClient< + GameSessionControlPlaneServiceGrpc.GameSessionControlPlaneServiceBlockingStub> + implements GameSessionInitialAdmissionBindProofClient { + private static final long CALL_DEADLINE_SECONDS = 5L; + + public GrpcGameSessionInitialAdmissionBindProofClient( + ServiceEndpointsProperties endpoints, + CommonGrpcClientProperties tlsProps, + GrpcChannelFactory channelFactory, + BlockingGrpcStubCustomizer stubCustomizer) { + super( + endpoints, + tlsProps, + channelFactory, + stubCustomizer, + GrpcGameSessionInitialAdmissionBindProofClient.class); + } + + @PostConstruct + void init() throws SSLException, IOException { + initReloadingClient(); + } + + @Override + protected String configuredTarget(ServiceEndpointsProperties endpoints) { + return endpoints.getGameSessionService(); + } + + @Override + protected String defaultTarget() { + return "game-session-service:6565"; + } + + @Override + protected GameSessionControlPlaneServiceGrpc.GameSessionControlPlaneServiceBlockingStub buildStub( + io.grpc.ManagedChannel channel) { + return applyStubCustomizer( + GameSessionControlPlaneServiceGrpc.newBlockingStub(channel).withCompression("gzip")); + } + + @Override + public InitialAdmissionBindOwnerProof readOwnerProof(InitialAdmissionBindHold hold) { + if (hold == null) { + throw new IllegalArgumentException("initial admission hold is required"); + } + GetInitialAdmissionBindProofResponse response = + stub() + .withDeadlineAfter(CALL_DEADLINE_SECONDS, TimeUnit.SECONDS) + .getInitialAdmissionBindProof(toRequest(hold)); + if (response.hasError()) { + throw new IllegalStateException( + "Game Session initial admission owner read failed: " + response.getError().getCode()); + } + return new InitialAdmissionBindOwnerProof( + fromWireOutcome(response.getOutcome()), + response.getHoldId(), + response.getHoldFence(), + parsePositive(response.getTenantId(), "tenant_id"), + response.getRealmUuid(), + response.getPlayableStateNamespaceUuid(), + fromWireScope(response.getPlayableStateScope()), + parsePositive(response.getGameInstanceId(), "game_instance_id"), + parsePositive(response.getVersionId(), "version_id"), + response.getActiveLifecycleEpoch(), + response.getInitialAdmissionRequestId(), + response.getRequestDigest(), + response.getExpectedNoPriorPointer(), + response.getExpectedCatalogRevision(), + nullIfBlank(response.getOwnerProofId()), + nullIfBlank(response.getPointerAuditId()), + response.getPointerVersion(), + nullIfBlank(response.getPointerAuditRequestDigest()), + response.getFutureCommitPrevented()); + } + + private GetInitialAdmissionBindProofRequest toRequest(InitialAdmissionBindHold hold) { + return GetInitialAdmissionBindProofRequest.newBuilder() + .setHoldId(hold.holdId()) + .setHoldFence(hold.holdFence()) + .setTenantId(Long.toString(hold.tenantId())) + .setRealmUuid(hold.realmUuid()) + .setPlayableStateNamespaceUuid(hold.playableStateNamespaceUuid()) + .setPlayableStateScope(toWireScope(hold.playableStateScope())) + .setGameInstanceId(Long.toString(hold.gameInstanceId())) + .setVersionId(Long.toString(hold.versionId())) + .setActiveLifecycleEpoch(hold.activeLifecycleEpoch()) + .setInitialAdmissionRequestId(hold.initialAdmissionRequestId()) + .setRequestDigest(hold.requestDigest()) + .setExpectedNoPriorPointer(hold.expectedNoPriorPointer()) + .setExpectedCatalogRevision(hold.expectedCatalogRevision()) + .build(); + } + + private PlayableStateScope toWireScope(String scope) { + return switch (scope) { + case "SHARED" -> PlayableStateScope.PLAYABLE_STATE_SCOPE_SHARED; + case "ISOLATED" -> PlayableStateScope.PLAYABLE_STATE_SCOPE_ISOLATED; + default -> throw new IllegalArgumentException("Unsupported playable state scope"); + }; + } + + private String fromWireScope(PlayableStateScope scope) { + return switch (scope) { + case PLAYABLE_STATE_SCOPE_SHARED -> "SHARED"; + case PLAYABLE_STATE_SCOPE_ISOLATED -> "ISOLATED"; + case PLAYABLE_STATE_SCOPE_UNSPECIFIED, UNRECOGNIZED -> null; + }; + } + + private Outcome fromWireOutcome(InitialAdmissionBindOwnerProofOutcome outcome) { + return switch (outcome) { + case INITIAL_ADMISSION_BIND_OWNER_PROOF_OUTCOME_COMMITTED -> Outcome.COMMITTED; + case INITIAL_ADMISSION_BIND_OWNER_PROOF_OUTCOME_ABORTED -> Outcome.ABORTED; + case INITIAL_ADMISSION_BIND_OWNER_PROOF_OUTCOME_NOT_FOUND -> Outcome.NOT_FOUND; + case INITIAL_ADMISSION_BIND_OWNER_PROOF_OUTCOME_PENDING -> Outcome.PENDING; + case INITIAL_ADMISSION_BIND_OWNER_PROOF_OUTCOME_UNAVAILABLE -> Outcome.UNAVAILABLE; + case INITIAL_ADMISSION_BIND_OWNER_PROOF_OUTCOME_UNSPECIFIED, + INITIAL_ADMISSION_BIND_OWNER_PROOF_OUTCOME_ERROR, + UNRECOGNIZED -> + Outcome.ERROR; + }; + } + + private long parsePositive(String value, String fieldName) { + try { + long parsed = Long.parseLong(value); + if (parsed <= 0L) { + throw new IllegalArgumentException(fieldName + " must be positive"); + } + return parsed; + } catch (NumberFormatException exception) { + throw new IllegalArgumentException(fieldName + " must be a positive number", exception); + } + } + + private String nullIfBlank(String value) { + return value == null || value.isBlank() ? null : value; + } +} diff --git a/services/world-management-service/src/main/java/net/firedevops/firemud/worldmanagement/data/TestDataSeeder.java b/services/world-management-service/src/main/java/net/firedevops/firemud/worldmanagement/data/TestDataSeeder.java index edc744ece8..3a6c802b90 100644 --- a/services/world-management-service/src/main/java/net/firedevops/firemud/worldmanagement/data/TestDataSeeder.java +++ b/services/world-management-service/src/main/java/net/firedevops/firemud/worldmanagement/data/TestDataSeeder.java @@ -1,30 +1,13 @@ package net.firedevops.firemud.worldmanagement.data; -import edu.umd.cs.findbugs.annotations.SuppressFBWarnings; -import java.time.Instant; -import java.util.HashMap; -import java.util.LinkedHashMap; -import java.util.List; -import java.util.Map; import lombok.RequiredArgsConstructor; -import net.firedevops.firemud.worldmanagement.config.SmokeDemoRuntimeSeedProperties; import net.firedevops.firemud.worldmanagement.entity.Region; -import net.firedevops.firemud.worldmanagement.entity.RegionInstance; import net.firedevops.firemud.worldmanagement.entity.Room; import net.firedevops.firemud.worldmanagement.entity.RoomExit; -import net.firedevops.firemud.worldmanagement.entity.RoomInstance; -import net.firedevops.firemud.worldmanagement.entity.RoomInstanceExit; -import net.firedevops.firemud.worldmanagement.entity.WorldInstance; import net.firedevops.firemud.worldmanagement.entity.Zone; -import net.firedevops.firemud.worldmanagement.entity.ZoneInstance; -import net.firedevops.firemud.worldmanagement.repository.RegionInstanceRepository; import net.firedevops.firemud.worldmanagement.repository.RegionRepository; import net.firedevops.firemud.worldmanagement.repository.RoomExitRepository; -import net.firedevops.firemud.worldmanagement.repository.RoomInstanceExitRepository; -import net.firedevops.firemud.worldmanagement.repository.RoomInstanceRepository; import net.firedevops.firemud.worldmanagement.repository.RoomRepository; -import net.firedevops.firemud.worldmanagement.repository.WorldInstanceRepository; -import net.firedevops.firemud.worldmanagement.repository.ZoneInstanceRepository; import net.firedevops.firemud.worldmanagement.repository.ZoneRepository; import org.springframework.boot.ApplicationArguments; import org.springframework.boot.ApplicationRunner; @@ -32,7 +15,7 @@ import org.springframework.stereotype.Component; import org.springframework.transaction.annotation.Transactional; -/** Seeds deterministic world/runtime fixtures when local compose explicitly enables them. */ +/** Seeds deterministic versioned world fixtures when local compose explicitly enables them. */ @Component @ConditionalOnProperty( prefix = "firemud.smoke.seed-demo-runtime", @@ -40,19 +23,16 @@ havingValue = "true", matchIfMissing = false) @RequiredArgsConstructor -@SuppressFBWarnings( - value = "EI_EXPOSE_REP2", - justification = "Repositories are injected for seeding and not exposed") public class TestDataSeeder implements ApplicationRunner { private static final long DEMO_TENANT_ID = 1L; private static final long DEMO_VERSION_ID = 1L; - private static final long STARTER_ROOM_INSTANCE_ROW_ID = 1021L; - private static final long SECONDARY_ROOM_INSTANCE_ROW_ID = 2045L; private static final String DEMO_REGION_NAME = "Demo Region"; private static final String DEMO_ZONE_NAME = "Demo Zone"; + private static final long STARTER_ROOM_ID = 1021L; private static final String STARTER_ROOM_NAME = "Candle-lit Antechamber"; private static final String STARTER_ROOM_DESCRIPTION = "Stalactites drip along the northern wall while a faint draft carries the smell of damp earth from the lower tunnels. Torches flicker in alcoves, casting motion into the shadowy archway to the north."; + private static final long SECONDARY_ROOM_ID = 2045L; private static final String SECONDARY_ROOM_NAME = "Smith's Annex"; private static final String SECONDARY_ROOM_DESCRIPTION = "An anvil, banked coals, and orderly tool racks mark this alcove as a working annex off the starter chamber."; @@ -61,25 +41,20 @@ public class TestDataSeeder implements ApplicationRunner { private final ZoneRepository zoneRepository; private final RoomRepository roomRepository; private final RoomExitRepository roomExitRepository; - private final WorldInstanceRepository worldInstanceRepository; - private final RegionInstanceRepository regionInstanceRepository; - private final ZoneInstanceRepository zoneInstanceRepository; - private final RoomInstanceRepository roomInstanceRepository; - private final RoomInstanceExitRepository roomInstanceExitRepository; - private final SmokeDemoRuntimeSeedProperties smokeDemoRuntimeSeedProperties; @Override @Transactional public void run(ApplicationArguments args) { ensureDemoTopology(); - ensureRuntimeTopologyForSeedTargets(); } private void ensureDemoTopology() { Region region = ensureDemoRegion(); Zone zone = ensureDemoZone(region); - Room starterRoom = ensureRoom(zone, STARTER_ROOM_NAME, STARTER_ROOM_DESCRIPTION); - Room secondaryRoom = ensureRoom(zone, SECONDARY_ROOM_NAME, SECONDARY_ROOM_DESCRIPTION); + Room starterRoom = + ensureRoom(zone, STARTER_ROOM_ID, STARTER_ROOM_NAME, STARTER_ROOM_DESCRIPTION); + Room secondaryRoom = + ensureRoom(zone, SECONDARY_ROOM_ID, SECONDARY_ROOM_NAME, SECONDARY_ROOM_DESCRIPTION); ensureRoomExit(starterRoom, secondaryRoom, "NORTH"); ensureRoomExit(secondaryRoom, starterRoom, "SOUTH"); } @@ -116,12 +91,25 @@ private Zone ensureDemoZone(Region region) { return zoneRepository.save(zone); } - private Room ensureRoom(Zone zone, String name, String description) { + private Room ensureRoom(Zone zone, long roomId, String name, String description) { Room room = roomRepository .findFirstByTenantIdAndVersionIdAndZoneIdAndName( DEMO_TENANT_ID, DEMO_VERSION_ID, zone.getId(), name) - .orElseGet(Room::new); + .orElse(null); + if (room != null && !Long.valueOf(roomId).equals(room.getId())) { + throw new IllegalStateException( + "DEMO_TEMPLATE_ROOM_ID_MISMATCH: " + + name + + " is persisted with room id " + + room.getId() + + " instead of " + + roomId); + } + if (room == null) { + room = new Room(); + room.setId(roomId); + } room.setTenantId(DEMO_TENANT_ID); room.setVersionId(DEMO_VERSION_ID); room.setZone(zone); @@ -129,7 +117,7 @@ private Room ensureRoom(Zone zone, String name, String description) { room.setDescription(description); room.setNameLocalizedVariantsJson(null); room.setDescriptionLocalizedVariantsJson(null); - return roomRepository.save(room); + return roomRepository.saveSeededWithExplicitId(room); } private void ensureRoomExit(Room fromRoom, Room toRoom, String direction) { @@ -146,213 +134,4 @@ private void ensureRoomExit(Room fromRoom, Room toRoom, String direction) { exit.setCost(1); roomExitRepository.save(exit); } - - private void ensureRuntimeTopologyForSeedTargets() { - List targets = - smokeDemoRuntimeSeedProperties.getTargets(); - if (targets == null) { - return; - } - for (SmokeDemoRuntimeSeedProperties.RuntimeTargetSeed target : targets) { - if (target == null || target.getTenantId() <= 0L || target.getGameInstanceId() <= 0L) { - continue; - } - ensureRuntimeTopology(target.getTenantId(), target.getGameInstanceId()); - } - } - - private void ensureRuntimeTopology(long tenantId, long gameInstanceId) { - WorldInstance savedWorldInstance = ensureWorldInstance(tenantId, gameInstanceId); - RegionInstance savedRegionInstance = - ensureRegionInstance(tenantId, gameInstanceId, savedWorldInstance); - - Map zoneInstancesByTemplateId = new LinkedHashMap<>(); - for (Zone templateZone : - zoneRepository.findByTenantIdAndVersionIdOrderByIdAsc(DEMO_TENANT_ID, DEMO_VERSION_ID)) { - ZoneInstance savedZoneInstance = - ensureZoneInstance(tenantId, gameInstanceId, savedRegionInstance, templateZone); - zoneInstancesByTemplateId.put(templateZone.getId(), savedZoneInstance); - } - - List templateRooms = - roomRepository.findByTenantIdAndVersionIdOrderByIdAsc(DEMO_TENANT_ID, DEMO_VERSION_ID); - Map roomInstancesByRoomInstanceRowId = new HashMap<>(); - for (RoomInstance existingRoomInstance : - roomInstanceRepository.findByTenantIdAndGameInstanceIdOrderByRoomInstanceRowIdAsc( - tenantId, gameInstanceId)) { - roomInstancesByRoomInstanceRowId.put( - existingRoomInstance.getRoomInstanceRowId(), existingRoomInstance); - } - Map roomInstancesByTemplateId = new LinkedHashMap<>(); - for (int index = 0; index < templateRooms.size(); index++) { - Room templateRoom = templateRooms.get(index); - ZoneInstance zoneInstance = zoneInstancesByTemplateId.get(templateRoom.getZone().getId()); - if (zoneInstance == null) { - continue; - } - RoomInstance savedRoomInstance = - ensureRoomInstance( - tenantId, - gameInstanceId, - savedRegionInstance, - zoneInstance, - templateRoom, - roomInstanceRowIdForTemplateOrder(index), - roomInstancesByRoomInstanceRowId); - roomInstancesByTemplateId.put(templateRoom.getId(), savedRoomInstance); - } - - Map> exitsByFromRoomInstanceRecordId = new HashMap<>(); - for (RoomExit templateExit : - roomExitRepository.findByTenantIdAndVersionIdOrderByIdAsc( - DEMO_TENANT_ID, DEMO_VERSION_ID)) { - RoomInstance fromRoomInstance = - roomInstancesByTemplateId.get(templateExit.getFromRoom().getId()); - RoomInstance toRoomInstance = roomInstancesByTemplateId.get(templateExit.getToRoom().getId()); - if (fromRoomInstance == null || toRoomInstance == null) { - continue; - } - ensureRoomInstanceExit( - tenantId, - gameInstanceId, - fromRoomInstance, - toRoomInstance, - templateExit, - exitsByFromRoomInstanceRecordId); - } - } - - private WorldInstance ensureWorldInstance(long tenantId, long gameInstanceId) { - WorldInstance worldInstance = - worldInstanceRepository - .findByTenantIdAndGameInstanceId(tenantId, gameInstanceId) - .orElseGet(WorldInstance::new); - if (worldInstance.getCreatedAt() == null) { - worldInstance.setCreatedAt(Instant.now()); - } - worldInstance.setTenantId(tenantId); - worldInstance.setGameInstanceId(gameInstanceId); - worldInstance.setGameTemplateId(1L); - worldInstance.setControlPlaneRequestId("dev-bootstrap:" + gameInstanceId); - worldInstance.setLaunchDescriptorId("ld-dev-bootstrap-" + gameInstanceId); - worldInstance.setVersionId(1L); - worldInstance.setScriptPatchVersion(null); - worldInstance.setRuntimeFlagsJson("{}"); - worldInstance.setGenerationConfigRevision("dev-bootstrap"); - worldInstance.setReleaseBundleId(1L); - worldInstance.setPublishedReleaseBundleRef("prb:dev:" + tenantId + ":1:1"); - worldInstance.setVersionStateEpoch(1L); - worldInstance.setLifecycleEpoch(2L); - worldInstance.setStatus("ACTIVE"); - worldInstance.setUpdatedAt(Instant.now()); - if (worldInstance.getRowVersion() == null) { - worldInstance.setRowVersion(0L); - } - return worldInstanceRepository.save(worldInstance); - } - - private RegionInstance ensureRegionInstance( - long tenantId, long gameInstanceId, WorldInstance savedWorldInstance) { - RegionInstance regionInstance = - regionInstanceRepository.findByTenantIdAndGameInstanceId(tenantId, gameInstanceId).stream() - .findFirst() - .orElseGet(RegionInstance::new); - regionInstance.setTenantId(tenantId); - regionInstance.setGameInstanceId(gameInstanceId); - regionInstance.setWorldInstance(savedWorldInstance); - regionInstance.setShardId(0); - regionInstance.setName("Starter Region"); - regionInstance.setGenerationSeed(gameInstanceId); - regionInstance.setGeneratorType("SimpleDungeonGenerator"); - regionInstance.setGeneratorParams("{}"); - regionInstance.setSpacingMultiplier(1.0); - return regionInstanceRepository.save(regionInstance); - } - - private ZoneInstance ensureZoneInstance( - long tenantId, long gameInstanceId, RegionInstance savedRegionInstance, Zone templateZone) { - ZoneInstance zoneInstance = - zoneInstanceRepository - .findByTenantIdAndGameInstanceIdAndZoneInstanceId( - tenantId, gameInstanceId, templateZone.getId()) - .orElseGet(ZoneInstance::new); - zoneInstance.setTenantId(tenantId); - zoneInstance.setGameInstanceId(gameInstanceId); - zoneInstance.setZoneInstanceId(templateZone.getId()); - zoneInstance.setTemplateZoneId(templateZone.getId()); - zoneInstance.setRegionInstance(savedRegionInstance); - zoneInstance.setName(templateZone.getName()); - return zoneInstanceRepository.save(zoneInstance); - } - - private RoomInstance ensureRoomInstance( - long tenantId, - long gameInstanceId, - RegionInstance savedRegionInstance, - ZoneInstance zoneInstance, - Room templateRoom, - long roomInstanceRowId, - Map roomInstancesByRoomInstanceRowId) { - RoomInstance roomInstance = - roomInstancesByRoomInstanceRowId.getOrDefault(roomInstanceRowId, new RoomInstance()); - roomInstance.setTenantId(tenantId); - roomInstance.setGameInstanceId(gameInstanceId); - roomInstance.setRoomInstanceRowId(roomInstanceRowId); - roomInstance.setTemplateRoomId(templateRoom.getId()); - roomInstance.setRegionInstance(savedRegionInstance); - roomInstance.setZoneInstance(zoneInstance); - roomInstance.setName(templateRoom.getName()); - roomInstance.setDescription(templateRoom.getDescription()); - roomInstance.setNameLocalizedVariantsJson(templateRoom.getNameLocalizedVariantsJson()); - roomInstance.setDescriptionLocalizedVariantsJson( - templateRoom.getDescriptionLocalizedVariantsJson()); - RoomInstance savedRoomInstance = roomInstanceRepository.save(roomInstance); - roomInstancesByRoomInstanceRowId.put(roomInstanceRowId, savedRoomInstance); - return savedRoomInstance; - } - - private void ensureRoomInstanceExit( - long tenantId, - long gameInstanceId, - RoomInstance fromRoomInstance, - RoomInstance toRoomInstance, - RoomExit templateExit, - Map> exitsByFromRoomInstanceRecordId) { - List existingExits = - exitsByFromRoomInstanceRecordId.computeIfAbsent( - fromRoomInstance.getId(), - ignored -> - roomInstanceExitRepository - .findByTenantIdAndGameInstanceIdAndFromRoomInstanceRecordId( - tenantId, gameInstanceId, fromRoomInstance.getId())); - RoomInstanceExit roomInstanceExit = - existingExits.stream() - .filter( - existingExit -> - templateExit.getDirection().equals(existingExit.getDirection()) - && existingExit.getToRoomInstance() != null - && toRoomInstance.getId().equals(existingExit.getToRoomInstance().getId())) - .findFirst() - .orElseGet(RoomInstanceExit::new); - roomInstanceExit.setTenantId(tenantId); - roomInstanceExit.setGameInstanceId(gameInstanceId); - roomInstanceExit.setFromRoomInstance(fromRoomInstance); - roomInstanceExit.setToRoomInstance(toRoomInstance); - roomInstanceExit.setDirection(templateExit.getDirection()); - roomInstanceExit.setCost(templateExit.getCost()); - RoomInstanceExit savedRoomInstanceExit = roomInstanceExitRepository.save(roomInstanceExit); - if (roomInstanceExit.getId() == null) { - existingExits.add(savedRoomInstanceExit); - } - } - - private long roomInstanceRowIdForTemplateOrder(int index) { - if (index == 0) { - return STARTER_ROOM_INSTANCE_ROW_ID; - } - if (index == 1) { - return SECONDARY_ROOM_INSTANCE_ROW_ID; - } - return SECONDARY_ROOM_INSTANCE_ROW_ID + index; - } } diff --git a/services/world-management-service/src/main/java/net/firedevops/firemud/worldmanagement/dto/InitialAdmissionBindOwnerProof.java b/services/world-management-service/src/main/java/net/firedevops/firemud/worldmanagement/dto/InitialAdmissionBindOwnerProof.java index c151c3a353..399496dcb5 100644 --- a/services/world-management-service/src/main/java/net/firedevops/firemud/worldmanagement/dto/InitialAdmissionBindOwnerProof.java +++ b/services/world-management-service/src/main/java/net/firedevops/firemud/worldmanagement/dto/InitialAdmissionBindOwnerProof.java @@ -20,7 +20,6 @@ public record InitialAdmissionBindOwnerProof( String pointerAuditId, long pointerVersion, String pointerAuditRequestDigest, - boolean priorPointerStillAbsent, boolean futureCommitPrevented) { public enum Outcome { COMMITTED, diff --git a/services/world-management-service/src/main/java/net/firedevops/firemud/worldmanagement/repository/InitialAdmissionBindHoldRepository.java b/services/world-management-service/src/main/java/net/firedevops/firemud/worldmanagement/repository/InitialAdmissionBindHoldRepository.java index dbc72b6fb9..090ea9e579 100644 --- a/services/world-management-service/src/main/java/net/firedevops/firemud/worldmanagement/repository/InitialAdmissionBindHoldRepository.java +++ b/services/world-management-service/src/main/java/net/firedevops/firemud/worldmanagement/repository/InitialAdmissionBindHoldRepository.java @@ -64,17 +64,6 @@ public List findNonterminal(int limit) { return rows.map(this::toEntity); } - public boolean hasNonterminalForGameInstance(long tenantId, long gameInstanceId) { - return Boolean.TRUE.equals( - dsl.fetchValue( - "SELECT EXISTS (SELECT 1 FROM initial_admission_bind_hold " - + "WHERE tenant_id = ? AND game_instance_id = ? " - + "AND status IN ('PENDING', 'RECONCILIATION_REQUIRED'))", - Boolean.class, - tenantId, - gameInstanceId)); - } - public boolean hasNonterminalForRealm(long tenantId, String realmUuid) { return Boolean.TRUE.equals( dsl.fetchValue( @@ -120,33 +109,34 @@ public Optional insertIfNoUniqueConflict( public Optional markReconciliationRequired( InitialAdmissionBindHold hold, String errorCode, Instant now) { - dsl.execute( - "UPDATE initial_admission_bind_hold SET status = 'RECONCILIATION_REQUIRED', " - + "reconciliation_error = ?, updated_at = ?, row_version = row_version + 1 " - + "WHERE hold_id = ?::uuid AND hold_fence = ?::uuid AND tenant_id = ? " - + "AND realm_uuid = ?::uuid AND playable_state_namespace_uuid = ?::uuid " - + "AND playable_state_scope = ? AND game_instance_id = ? AND version_id = ? " - + "AND active_lifecycle_epoch = ? AND initial_admission_request_id = ? " - + "AND request_digest = ? AND expected_no_prior_pointer = ? " - + "AND expected_catalog_revision = ? AND row_version = ? " - + "AND status IN ('PENDING', 'RECONCILIATION_REQUIRED')", - errorCode, - toLocalDateTime(now), - UUID.fromString(hold.holdId()), - UUID.fromString(hold.holdFence()), - hold.tenantId(), - UUID.fromString(hold.realmUuid()), - UUID.fromString(hold.playableStateNamespaceUuid()), - hold.playableStateScope(), - hold.gameInstanceId(), - hold.versionId(), - hold.activeLifecycleEpoch(), - hold.initialAdmissionRequestId(), - hold.requestDigest(), - hold.expectedNoPriorPointer(), - hold.expectedCatalogRevision(), - hold.rowVersion()); - return findByHoldIdForUpdate(hold.holdId()); + int updated = + dsl.execute( + "UPDATE initial_admission_bind_hold SET status = 'RECONCILIATION_REQUIRED', " + + "reconciliation_error = ?, updated_at = ?, row_version = row_version + 1 " + + "WHERE hold_id = ?::uuid AND hold_fence = ?::uuid AND tenant_id = ? " + + "AND realm_uuid = ?::uuid AND playable_state_namespace_uuid = ?::uuid " + + "AND playable_state_scope = ? AND game_instance_id = ? AND version_id = ? " + + "AND active_lifecycle_epoch = ? AND initial_admission_request_id = ? " + + "AND request_digest = ? AND expected_no_prior_pointer = ? " + + "AND expected_catalog_revision = ? AND row_version = ? " + + "AND status IN ('PENDING', 'RECONCILIATION_REQUIRED')", + errorCode, + toLocalDateTime(now), + UUID.fromString(hold.holdId()), + UUID.fromString(hold.holdFence()), + hold.tenantId(), + UUID.fromString(hold.realmUuid()), + UUID.fromString(hold.playableStateNamespaceUuid()), + hold.playableStateScope(), + hold.gameInstanceId(), + hold.versionId(), + hold.activeLifecycleEpoch(), + hold.initialAdmissionRequestId(), + hold.requestDigest(), + hold.expectedNoPriorPointer(), + hold.expectedCatalogRevision(), + hold.rowVersion()); + return updated == 1 ? findByHoldIdForUpdate(hold.holdId()) : Optional.empty(); } public Optional recordTerminalProof( diff --git a/services/world-management-service/src/main/java/net/firedevops/firemud/worldmanagement/repository/RoomRepository.java b/services/world-management-service/src/main/java/net/firedevops/firemud/worldmanagement/repository/RoomRepository.java index ba89b5a531..cb91c3f047 100644 --- a/services/world-management-service/src/main/java/net/firedevops/firemud/worldmanagement/repository/RoomRepository.java +++ b/services/world-management-service/src/main/java/net/firedevops/firemud/worldmanagement/repository/RoomRepository.java @@ -4,12 +4,14 @@ import edu.umd.cs.findbugs.annotations.SuppressFBWarnings; import java.util.List; +import java.util.Objects; import java.util.Optional; import net.firedevops.firemud.worldmanagement.entity.Room; import net.firedevops.firemud.worldmanagement.jooq.tables.records.RoomRecord; import org.jooq.DSLContext; import org.jooq.Record; import org.springframework.stereotype.Repository; +import org.springframework.transaction.annotation.Transactional; @Repository @SuppressFBWarnings( @@ -87,6 +89,43 @@ public Room save(Room entity) { return findById(entity.getId()).orElseThrow(); } + @Transactional + public Room saveSeededWithExplicitId(Room entity) { + if (entity.getId() == null || entity.getId() <= 0) { + throw new IllegalArgumentException("SEED_ROOM_ID_INVALID: a positive room id is required"); + } + if (entity.getTenantId() == null + || entity.getVersionId() == null + || entity.getZone() == null + || entity.getZone().getId() == null + || entity.getName() == null) { + throw new IllegalArgumentException( + "SEED_ROOM_ID_INVALID: room template identity is required"); + } + + // Serialize explicit fixture inserts with ordinary room inserts before checking the PK or + // advancing the BIGSERIAL sequence. This is limited to the opt-in demo template seeder. + dsl.execute("LOCK TABLE room IN SHARE ROW EXCLUSIVE MODE"); + Room existing = findById(entity.getId()).orElse(null); + if (existing != null && !sameSeededTemplateIdentity(existing, entity)) { + throw new IllegalStateException( + "SEED_ROOM_ID_CONFLICT: room id " + + entity.getId() + + " belongs to a different tenant, version, zone, or template room"); + } + + if (existing == null) { + RoomRecord record = dsl.newRecord(ROOM); + record.setId(entity.getId()); + populate(record, entity); + record.insert(); + } else { + save(entity); + } + advanceRoomIdSequence(); + return findById(entity.getId()).orElseThrow(); + } + public void delete(Room entity) { dsl.deleteFrom(ROOM).where(ROOM.ID.eq(entity.getId())).execute(); } @@ -109,6 +148,22 @@ private void populate(RoomRecord record, Room entity) { record.setVersionId(entity.getVersionId()); } + private boolean sameSeededTemplateIdentity(Room existing, Room requested) { + return Objects.equals(existing.getTenantId(), requested.getTenantId()) + && Objects.equals(existing.getVersionId(), requested.getVersionId()) + && existing.getZone() != null + && Objects.equals(existing.getZone().getId(), requested.getZone().getId()) + && Objects.equals(existing.getName(), requested.getName()); + } + + private void advanceRoomIdSequence() { + dsl.fetchValue( + "SELECT setval(pg_get_serial_sequence('room', 'id'), " + + "GREATEST(COALESCE((SELECT MAX(id) FROM room), 1), " + + "COALESCE((SELECT last_value FROM room_id_seq), 1)), true)", + Long.class); + } + private Room toEntity(Record record) { Room entity = new Room(); entity.setId(record.get(ROOM.ID)); diff --git a/services/world-management-service/src/main/java/net/firedevops/firemud/worldmanagement/service/impl/InitialAdmissionBindHoldReconciler.java b/services/world-management-service/src/main/java/net/firedevops/firemud/worldmanagement/service/impl/InitialAdmissionBindHoldReconciler.java index 6bd2d07d1d..034331688a 100644 --- a/services/world-management-service/src/main/java/net/firedevops/firemud/worldmanagement/service/impl/InitialAdmissionBindHoldReconciler.java +++ b/services/world-management-service/src/main/java/net/firedevops/firemud/worldmanagement/service/impl/InitialAdmissionBindHoldReconciler.java @@ -8,6 +8,7 @@ import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.beans.factory.ObjectProvider; +import org.springframework.beans.factory.annotation.Autowired; import org.springframework.scheduling.annotation.Scheduled; import org.springframework.stereotype.Component; @@ -22,6 +23,7 @@ public class InitialAdmissionBindHoldReconciler { private final ObjectProvider proofClientProvider; private final Clock clock; + @Autowired public InitialAdmissionBindHoldReconciler( InitialAdmissionBindHoldRepository holdRepository, InitialAdmissionBindHoldService holdService, @@ -49,26 +51,37 @@ public void reconcilePendingHolds() { } GameSessionInitialAdmissionBindProofClient proofClient = proofClientProvider.getIfAvailable(); for (var hold : holds) { - if (proofClient == null) { - holdService.requireReconciliation(hold.holdId(), "GS_OWNER_READ_UNAVAILABLE"); - continue; - } - if (!hold.diagnosticExpiresAt().isAfter(clock.instant())) { - logger.warn( - "Initial admission bind hold exceeded its diagnostic age holdId={} tenant={} gameInstanceId={}", - hold.holdId(), - hold.tenantId(), - hold.gameInstanceId()); - } try { - holdService.reconcileOwnerProof(hold.holdId(), proofClient.readOwnerProof(hold)); + reconcileHold(hold, proofClient); } catch (RuntimeException exception) { logger.warn( - "Initial admission bind owner readback failed holdId={} errorType={}", - hold.holdId(), - exception.getClass().getSimpleName()); - holdService.requireReconciliation(hold.holdId(), "GS_OWNER_READ_FAILED"); + "Initial admission bind reconciliation failed holdId={}", hold.holdId(), exception); } } } + + private void reconcileHold( + net.firedevops.firemud.worldmanagement.entity.InitialAdmissionBindHold hold, + GameSessionInitialAdmissionBindProofClient proofClient) { + if (proofClient == null) { + holdService.requireReconciliation(hold.holdId(), "GS_OWNER_READ_UNAVAILABLE"); + return; + } + if (!hold.diagnosticExpiresAt().isAfter(clock.instant())) { + logger.warn( + "Initial admission bind hold exceeded its diagnostic age holdId={} tenant={} gameInstanceId={}", + hold.holdId(), + hold.tenantId(), + hold.gameInstanceId()); + } + try { + holdService.reconcileOwnerProof(hold.holdId(), proofClient.readOwnerProof(hold)); + } catch (RuntimeException exception) { + logger.warn( + "Initial admission bind owner readback failed holdId={} errorType={}", + hold.holdId(), + exception.getClass().getSimpleName()); + holdService.requireReconciliation(hold.holdId(), "GS_OWNER_READ_FAILED"); + } + } } diff --git a/services/world-management-service/src/main/java/net/firedevops/firemud/worldmanagement/service/impl/InitialAdmissionBindHoldServiceImpl.java b/services/world-management-service/src/main/java/net/firedevops/firemud/worldmanagement/service/impl/InitialAdmissionBindHoldServiceImpl.java index 557c42c3e0..bfdf0659c1 100644 --- a/services/world-management-service/src/main/java/net/firedevops/firemud/worldmanagement/service/impl/InitialAdmissionBindHoldServiceImpl.java +++ b/services/world-management-service/src/main/java/net/firedevops/firemud/worldmanagement/service/impl/InitialAdmissionBindHoldServiceImpl.java @@ -208,10 +208,6 @@ public InitialAdmissionBindHoldDto requireReconciliation(String holdId, String e private InitialAdmissionBindHoldDto markReconciliationRequired( InitialAdmissionBindHold hold, String errorCode) { String normalizedErrorCode = normalizeErrorCode(errorCode); - if (STATUS_RECONCILIATION_REQUIRED.equals(hold.status()) - && normalizedErrorCode.equals(hold.reconciliationError())) { - return toDto(hold); - } return holdRepository .markReconciliationRequired(hold, normalizedErrorCode, clock.instant()) .map(this::toDto) @@ -300,7 +296,7 @@ private boolean hasDefinitiveTerminalEvidence( } if (proof.outcome() == InitialAdmissionBindOwnerProof.Outcome.COMMITTED) { return proof.expectedNoPriorPointer() - && proof.pointerVersion() > 0L + && proof.pointerVersion() == 1L && proof.pointerAuditId() != null && !proof.pointerAuditId().isBlank() && hold.requestDigest().equals(proof.pointerAuditRequestDigest()); @@ -382,7 +378,6 @@ private String proofDigest(InitialAdmissionBindOwnerProof proof) { nullToEmpty(proof.pointerAuditId()), Long.toString(proof.pointerVersion()), nullToEmpty(proof.pointerAuditRequestDigest()), - Boolean.toString(proof.priorPointerStillAbsent()), Boolean.toString(proof.futureCommitPrevented())); try { return HexFormat.of() diff --git a/services/world-management-service/src/test/java/integration/net/firedevops/firemud/worldmanagement/RoomRepositoryPostgresIntegrationTest.java b/services/world-management-service/src/test/java/integration/net/firedevops/firemud/worldmanagement/RoomRepositoryPostgresIntegrationTest.java new file mode 100644 index 0000000000..0f1712ca91 --- /dev/null +++ b/services/world-management-service/src/test/java/integration/net/firedevops/firemud/worldmanagement/RoomRepositoryPostgresIntegrationTest.java @@ -0,0 +1,116 @@ +package net.firedevops.firemud.worldmanagement; + +import static org.assertj.core.api.Assertions.assertThat; +import static org.assertj.core.api.Assertions.assertThatThrownBy; + +import net.firedevops.firemud.test.PostgresBackedServiceTestSupport; +import net.firedevops.firemud.worldmanagement.client.EntityManagementClient; +import net.firedevops.firemud.worldmanagement.client.GameDesignClient; +import net.firedevops.firemud.worldmanagement.client.GameSessionClient; +import net.firedevops.firemud.worldmanagement.entity.Region; +import net.firedevops.firemud.worldmanagement.entity.Room; +import net.firedevops.firemud.worldmanagement.entity.Zone; +import net.firedevops.firemud.worldmanagement.repository.RegionRepository; +import net.firedevops.firemud.worldmanagement.repository.RoomRepository; +import net.firedevops.firemud.worldmanagement.repository.ZoneRepository; +import org.junit.jupiter.api.Test; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.boot.test.context.SpringBootTest; +import org.springframework.grpc.server.lifecycle.GrpcServerLifecycle; +import org.springframework.test.context.DynamicPropertyRegistry; +import org.springframework.test.context.DynamicPropertySource; +import org.springframework.test.context.bean.override.mockito.MockitoBean; +import org.testcontainers.containers.GenericContainer; +import org.testcontainers.containers.PostgreSQLContainer; +import org.testcontainers.junit.jupiter.Container; +import org.testcontainers.junit.jupiter.Testcontainers; + +@Testcontainers(disabledWithoutDocker = true) +@SuppressWarnings("resource") +@SpringBootTest( + classes = WorldManagementServiceApplication.class, + properties = {"spring.grpc.server.port=0", "firemud.smoke.seed-demo-runtime.enabled=false"}) +class RoomRepositoryPostgresIntegrationTest { + private static final long TENANT_ID = 82001L; + private static final long VERSION_ID = 77L; + + @Container + static PostgreSQLContainer postgres = new PostgreSQLContainer<>("postgres:16-alpine"); + + @Container + static GenericContainer redis = + new GenericContainer<>("redis:7.2-alpine").withExposedPorts(6379); + + @DynamicPropertySource + static void configure(DynamicPropertyRegistry registry) { + PostgresBackedServiceTestSupport.registerPostgresService( + registry, postgres, "world_management_service"); + PostgresBackedServiceTestSupport.registerRedisService(registry, redis); + } + + @Autowired private RegionRepository regionRepository; + @Autowired private RoomRepository roomRepository; + @Autowired private ZoneRepository zoneRepository; + + @MockitoBean private GrpcServerLifecycle grpcServerLifecycle; + @MockitoBean private EntityManagementClient entityManagementClient; + @MockitoBean private GameDesignClient gameDesignClient; + @MockitoBean private GameSessionClient gameSessionClient; + + @Test + void seededRoomIdentityInsertAdvancesSequenceAndRejectsForeignCollision() { + Region region = new Region(); + region.setTenantId(TENANT_ID); + region.setVersionId(VERSION_ID); + region.setShardId(0); + region.setName("Explicit Room ID Fixture"); + region.setGenerationSeed(0L); + region.setSpacingMultiplier(1.0); + Region savedRegion = regionRepository.save(region); + + Zone zone = new Zone(); + zone.setTenantId(TENANT_ID); + zone.setVersionId(VERSION_ID); + zone.setRegion(savedRegion); + zone.setName("Explicit Room ID Fixture Zone"); + Zone savedZone = zoneRepository.save(zone); + + Room starter = room(1021L, TENANT_ID, savedZone, "Candle-lit Antechamber"); + Room secondary = room(2045L, TENANT_ID, savedZone, "Smith's Annex"); + Room savedStarter = roomRepository.saveSeededWithExplicitId(starter); + Room savedSecondary = roomRepository.saveSeededWithExplicitId(secondary); + + assertThat(savedStarter.getId()).isEqualTo(1021L); + assertThat(savedStarter.getTenantId()).isEqualTo(TENANT_ID); + assertThat(savedStarter.getVersionId()).isEqualTo(VERSION_ID); + assertThat(savedStarter.getZone().getId()).isEqualTo(savedZone.getId()); + assertThat(savedSecondary.getId()).isEqualTo(2045L); + assertThat(savedSecondary.getTenantId()).isEqualTo(TENANT_ID); + assertThat(savedSecondary.getVersionId()).isEqualTo(VERSION_ID); + assertThat(savedSecondary.getZone().getId()).isEqualTo(savedZone.getId()); + + Room ordinaryRoom = room(null, TENANT_ID, savedZone, "Ordinary Future Room"); + Room savedOrdinaryRoom = roomRepository.save(ordinaryRoom); + assertThat(savedOrdinaryRoom.getId()).isGreaterThan(2045L); + + Room conflictingRoom = room(1021L, TENANT_ID + 1, savedZone, "Foreign Template Room"); + assertThatThrownBy(() -> roomRepository.saveSeededWithExplicitId(conflictingRoom)) + .isInstanceOf(IllegalStateException.class) + .hasMessageStartingWith("SEED_ROOM_ID_CONFLICT:"); + assertThat(roomRepository.findById(1021L)) + .get() + .extracting(Room::getTenantId, Room::getVersionId, Room::getName) + .containsExactly(TENANT_ID, VERSION_ID, "Candle-lit Antechamber"); + } + + private Room room(Long id, long tenantId, Zone zone, String name) { + Room room = new Room(); + room.setId(id); + room.setTenantId(tenantId); + room.setVersionId(VERSION_ID); + room.setZone(zone); + room.setName(name); + room.setDescription("Integration fixture room."); + return room; + } +} diff --git a/services/world-management-service/src/test/java/unit/net/firedevops/firemud/worldmanagement/client/GrpcGameSessionInitialAdmissionBindProofClientTest.java b/services/world-management-service/src/test/java/unit/net/firedevops/firemud/worldmanagement/client/GrpcGameSessionInitialAdmissionBindProofClientTest.java new file mode 100644 index 0000000000..8cc01a9e0c --- /dev/null +++ b/services/world-management-service/src/test/java/unit/net/firedevops/firemud/worldmanagement/client/GrpcGameSessionInitialAdmissionBindProofClientTest.java @@ -0,0 +1,223 @@ +package net.firedevops.firemud.worldmanagement.client; + +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertNull; +import static org.junit.jupiter.api.Assertions.assertThrows; +import static org.mockito.ArgumentMatchers.any; +import static org.mockito.ArgumentMatchers.anyLong; +import static org.mockito.Mockito.mock; +import static org.mockito.Mockito.never; +import static org.mockito.Mockito.verify; +import static org.mockito.Mockito.when; + +import io.grpc.ManagedChannel; +import java.time.Instant; +import java.util.concurrent.TimeUnit; +import javax.net.ssl.SSLException; +import net.firedevops.firemud.common.config.ServiceEndpointsProperties; +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.entitymanagement.v1.PlayableStateScope; +import net.firedevops.firemud.gamesession.v1.GameSessionControlPlaneServiceGrpc; +import net.firedevops.firemud.gamesession.v1.GetInitialAdmissionBindProofRequest; +import net.firedevops.firemud.gamesession.v1.GetInitialAdmissionBindProofResponse; +import net.firedevops.firemud.gamesession.v1.InitialAdmissionBindOwnerProofOutcome; +import net.firedevops.firemud.worldmanagement.dto.InitialAdmissionBindOwnerProof.Outcome; +import net.firedevops.firemud.worldmanagement.entity.InitialAdmissionBindHold; +import org.junit.jupiter.api.Test; +import org.mockito.ArgumentCaptor; + +class GrpcGameSessionInitialAdmissionBindProofClientTest { + private static final String HOLD_ID = "00000000-0000-0000-0000-000000000003"; + private static final String HOLD_FENCE = "00000000-0000-0000-0000-000000000004"; + private static final String REALM_UUID = "00000000-0000-0000-0000-000000000001"; + private static final String NAMESPACE_UUID = "00000000-0000-0000-0000-000000000002"; + private static final String REQUEST_ID = "initial-admission-1"; + private static final String REQUEST_DIGEST = "a".repeat(64); + + @Test + void sendsFullHoldTupleWithDeadlineAndMapsCommittedOwnerProof() throws Exception { + var stub = + mock(GameSessionControlPlaneServiceGrpc.GameSessionControlPlaneServiceBlockingStub.class); + when(stub.withDeadlineAfter(anyLong(), any())).thenReturn(stub); + when(stub.getInitialAdmissionBindProof(any())) + .thenReturn( + response( + InitialAdmissionBindOwnerProofOutcome + .INITIAL_ADMISSION_BIND_OWNER_PROOF_OUTCOME_COMMITTED, + "gs-ledger-100", + "audit-100", + 1L, + REQUEST_DIGEST, + false)); + TestClient client = client(stub); + client.init(); + + var proof = client.readOwnerProof(hold("SHARED")); + + ArgumentCaptor request = + ArgumentCaptor.forClass(GetInitialAdmissionBindProofRequest.class); + verify(stub).withDeadlineAfter(5L, TimeUnit.SECONDS); + verify(stub).getInitialAdmissionBindProof(request.capture()); + assertEquals(HOLD_ID, request.getValue().getHoldId()); + assertEquals(HOLD_FENCE, request.getValue().getHoldFence()); + assertEquals("42", request.getValue().getTenantId()); + assertEquals(REALM_UUID, request.getValue().getRealmUuid()); + assertEquals(NAMESPACE_UUID, request.getValue().getPlayableStateNamespaceUuid()); + assertEquals( + PlayableStateScope.PLAYABLE_STATE_SCOPE_SHARED, request.getValue().getPlayableStateScope()); + assertEquals("101", request.getValue().getGameInstanceId()); + assertEquals("11", request.getValue().getVersionId()); + assertEquals(7L, request.getValue().getActiveLifecycleEpoch()); + assertEquals(REQUEST_ID, request.getValue().getInitialAdmissionRequestId()); + assertEquals(REQUEST_DIGEST, request.getValue().getRequestDigest()); + assertEquals(1L, request.getValue().getExpectedCatalogRevision()); + assertEquals(Outcome.COMMITTED, proof.outcome()); + assertEquals("gs-ledger-100", proof.ownerProofId()); + assertEquals("audit-100", proof.pointerAuditId()); + assertEquals(1L, proof.pointerVersion()); + assertEquals(REQUEST_DIGEST, proof.pointerAuditRequestDigest()); + client.close(); + } + + @Test + void mapsExactAbortedAttemptTombstoneWithoutGlobalPointerAbsenceClaim() throws Exception { + var stub = + mock(GameSessionControlPlaneServiceGrpc.GameSessionControlPlaneServiceBlockingStub.class); + when(stub.withDeadlineAfter(anyLong(), any())).thenReturn(stub); + when(stub.getInitialAdmissionBindProof(any())) + .thenReturn( + response( + InitialAdmissionBindOwnerProofOutcome + .INITIAL_ADMISSION_BIND_OWNER_PROOF_OUTCOME_ABORTED, + "gs-ledger-101", + "", + 0L, + "", + true)); + TestClient client = client(stub); + client.init(); + + var proof = client.readOwnerProof(hold("SHARED")); + + assertEquals(Outcome.ABORTED, proof.outcome()); + assertEquals("gs-ledger-101", proof.ownerProofId()); + assertNull(proof.pointerAuditId()); + assertEquals(0L, proof.pointerVersion()); + assertNull(proof.pointerAuditRequestDigest()); + assertEquals(true, proof.futureCommitPrevented()); + client.close(); + } + + @Test + void unsupportedLocalScopeFailsBeforeCallingGameSession() throws Exception { + var stub = + mock(GameSessionControlPlaneServiceGrpc.GameSessionControlPlaneServiceBlockingStub.class); + TestClient client = client(stub); + client.init(); + + assertThrows(IllegalArgumentException.class, () -> client.readOwnerProof(hold("UNKNOWN"))); + + verify(stub, never()).getInitialAdmissionBindProof(any()); + client.close(); + } + + private static GetInitialAdmissionBindProofResponse response( + InitialAdmissionBindOwnerProofOutcome outcome, + String ownerProofId, + String auditId, + long pointerVersion, + String auditDigest, + boolean futureCommitPrevented) { + return GetInitialAdmissionBindProofResponse.newBuilder() + .setHoldId(HOLD_ID) + .setHoldFence(HOLD_FENCE) + .setTenantId("42") + .setRealmUuid(REALM_UUID) + .setPlayableStateNamespaceUuid(NAMESPACE_UUID) + .setPlayableStateScope(PlayableStateScope.PLAYABLE_STATE_SCOPE_SHARED) + .setGameInstanceId("101") + .setVersionId("11") + .setActiveLifecycleEpoch(7L) + .setInitialAdmissionRequestId(REQUEST_ID) + .setRequestDigest(REQUEST_DIGEST) + .setExpectedNoPriorPointer(true) + .setExpectedCatalogRevision(1L) + .setOutcome(outcome) + .setOwnerProofId(ownerProofId) + .setPointerAuditId(auditId) + .setPointerVersion(pointerVersion) + .setPointerAuditRequestDigest(auditDigest) + .setFutureCommitPrevented(futureCommitPrevented) + .build(); + } + + private static InitialAdmissionBindHold hold(String scope) { + Instant now = Instant.parse("2026-10-02T00:00:00Z"); + return new InitialAdmissionBindHold( + HOLD_ID, + HOLD_FENCE, + 42L, + REALM_UUID, + NAMESPACE_UUID, + scope, + 101L, + 11L, + 7L, + REQUEST_ID, + REQUEST_DIGEST, + true, + 1L, + "PENDING", + now.plusSeconds(300), + null, + null, + null, + null, + null, + now, + now, + null, + 0L); + } + + private static TestClient client( + GameSessionControlPlaneServiceGrpc.GameSessionControlPlaneServiceBlockingStub stub) { + ServiceEndpointsProperties endpoints = new ServiceEndpointsProperties(); + CommonGrpcClientProperties grpc = new CommonGrpcClientProperties(); + grpc.setPlaintext(true); + return new TestClient( + endpoints, grpc, new PassingChannelFactory(), BlockingGrpcStubCustomizer.noop(), stub); + } + + private static final class TestClient extends GrpcGameSessionInitialAdmissionBindProofClient { + private final GameSessionControlPlaneServiceGrpc.GameSessionControlPlaneServiceBlockingStub + stub; + + private TestClient( + ServiceEndpointsProperties endpoints, + CommonGrpcClientProperties tlsProps, + GrpcChannelFactory channelFactory, + BlockingGrpcStubCustomizer stubCustomizer, + GameSessionControlPlaneServiceGrpc.GameSessionControlPlaneServiceBlockingStub stub) { + super(endpoints, tlsProps, channelFactory, stubCustomizer); + this.stub = stub; + } + + @Override + protected GameSessionControlPlaneServiceGrpc.GameSessionControlPlaneServiceBlockingStub + buildStub(ManagedChannel channel) { + return stub; + } + } + + private static final class PassingChannelFactory extends GrpcChannelFactory { + @Override + public ManagedChannel buildChannel( + String target, int defaultPort, CommonGrpcClientProperties properties, boolean keepAlive) + throws SSLException { + return mock(ManagedChannel.class); + } + } +} diff --git a/services/world-management-service/src/test/java/unit/net/firedevops/firemud/worldmanagement/data/TestDataSeederTest.java b/services/world-management-service/src/test/java/unit/net/firedevops/firemud/worldmanagement/data/TestDataSeederTest.java index 73258d65b0..c7b61de93d 100644 --- a/services/world-management-service/src/test/java/unit/net/firedevops/firemud/worldmanagement/data/TestDataSeederTest.java +++ b/services/world-management-service/src/test/java/unit/net/firedevops/firemud/worldmanagement/data/TestDataSeederTest.java @@ -1,6 +1,8 @@ package net.firedevops.firemud.worldmanagement.data; import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertThrows; +import static org.junit.jupiter.api.Assertions.assertTrue; import static org.mockito.ArgumentMatchers.any; import static org.mockito.Mockito.never; import static org.mockito.Mockito.times; @@ -9,24 +11,13 @@ import java.util.List; import java.util.Optional; -import net.firedevops.firemud.worldmanagement.config.SmokeDemoRuntimeSeedProperties; import net.firedevops.firemud.worldmanagement.entity.Region; -import net.firedevops.firemud.worldmanagement.entity.RegionInstance; import net.firedevops.firemud.worldmanagement.entity.Room; import net.firedevops.firemud.worldmanagement.entity.RoomExit; -import net.firedevops.firemud.worldmanagement.entity.RoomInstance; -import net.firedevops.firemud.worldmanagement.entity.RoomInstanceExit; -import net.firedevops.firemud.worldmanagement.entity.WorldInstance; import net.firedevops.firemud.worldmanagement.entity.Zone; -import net.firedevops.firemud.worldmanagement.entity.ZoneInstance; -import net.firedevops.firemud.worldmanagement.repository.RegionInstanceRepository; import net.firedevops.firemud.worldmanagement.repository.RegionRepository; import net.firedevops.firemud.worldmanagement.repository.RoomExitRepository; -import net.firedevops.firemud.worldmanagement.repository.RoomInstanceExitRepository; -import net.firedevops.firemud.worldmanagement.repository.RoomInstanceRepository; import net.firedevops.firemud.worldmanagement.repository.RoomRepository; -import net.firedevops.firemud.worldmanagement.repository.WorldInstanceRepository; -import net.firedevops.firemud.worldmanagement.repository.ZoneInstanceRepository; import net.firedevops.firemud.worldmanagement.repository.ZoneRepository; import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.Test; @@ -40,36 +31,14 @@ class TestDataSeederTest { @Mock ZoneRepository zoneRepository; @Mock RoomRepository roomRepository; @Mock RoomExitRepository roomExitRepository; - @Mock WorldInstanceRepository worldInstanceRepository; - @Mock RegionInstanceRepository regionInstanceRepository; - @Mock ZoneInstanceRepository zoneInstanceRepository; - @Mock RoomInstanceRepository roomInstanceRepository; - @Mock RoomInstanceExitRepository roomInstanceExitRepository; private TestDataSeeder seeder; @BeforeEach void setup() { MockitoAnnotations.openMocks(this); - SmokeDemoRuntimeSeedProperties smokeDemoRuntimeSeedProperties = - new SmokeDemoRuntimeSeedProperties(); - SmokeDemoRuntimeSeedProperties.RuntimeTargetSeed target = - new SmokeDemoRuntimeSeedProperties.RuntimeTargetSeed(); - target.setTenantId(1L); - target.setGameInstanceId(1L); - smokeDemoRuntimeSeedProperties.setTargets(List.of(target)); seeder = - new TestDataSeeder( - regionRepository, - zoneRepository, - roomRepository, - roomExitRepository, - worldInstanceRepository, - regionInstanceRepository, - zoneInstanceRepository, - roomInstanceRepository, - roomInstanceExitRepository, - smokeDemoRuntimeSeedProperties); + new TestDataSeeder(regionRepository, zoneRepository, roomRepository, roomExitRepository); } @Test @@ -92,49 +61,50 @@ void runSeedsCanonicalTopologyWhenMissing() throws Exception { when(roomRepository.findFirstByTenantIdAndVersionIdAndZoneIdAndName( 1L, 1L, 20L, "Smith's Annex")) .thenReturn(Optional.empty()); - Room savedRoom1 = new Room(); - savedRoom1.setId(30L); - savedRoom1.setZone(savedZone); - savedRoom1.setName("Candle-lit Antechamber"); - Room savedRoom2 = new Room(); - savedRoom2.setId(31L); - savedRoom2.setZone(savedZone); - savedRoom2.setName("Smith's Annex"); - when(roomRepository.save(any())).thenReturn(savedRoom1, savedRoom2); + when(roomRepository.saveSeededWithExplicitId(any())) + .thenAnswer(invocation -> invocation.getArgument(0)); when(roomExitRepository.findFirstByTenantIdAndVersionIdAndFromRoomIdAndToRoomIdAndDirection( - 1L, 1L, 30L, 31L, "NORTH")) + 1L, 1L, 1021L, 2045L, "NORTH")) .thenReturn(Optional.empty()); when(roomExitRepository.findFirstByTenantIdAndVersionIdAndFromRoomIdAndToRoomIdAndDirection( - 1L, 1L, 31L, 30L, "SOUTH")) + 1L, 1L, 2045L, 1021L, "SOUTH")) .thenReturn(Optional.empty()); - when(zoneRepository.findByTenantIdAndVersionIdOrderByIdAsc(1L, 1L)).thenReturn(List.of()); - when(roomRepository.findByTenantIdAndVersionIdOrderByIdAsc(1L, 1L)).thenReturn(List.of()); - when(roomExitRepository.findByTenantIdAndVersionIdOrderByIdAsc(1L, 1L)).thenReturn(List.of()); - when(worldInstanceRepository.findByTenantIdAndGameInstanceId(1L, 1L)) - .thenReturn(Optional.empty()); - when(worldInstanceRepository.save(any())) - .thenAnswer(invocation -> withWorldInstanceId(invocation.getArgument(0))); - when(regionInstanceRepository.findByTenantIdAndGameInstanceId(1L, 1L)).thenReturn(List.of()); - when(regionInstanceRepository.save(any())) - .thenAnswer(invocation -> withRegionInstanceId(invocation.getArgument(0))); seeder.run(new DefaultApplicationArguments(new String[] {})); verify(regionRepository).save(any()); verify(zoneRepository).save(any()); - verify(roomRepository, times(2)).save(any()); - verify(worldInstanceRepository).save(any()); - verify(regionInstanceRepository).save(any()); - ArgumentCaptor exitCaptor = - ArgumentCaptor.forClass(net.firedevops.firemud.worldmanagement.entity.RoomExit.class); + ArgumentCaptor roomCaptor = ArgumentCaptor.forClass(Room.class); + verify(roomRepository, times(2)).saveSeededWithExplicitId(roomCaptor.capture()); + assertEquals( + List.of(1021L, 2045L), roomCaptor.getAllValues().stream().map(Room::getId).toList()); + assertEquals( + List.of("Candle-lit Antechamber", "Smith's Annex"), + roomCaptor.getAllValues().stream().map(Room::getName).toList()); + assertEquals( + List.of( + "Stalactites drip along the northern wall while a faint draft carries the smell of damp" + + " earth from the lower tunnels. Torches flicker in alcoves, casting motion into the" + + " shadowy archway to the north.", + "An anvil, banked coals, and orderly tool racks mark this alcove as a working annex off" + + " the starter chamber."), + roomCaptor.getAllValues().stream().map(Room::getDescription).toList()); + assertEquals( + List.of(1L, 1L), roomCaptor.getAllValues().stream().map(Room::getVersionId).toList()); + assertEquals( + List.of(1L, 1L), roomCaptor.getAllValues().stream().map(Room::getTenantId).toList()); + assertEquals( + List.of(20L, 20L), + roomCaptor.getAllValues().stream().map(room -> room.getZone().getId()).toList()); + ArgumentCaptor exitCaptor = ArgumentCaptor.forClass(RoomExit.class); verify(roomExitRepository, times(2)).save(exitCaptor.capture()); assertEquals( List.of("NORTH", "SOUTH"), exitCaptor.getAllValues().stream().map(RoomExit::getDirection).toList()); - assertEquals(30L, exitCaptor.getAllValues().get(0).getFromRoom().getId()); - assertEquals(31L, exitCaptor.getAllValues().get(0).getToRoom().getId()); - assertEquals(31L, exitCaptor.getAllValues().get(1).getFromRoom().getId()); - assertEquals(30L, exitCaptor.getAllValues().get(1).getToRoom().getId()); + assertEquals(1021L, exitCaptor.getAllValues().get(0).getFromRoom().getId()); + assertEquals(2045L, exitCaptor.getAllValues().get(0).getToRoom().getId()); + assertEquals(2045L, exitCaptor.getAllValues().get(1).getFromRoom().getId()); + assertEquals(1021L, exitCaptor.getAllValues().get(1).getToRoom().getId()); } @Test @@ -145,10 +115,10 @@ void runReassertsCanonicalTopologyWhenRowsAlreadyExist() throws Exception { existingZone.setId(20L); existingZone.setRegion(existingRegion); Room existingRoom1 = new Room(); - existingRoom1.setId(30L); + existingRoom1.setId(1021L); existingRoom1.setZone(existingZone); Room existingRoom2 = new Room(); - existingRoom2.setId(31L); + existingRoom2.setId(2045L); existingRoom2.setZone(existingZone); when(regionRepository.findFirstByTenantIdAndVersionIdAndShardIdAndName( @@ -164,29 +134,20 @@ void runReassertsCanonicalTopologyWhenRowsAlreadyExist() throws Exception { when(roomRepository.findFirstByTenantIdAndVersionIdAndZoneIdAndName( 1L, 1L, 20L, "Smith's Annex")) .thenReturn(Optional.of(existingRoom2)); - when(roomRepository.save(any())).thenReturn(existingRoom1, existingRoom2); + when(roomRepository.saveSeededWithExplicitId(any())) + .thenAnswer(invocation -> invocation.getArgument(0)); when(roomExitRepository.findFirstByTenantIdAndVersionIdAndFromRoomIdAndToRoomIdAndDirection( - 1L, 1L, 30L, 31L, "NORTH")) + 1L, 1L, 1021L, 2045L, "NORTH")) .thenReturn(Optional.of(existingExit(40L))); when(roomExitRepository.findFirstByTenantIdAndVersionIdAndFromRoomIdAndToRoomIdAndDirection( - 1L, 1L, 31L, 30L, "SOUTH")) + 1L, 1L, 2045L, 1021L, "SOUTH")) .thenReturn(Optional.of(existingExit(41L))); - when(zoneRepository.findByTenantIdAndVersionIdOrderByIdAsc(1L, 1L)).thenReturn(List.of()); - when(roomRepository.findByTenantIdAndVersionIdOrderByIdAsc(1L, 1L)).thenReturn(List.of()); - when(roomExitRepository.findByTenantIdAndVersionIdOrderByIdAsc(1L, 1L)).thenReturn(List.of()); - when(worldInstanceRepository.findByTenantIdAndGameInstanceId(1L, 1L)) - .thenReturn(Optional.empty()); - when(worldInstanceRepository.save(any())) - .thenAnswer(invocation -> withWorldInstanceId(invocation.getArgument(0))); - when(regionInstanceRepository.findByTenantIdAndGameInstanceId(1L, 1L)).thenReturn(List.of()); - when(regionInstanceRepository.save(any())) - .thenAnswer(invocation -> withRegionInstanceId(invocation.getArgument(0))); seeder.run(new DefaultApplicationArguments(new String[] {})); verify(regionRepository).save(any()); verify(zoneRepository).save(any()); - verify(roomRepository, times(2)).save(any()); + verify(roomRepository, times(2)).saveSeededWithExplicitId(any()); ArgumentCaptor exitCaptor = ArgumentCaptor.forClass(RoomExit.class); verify(roomExitRepository, times(2)).save(exitCaptor.capture()); assertEquals( @@ -194,169 +155,22 @@ void runReassertsCanonicalTopologyWhenRowsAlreadyExist() throws Exception { exitCaptor.getAllValues().stream().map(RoomExit::getDirection).toList()); assertEquals( List.of(40L, 41L), exitCaptor.getAllValues().stream().map(RoomExit::getId).toList()); - assertEquals(30L, exitCaptor.getAllValues().get(0).getFromRoom().getId()); - assertEquals(31L, exitCaptor.getAllValues().get(0).getToRoom().getId()); - assertEquals(31L, exitCaptor.getAllValues().get(1).getFromRoom().getId()); - assertEquals(30L, exitCaptor.getAllValues().get(1).getToRoom().getId()); - verify(regionRepository, never()).count(); - } - - @Test - void runReassertsRuntimeTopologyWhenWorldAlreadyExistsButRoomsAreMissing() throws Exception { - Region existingRegion = new Region(); - existingRegion.setId(10L); - Zone existingZone = new Zone(); - existingZone.setId(20L); - existingZone.setRegion(existingRegion); - Room templateRoom1 = new Room(); - templateRoom1.setId(30L); - templateRoom1.setZone(existingZone); - templateRoom1.setName("Candle-lit Antechamber"); - templateRoom1.setDescription("starter"); - Room templateRoom2 = new Room(); - templateRoom2.setId(31L); - templateRoom2.setZone(existingZone); - templateRoom2.setName("Smith's Annex"); - templateRoom2.setDescription("annex"); - RoomExit templateExit = new RoomExit(); - templateExit.setFromRoom(templateRoom1); - templateExit.setToRoom(templateRoom2); - templateExit.setDirection("NORTH"); - templateExit.setCost(1); - RoomExit reverseTemplateExit = new RoomExit(); - reverseTemplateExit.setFromRoom(templateRoom2); - reverseTemplateExit.setToRoom(templateRoom1); - reverseTemplateExit.setDirection("SOUTH"); - reverseTemplateExit.setCost(1); - WorldInstance existingWorld = new WorldInstance(); - existingWorld.setId(200L); - existingWorld.setTenantId(1L); - existingWorld.setGameInstanceId(1L); - existingWorld.setRowVersion(0L); - - when(regionRepository.findFirstByTenantIdAndVersionIdAndShardIdAndName( - 1L, 1L, 0, "Demo Region")) - .thenReturn(Optional.of(existingRegion)); - when(regionRepository.save(any())).thenReturn(existingRegion); - when(zoneRepository.findFirstByTenantIdAndVersionIdAndRegionIdAndName(1L, 1L, 10L, "Demo Zone")) - .thenReturn(Optional.of(existingZone)); - when(zoneRepository.save(any())).thenReturn(existingZone); - when(roomRepository.findFirstByTenantIdAndVersionIdAndZoneIdAndName( - 1L, 1L, 20L, "Candle-lit Antechamber")) - .thenReturn(Optional.of(templateRoom1)); - when(roomRepository.findFirstByTenantIdAndVersionIdAndZoneIdAndName( - 1L, 1L, 20L, "Smith's Annex")) - .thenReturn(Optional.of(templateRoom2)); - when(roomRepository.save(any())).thenReturn(templateRoom1, templateRoom2); - when(roomExitRepository.findFirstByTenantIdAndVersionIdAndFromRoomIdAndToRoomIdAndDirection( - 1L, 1L, 30L, 31L, "NORTH")) - .thenReturn(Optional.of(templateExit)); - when(roomExitRepository.findFirstByTenantIdAndVersionIdAndFromRoomIdAndToRoomIdAndDirection( - 1L, 1L, 31L, 30L, "SOUTH")) - .thenReturn(Optional.of(reverseTemplateExit)); - when(zoneRepository.findByTenantIdAndVersionIdOrderByIdAsc(1L, 1L)) - .thenReturn(List.of(existingZone)); - when(roomRepository.findByTenantIdAndVersionIdOrderByIdAsc(1L, 1L)) - .thenReturn(List.of(templateRoom1, templateRoom2)); - when(roomExitRepository.findByTenantIdAndVersionIdOrderByIdAsc(1L, 1L)) - .thenReturn(List.of(templateExit, reverseTemplateExit)); - when(worldInstanceRepository.findByTenantIdAndGameInstanceId(1L, 1L)) - .thenReturn(Optional.of(existingWorld)); - when(worldInstanceRepository.save(any())) - .thenAnswer(invocation -> withWorldInstanceId(invocation.getArgument(0))); - when(regionInstanceRepository.findByTenantIdAndGameInstanceId(1L, 1L)).thenReturn(List.of()); - when(regionInstanceRepository.save(any())) - .thenAnswer(invocation -> withRegionInstanceId(invocation.getArgument(0))); - when(zoneInstanceRepository.findByTenantIdAndGameInstanceIdAndZoneInstanceId(1L, 1L, 20L)) - .thenReturn(Optional.empty()); - when(zoneInstanceRepository.save(any())) - .thenAnswer(invocation -> withZoneInstanceId(invocation.getArgument(0))); - when(roomInstanceRepository.findByTenantIdAndGameInstanceIdOrderByRoomInstanceRowIdAsc(1L, 1L)) - .thenReturn(List.of()); - when(roomInstanceRepository.save(any())) - .thenAnswer(invocation -> withRoomInstanceRowId(invocation.getArgument(0))); - when(roomInstanceExitRepository.findByTenantIdAndGameInstanceIdAndFromRoomInstanceRecordId( - 1L, 1L, 1021L)) - .thenReturn(List.of()); - when(roomInstanceExitRepository.findByTenantIdAndGameInstanceIdAndFromRoomInstanceRecordId( - 1L, 1L, 2045L)) - .thenReturn(List.of()); - when(roomInstanceExitRepository.save(any())) - .thenAnswer(invocation -> withRoomInstanceExitId(invocation.getArgument(0))); - - seeder.run(new DefaultApplicationArguments(new String[] {})); - - verify(worldInstanceRepository).save(any()); - verify(regionInstanceRepository).save(any()); - verify(zoneInstanceRepository).save(any()); - verify(roomInstanceRepository, times(2)).save(any()); - ArgumentCaptor roomCaptor = ArgumentCaptor.forClass(RoomInstance.class); - verify(roomInstanceRepository, times(2)).save(roomCaptor.capture()); - List savedRooms = roomCaptor.getAllValues(); - assertEquals(1021L, savedRooms.get(0).getRoomInstanceRowId()); - assertEquals(2045L, savedRooms.get(1).getRoomInstanceRowId()); - ArgumentCaptor exitCaptor = ArgumentCaptor.forClass(RoomInstanceExit.class); - verify(roomInstanceExitRepository, times(2)).save(exitCaptor.capture()); - assertEquals( - List.of("NORTH", "SOUTH"), - exitCaptor.getAllValues().stream().map(RoomInstanceExit::getDirection).toList()); - assertEquals( - 1021L, exitCaptor.getAllValues().get(0).getFromRoomInstance().getRoomInstanceRowId()); - assertEquals( - 2045L, exitCaptor.getAllValues().get(0).getToRoomInstance().getRoomInstanceRowId()); - assertEquals( - 2045L, exitCaptor.getAllValues().get(1).getFromRoomInstance().getRoomInstanceRowId()); - assertEquals( - 1021L, exitCaptor.getAllValues().get(1).getToRoomInstance().getRoomInstanceRowId()); + assertEquals(1021L, exitCaptor.getAllValues().get(0).getFromRoom().getId()); + assertEquals(2045L, exitCaptor.getAllValues().get(0).getToRoom().getId()); + assertEquals(2045L, exitCaptor.getAllValues().get(1).getFromRoom().getId()); + assertEquals(1021L, exitCaptor.getAllValues().get(1).getToRoom().getId()); } @Test - void runMaterializesRuntimeTopologyForNonDefaultTenantFromCanonicalDemoTemplate() - throws Exception { - SmokeDemoRuntimeSeedProperties properties = new SmokeDemoRuntimeSeedProperties(); - SmokeDemoRuntimeSeedProperties.RuntimeTargetSeed target = - new SmokeDemoRuntimeSeedProperties.RuntimeTargetSeed(); - target.setTenantId(2L); - target.setGameInstanceId(55L); - properties.setTargets(List.of(target)); - seeder = - new TestDataSeeder( - regionRepository, - zoneRepository, - roomRepository, - roomExitRepository, - worldInstanceRepository, - regionInstanceRepository, - zoneInstanceRepository, - roomInstanceRepository, - roomInstanceExitRepository, - properties); - + void runFailsClosedWhenPersistedDemoRoomUsesAnotherIdentity() { Region existingRegion = new Region(); existingRegion.setId(10L); Zone existingZone = new Zone(); existingZone.setId(20L); existingZone.setRegion(existingRegion); - Room templateRoom1 = new Room(); - templateRoom1.setId(30L); - templateRoom1.setZone(existingZone); - templateRoom1.setName("Candle-lit Antechamber"); - templateRoom1.setDescription("starter"); - Room templateRoom2 = new Room(); - templateRoom2.setId(31L); - templateRoom2.setZone(existingZone); - templateRoom2.setName("Smith's Annex"); - templateRoom2.setDescription("annex"); - RoomExit templateExit = new RoomExit(); - templateExit.setFromRoom(templateRoom1); - templateExit.setToRoom(templateRoom2); - templateExit.setDirection("NORTH"); - templateExit.setCost(1); - RoomExit reverseTemplateExit = new RoomExit(); - reverseTemplateExit.setFromRoom(templateRoom2); - reverseTemplateExit.setToRoom(templateRoom1); - reverseTemplateExit.setDirection("SOUTH"); - reverseTemplateExit.setCost(1); + Room starterRoom = new Room(); + starterRoom.setId(30L); + starterRoom.setZone(existingZone); when(regionRepository.findFirstByTenantIdAndVersionIdAndShardIdAndName( 1L, 1L, 0, "Demo Region")) @@ -367,79 +181,16 @@ void runMaterializesRuntimeTopologyForNonDefaultTenantFromCanonicalDemoTemplate( when(zoneRepository.save(any())).thenReturn(existingZone); when(roomRepository.findFirstByTenantIdAndVersionIdAndZoneIdAndName( 1L, 1L, 20L, "Candle-lit Antechamber")) - .thenReturn(Optional.of(templateRoom1)); - when(roomRepository.findFirstByTenantIdAndVersionIdAndZoneIdAndName( - 1L, 1L, 20L, "Smith's Annex")) - .thenReturn(Optional.of(templateRoom2)); - when(roomRepository.save(any())).thenReturn(templateRoom1, templateRoom2); - when(roomExitRepository.findFirstByTenantIdAndVersionIdAndFromRoomIdAndToRoomIdAndDirection( - 1L, 1L, 30L, 31L, "NORTH")) - .thenReturn(Optional.of(templateExit)); - when(roomExitRepository.findFirstByTenantIdAndVersionIdAndFromRoomIdAndToRoomIdAndDirection( - 1L, 1L, 31L, 30L, "SOUTH")) - .thenReturn(Optional.of(reverseTemplateExit)); - when(zoneRepository.findByTenantIdAndVersionIdOrderByIdAsc(1L, 1L)) - .thenReturn(List.of(existingZone)); - when(roomRepository.findByTenantIdAndVersionIdOrderByIdAsc(1L, 1L)) - .thenReturn(List.of(templateRoom1, templateRoom2)); - when(roomExitRepository.findByTenantIdAndVersionIdOrderByIdAsc(1L, 1L)) - .thenReturn(List.of(templateExit, reverseTemplateExit)); - when(worldInstanceRepository.findByTenantIdAndGameInstanceId(2L, 55L)) - .thenReturn(Optional.empty()); - when(worldInstanceRepository.save(any())) - .thenAnswer(invocation -> withWorldInstanceId(invocation.getArgument(0))); - when(regionInstanceRepository.findByTenantIdAndGameInstanceId(2L, 55L)).thenReturn(List.of()); - when(regionInstanceRepository.save(any())) - .thenAnswer(invocation -> withRegionInstanceId(invocation.getArgument(0))); - when(zoneInstanceRepository.findByTenantIdAndGameInstanceIdAndZoneInstanceId(2L, 55L, 20L)) - .thenReturn(Optional.empty()); - when(zoneInstanceRepository.save(any())) - .thenAnswer(invocation -> withZoneInstanceId(invocation.getArgument(0))); - when(roomInstanceRepository.findByTenantIdAndGameInstanceIdOrderByRoomInstanceRowIdAsc(2L, 55L)) - .thenReturn(List.of()); - when(roomInstanceRepository.save(any())) - .thenAnswer(invocation -> withRoomInstanceRowId(invocation.getArgument(0))); - when(roomInstanceExitRepository.findByTenantIdAndGameInstanceIdAndFromRoomInstanceRecordId( - 2L, 55L, 1021L)) - .thenReturn(List.of()); - when(roomInstanceExitRepository.findByTenantIdAndGameInstanceIdAndFromRoomInstanceRecordId( - 2L, 55L, 2045L)) - .thenReturn(List.of()); - when(roomInstanceExitRepository.save(any())) - .thenAnswer(invocation -> withRoomInstanceExitId(invocation.getArgument(0))); - - seeder.run(new DefaultApplicationArguments(new String[] {})); + .thenReturn(Optional.of(starterRoom)); - verify(zoneRepository).findByTenantIdAndVersionIdOrderByIdAsc(1L, 1L); - verify(roomRepository).findByTenantIdAndVersionIdOrderByIdAsc(1L, 1L); - verify(roomExitRepository).findByTenantIdAndVersionIdOrderByIdAsc(1L, 1L); - verify(worldInstanceRepository).findByTenantIdAndGameInstanceId(2L, 55L); - verify(zoneInstanceRepository).findByTenantIdAndGameInstanceIdAndZoneInstanceId(2L, 55L, 20L); - verify(roomInstanceRepository, times(2)).save(any()); - ArgumentCaptor exitCaptor = ArgumentCaptor.forClass(RoomInstanceExit.class); - verify(roomInstanceExitRepository, times(2)).save(exitCaptor.capture()); - List savedExits = exitCaptor.getAllValues(); - assertEquals( - List.of("NORTH", "SOUTH"), - savedExits.stream().map(RoomInstanceExit::getDirection).toList()); - assertEquals(2L, savedExits.get(0).getTenantId()); - assertEquals(55L, savedExits.get(0).getGameInstanceId()); - assertEquals(1021L, savedExits.get(0).getFromRoomInstance().getRoomInstanceRowId()); - assertEquals(2045L, savedExits.get(0).getToRoomInstance().getRoomInstanceRowId()); - assertEquals(2L, savedExits.get(1).getTenantId()); - assertEquals(55L, savedExits.get(1).getGameInstanceId()); - assertEquals(2045L, savedExits.get(1).getFromRoomInstance().getRoomInstanceRowId()); - assertEquals(1021L, savedExits.get(1).getToRoomInstance().getRoomInstanceRowId()); - } + IllegalStateException exception = + assertThrows( + IllegalStateException.class, + () -> seeder.run(new DefaultApplicationArguments(new String[] {}))); - private WorldInstance withWorldInstanceId(WorldInstance worldInstance) { - if (worldInstance.getId() == null) { - worldInstance.setId(200L); - } - if (worldInstance.getRowVersion() == null) { - worldInstance.setRowVersion(0L); - } - return worldInstance; + assertTrue(exception.getMessage().startsWith("DEMO_TEMPLATE_ROOM_ID_MISMATCH:")); + verify(roomRepository, never()).saveSeededWithExplicitId(any()); + verify(roomExitRepository, never()).save(any()); } private RoomExit existingExit(long id) { @@ -447,32 +198,4 @@ private RoomExit existingExit(long id) { exit.setId(id); return exit; } - - private RegionInstance withRegionInstanceId(RegionInstance regionInstance) { - if (regionInstance.getId() == null) { - regionInstance.setId(300L); - } - return regionInstance; - } - - private ZoneInstance withZoneInstanceId(ZoneInstance zoneInstance) { - if (zoneInstance.getId() == null) { - zoneInstance.setId(400L + zoneInstance.getZoneInstanceId()); - } - return zoneInstance; - } - - private RoomInstance withRoomInstanceRowId(RoomInstance roomInstance) { - if (roomInstance.getId() == null) { - roomInstance.setId(roomInstance.getRoomInstanceRowId()); - } - return roomInstance; - } - - private RoomInstanceExit withRoomInstanceExitId(RoomInstanceExit roomInstanceExit) { - if (roomInstanceExit.getId() == null) { - roomInstanceExit.setId(500L); - } - return roomInstanceExit; - } } diff --git a/services/world-management-service/src/test/java/unit/net/firedevops/firemud/worldmanagement/repository/InitialAdmissionBindHoldRepositoryTest.java b/services/world-management-service/src/test/java/unit/net/firedevops/firemud/worldmanagement/repository/InitialAdmissionBindHoldRepositoryTest.java new file mode 100644 index 0000000000..2f485d63dc --- /dev/null +++ b/services/world-management-service/src/test/java/unit/net/firedevops/firemud/worldmanagement/repository/InitialAdmissionBindHoldRepositoryTest.java @@ -0,0 +1,84 @@ +package net.firedevops.firemud.worldmanagement.repository; + +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertFalse; +import static org.junit.jupiter.api.Assertions.assertTrue; +import static org.mockito.ArgumentMatchers.any; +import static org.mockito.ArgumentMatchers.anyString; +import static org.mockito.Mockito.verify; +import static org.mockito.Mockito.verifyNoMoreInteractions; +import static org.mockito.Mockito.when; + +import java.time.Instant; +import java.time.LocalDateTime; +import java.time.ZoneOffset; +import net.firedevops.firemud.worldmanagement.entity.InitialAdmissionBindHold; +import org.jooq.DSLContext; +import org.junit.jupiter.api.Test; +import org.mockito.ArgumentCaptor; +import org.mockito.Mockito; + +class InitialAdmissionBindHoldRepositoryTest { + private static final String HOLD_ID = "00000000-0000-0000-0000-000000000003"; + + @Test + void lostReconciliationCasReturnsEmptyWithoutReadingConcurrentRowAsSuccess() { + DSLContext dsl = Mockito.mock(DSLContext.class); + when(dsl.execute(anyString(), any(Object[].class))).thenReturn(0); + InitialAdmissionBindHoldRepository repository = new InitialAdmissionBindHoldRepository(dsl); + + var result = repository.markReconciliationRequired(hold(), "GS_OWNER_PENDING", Instant.now()); + + assertFalse(result.isPresent()); + ArgumentCaptor query = ArgumentCaptor.forClass(String.class); + verify(dsl).execute(query.capture(), any(Object[].class)); + assertTrue(query.getValue().startsWith("UPDATE initial_admission_bind_hold SET")); + verifyNoMoreInteractions(dsl); + } + + @Test + void reconciliationAttemptUpdatesTimestampAndRowVersionEvenForSameDiagnostic() { + DSLContext dsl = Mockito.mock(DSLContext.class); + when(dsl.execute(anyString(), Mockito.any())).thenReturn(0); + InitialAdmissionBindHoldRepository repository = new InitialAdmissionBindHoldRepository(dsl); + Instant attemptedAt = Instant.parse("2026-10-02T04:05:06Z"); + + repository.markReconciliationRequired(hold(), "GS_OWNER_PENDING", attemptedAt); + + ArgumentCaptor query = ArgumentCaptor.forClass(String.class); + ArgumentCaptor bindings = ArgumentCaptor.forClass(Object[].class); + verify(dsl).execute(query.capture(), bindings.capture()); + assertTrue(query.getValue().contains("updated_at = ?")); + assertTrue(query.getValue().contains("row_version = row_version + 1")); + assertEquals(LocalDateTime.ofInstant(attemptedAt, ZoneOffset.UTC), bindings.getValue()[1]); + } + + private InitialAdmissionBindHold hold() { + Instant now = Instant.parse("2026-10-02T00:00:00Z"); + return new InitialAdmissionBindHold( + HOLD_ID, + "00000000-0000-0000-0000-000000000004", + 42L, + "00000000-0000-0000-0000-000000000001", + "00000000-0000-0000-0000-000000000002", + "SHARED", + 101L, + 11L, + 7L, + "initial-admission-1", + "a".repeat(64), + true, + 1L, + "RECONCILIATION_REQUIRED", + now.plusSeconds(300), + null, + null, + null, + null, + "GS_OWNER_PENDING", + now, + now, + null, + 3L); + } +} diff --git a/services/world-management-service/src/test/java/unit/net/firedevops/firemud/worldmanagement/service/impl/InitialAdmissionBindHoldReconcilerTest.java b/services/world-management-service/src/test/java/unit/net/firedevops/firemud/worldmanagement/service/impl/InitialAdmissionBindHoldReconcilerTest.java new file mode 100644 index 0000000000..c2acf3e573 --- /dev/null +++ b/services/world-management-service/src/test/java/unit/net/firedevops/firemud/worldmanagement/service/impl/InitialAdmissionBindHoldReconcilerTest.java @@ -0,0 +1,97 @@ +package net.firedevops.firemud.worldmanagement.service.impl; + +import static org.junit.jupiter.api.Assertions.assertNotNull; +import static org.mockito.Mockito.doThrow; +import static org.mockito.Mockito.verify; +import static org.mockito.Mockito.when; + +import java.time.Instant; +import java.util.List; +import net.firedevops.firemud.worldmanagement.client.GameSessionInitialAdmissionBindProofClient; +import net.firedevops.firemud.worldmanagement.entity.InitialAdmissionBindHold; +import net.firedevops.firemud.worldmanagement.repository.InitialAdmissionBindHoldRepository; +import net.firedevops.firemud.worldmanagement.service.InitialAdmissionBindHoldService; +import org.junit.jupiter.api.Test; +import org.mockito.Mockito; +import org.springframework.beans.factory.ObjectProvider; +import org.springframework.context.annotation.AnnotationConfigApplicationContext; + +class InitialAdmissionBindHoldReconcilerTest { + @Test + void springContextSelectsAutowiredProductionConstructor() { + try (AnnotationConfigApplicationContext context = new AnnotationConfigApplicationContext()) { + context.registerBean( + InitialAdmissionBindHoldRepository.class, + () -> Mockito.mock(InitialAdmissionBindHoldRepository.class)); + context.registerBean( + InitialAdmissionBindHoldService.class, + () -> Mockito.mock(InitialAdmissionBindHoldService.class)); + context.registerBean( + GameSessionInitialAdmissionBindProofClient.class, + () -> Mockito.mock(GameSessionInitialAdmissionBindProofClient.class)); + context.registerBean(InitialAdmissionBindHoldReconciler.class); + + context.refresh(); + + assertNotNull(context.getBean(InitialAdmissionBindHoldReconciler.class)); + } + } + + @Test + void failedReconciliationRequiredCasDoesNotStopTheRemainingBatch() { + InitialAdmissionBindHold first = hold(3L); + InitialAdmissionBindHold second = hold(4L); + InitialAdmissionBindHoldRepository repository = + Mockito.mock(InitialAdmissionBindHoldRepository.class); + InitialAdmissionBindHoldService service = Mockito.mock(InitialAdmissionBindHoldService.class); + ObjectProvider proofClientProvider = mockProvider(); + when(repository.findNonterminal(32)).thenReturn(List.of(first, second)); + when(proofClientProvider.getIfAvailable()).thenReturn(null); + doThrow(new IllegalStateException("stale reconciliation CAS")) + .when(service) + .requireReconciliation(first.holdId(), "GS_OWNER_READ_UNAVAILABLE"); + + InitialAdmissionBindHoldReconciler reconciler = + new InitialAdmissionBindHoldReconciler(repository, service, proofClientProvider); + reconciler.reconcilePendingHolds(); + + verify(service).requireReconciliation(first.holdId(), "GS_OWNER_READ_UNAVAILABLE"); + verify(service).requireReconciliation(second.holdId(), "GS_OWNER_READ_UNAVAILABLE"); + } + + private static InitialAdmissionBindHold hold(long suffix) { + String uuidSuffix = String.format("%012d", suffix); + Instant now = Instant.now(); + return new InitialAdmissionBindHold( + "00000000-0000-0000-0000-" + uuidSuffix, + "10000000-0000-0000-0000-" + uuidSuffix, + 42L, + "20000000-0000-0000-0000-000000000001", + "30000000-0000-0000-0000-000000000002", + "SHARED", + 101L, + 11L, + 7L, + "initial-admission-" + suffix, + "a".repeat(64), + true, + 1L, + "PENDING", + now.plusSeconds(300), + null, + null, + null, + null, + null, + now, + now, + null, + 0L); + } + + @SuppressWarnings("unchecked") + private static ObjectProvider mockProvider() { + return (ObjectProvider) + Mockito.mock(ObjectProvider.class); + } +} diff --git a/services/world-management-service/src/test/java/unit/net/firedevops/firemud/worldmanagement/service/impl/InitialAdmissionBindHoldServiceImplTest.java b/services/world-management-service/src/test/java/unit/net/firedevops/firemud/worldmanagement/service/impl/InitialAdmissionBindHoldServiceImplTest.java index 2143e36d69..1f26c1f791 100644 --- a/services/world-management-service/src/test/java/unit/net/firedevops/firemud/worldmanagement/service/impl/InitialAdmissionBindHoldServiceImplTest.java +++ b/services/world-management-service/src/test/java/unit/net/firedevops/firemud/worldmanagement/service/impl/InitialAdmissionBindHoldServiceImplTest.java @@ -150,8 +150,7 @@ void pendingOwnerReadMovesHoldToBlockingReconciliationRequired() { when(holdRepository.markReconciliationRequired(any(), Mockito.eq("GS_OWNER_PENDING"), any())) .thenAnswer(invocation -> Optional.of(withStatus(hold, "RECONCILIATION_REQUIRED", 1L))); - var result = - service.reconcileOwnerProof(HOLD_ID, ownerProof(Outcome.PENDING, false, false, null)); + var result = service.reconcileOwnerProof(HOLD_ID, ownerProof(Outcome.PENDING, false, null)); assertEquals("RECONCILIATION_REQUIRED", result.status()); verify(holdRepository, never()) @@ -167,9 +166,28 @@ void committedReadbackRequiresExactPointerAuditDigest() { any(), Mockito.eq("GS_OWNER_TERMINAL_PROOF_INCOMPLETE"), any())) .thenAnswer(invocation -> Optional.of(withStatus(hold, "RECONCILIATION_REQUIRED", 1L))); + var result = + service.reconcileOwnerProof(HOLD_ID, ownerProof(Outcome.COMMITTED, true, "c".repeat(64))); + + assertEquals("RECONCILIATION_REQUIRED", result.status()); + verify(worldInstanceRepository, never()) + .findByTenantIdAndGameInstanceIdForUpdate(TENANT_ID, GAME_INSTANCE_ID); + verify(holdRepository, never()) + .recordTerminalProof(any(), any(), any(), any(), any(), any(), any()); + } + + @Test + void committedReadbackRequiresTheFirstPointerVersionExactly() { + InitialAdmissionBindHold hold = pendingHold(); + when(holdRepository.findByHoldId(HOLD_ID)).thenReturn(Optional.of(hold)); + when(holdRepository.findByHoldIdForUpdate(HOLD_ID)).thenReturn(Optional.of(hold)); + when(holdRepository.markReconciliationRequired( + any(), Mockito.eq("GS_OWNER_TERMINAL_PROOF_INCOMPLETE"), any())) + .thenAnswer(invocation -> Optional.of(withStatus(hold, "RECONCILIATION_REQUIRED", 1L))); + var result = service.reconcileOwnerProof( - HOLD_ID, ownerProof(Outcome.COMMITTED, true, true, "c".repeat(64))); + HOLD_ID, ownerProof(Outcome.COMMITTED, true, REQUEST_DIGEST, 2L)); assertEquals("RECONCILIATION_REQUIRED", result.status()); verify(worldInstanceRepository, never()) @@ -202,18 +220,16 @@ void exactCommittedPointerAndAuditReadbackTerminalizesAndReplays() { InitialAdmissionBindHold committed = withTerminalProof( pending, - ownerProof(Outcome.COMMITTED, true, true, REQUEST_DIGEST), + ownerProof(Outcome.COMMITTED, true, REQUEST_DIGEST), invocation.getArgument(3)); persisted.set(committed); return Optional.of(committed); }); var first = - service.reconcileOwnerProof( - HOLD_ID, ownerProof(Outcome.COMMITTED, true, true, REQUEST_DIGEST)); + service.reconcileOwnerProof(HOLD_ID, ownerProof(Outcome.COMMITTED, true, REQUEST_DIGEST)); var retry = - service.reconcileOwnerProof( - HOLD_ID, ownerProof(Outcome.COMMITTED, true, true, REQUEST_DIGEST)); + service.reconcileOwnerProof(HOLD_ID, ownerProof(Outcome.COMMITTED, true, REQUEST_DIGEST)); assertEquals("COMMITTED", first.status()); assertEquals(first, retry); @@ -230,8 +246,7 @@ void abortedAttemptRequiresDurableTombstoneAndPreventsFutureCommit() { any(), Mockito.eq("GS_OWNER_TERMINAL_PROOF_INCOMPLETE"), any())) .thenAnswer(invocation -> Optional.of(withStatus(pending, "RECONCILIATION_REQUIRED", 1L))); - var result = - service.reconcileOwnerProof(HOLD_ID, ownerProof(Outcome.ABORTED, false, false, null)); + var result = service.reconcileOwnerProof(HOLD_ID, ownerProof(Outcome.ABORTED, false, null)); assertEquals("RECONCILIATION_REQUIRED", result.status()); verify(holdRepository, never()) @@ -241,7 +256,7 @@ void abortedAttemptRequiresDurableTombstoneAndPreventsFutureCommit() { @Test void exactAbortedTombstoneDoesNotRequirePriorPointerAbsence() { InitialAdmissionBindHold pending = pendingHold(); - InitialAdmissionBindOwnerProof proof = ownerProof(Outcome.ABORTED, false, true, null); + InitialAdmissionBindOwnerProof proof = ownerProof(Outcome.ABORTED, true, null); when(holdRepository.findByHoldId(HOLD_ID)).thenReturn(Optional.of(pending)); when(holdRepository.findByHoldIdForUpdate(HOLD_ID)).thenReturn(Optional.of(pending)); when(worldInstanceRepository.findByTenantIdAndGameInstanceIdForUpdate( @@ -267,6 +282,36 @@ void exactAbortedTombstoneDoesNotRequirePriorPointerAbsence() { any(), Mockito.eq("ABORTED"), any(), any(), Mockito.isNull(), Mockito.isNull(), any()); } + @Test + void repeatedIdenticalOwnerErrorsStillTouchAndRotateBlockedHold() { + InitialAdmissionBindHold blocked = withStatus(pendingHold(), "RECONCILIATION_REQUIRED", 1L); + when(holdRepository.findByHoldId(HOLD_ID)).thenReturn(Optional.of(blocked)); + when(holdRepository.markReconciliationRequired(any(), Mockito.eq("GS_OWNER_PENDING"), any())) + .thenAnswer( + invocation -> + Optional.of(withStatus(invocation.getArgument(0), "RECONCILIATION_REQUIRED", 2L))); + + var result = service.reconcileOwnerProof(HOLD_ID, ownerProof(Outcome.PENDING, false, null)); + + assertEquals("RECONCILIATION_REQUIRED", result.status()); + assertEquals(HOLD_ID, result.holdId()); + verify(holdRepository).markReconciliationRequired(any(), Mockito.eq("GS_OWNER_PENDING"), any()); + } + + @Test + void lostReconciliationCompareAndSetRaisesStaleError() { + when(holdRepository.findByHoldIdForUpdate(HOLD_ID)).thenReturn(Optional.of(pendingHold())); + when(holdRepository.markReconciliationRequired(any(), Mockito.eq("GS_OWNER_PENDING"), any())) + .thenReturn(Optional.empty()); + + IllegalStateException error = + assertThrows( + IllegalStateException.class, + () -> service.requireReconciliation(HOLD_ID, "GS_OWNER_PENDING")); + + assertTrue(error.getMessage().startsWith("INITIAL_ADMISSION_BIND_HOLD_STALE:")); + } + private InitialAdmissionBindHoldRequest request() { return new InitialAdmissionBindHoldRequest( TENANT_ID, @@ -322,10 +367,13 @@ private InitialAdmissionBindHold pendingHold() { } private InitialAdmissionBindOwnerProof ownerProof( - Outcome outcome, - boolean attemptPointerAbsent, - boolean futureCommitPrevented, - String auditDigest) { + Outcome outcome, boolean futureCommitPrevented, String auditDigest) { + return ownerProof( + outcome, futureCommitPrevented, auditDigest, outcome == Outcome.COMMITTED ? 1L : 0L); + } + + private InitialAdmissionBindOwnerProof ownerProof( + Outcome outcome, boolean futureCommitPrevented, String auditDigest, long pointerVersion) { return new InitialAdmissionBindOwnerProof( outcome, HOLD_ID, @@ -343,9 +391,8 @@ private InitialAdmissionBindOwnerProof ownerProof( 17L, "gs-ledger-100", outcome == Outcome.COMMITTED ? "audit-100" : null, - outcome == Outcome.COMMITTED ? 1L : 0L, + pointerVersion, auditDigest, - attemptPointerAbsent, futureCommitPrevented); } diff --git a/services/world-management-service/src/test/java/unit/net/firedevops/firemud/worldmanagement/service/impl/WorldLifecycleCommandServiceImplTest.java b/services/world-management-service/src/test/java/unit/net/firedevops/firemud/worldmanagement/service/impl/WorldLifecycleCommandServiceImplTest.java index d7ba28c7e4..b360b2394c 100644 --- a/services/world-management-service/src/test/java/unit/net/firedevops/firemud/worldmanagement/service/impl/WorldLifecycleCommandServiceImplTest.java +++ b/services/world-management-service/src/test/java/unit/net/firedevops/firemud/worldmanagement/service/impl/WorldLifecycleCommandServiceImplTest.java @@ -10,6 +10,7 @@ import static org.mockito.ArgumentMatchers.anyString; import static org.mockito.Mockito.doThrow; import static org.mockito.Mockito.mock; +import static org.mockito.Mockito.times; import static org.mockito.Mockito.verify; import static org.mockito.Mockito.when; @@ -31,6 +32,9 @@ import net.firedevops.firemud.worldmanagement.config.WorldProperties; import net.firedevops.firemud.worldmanagement.dto.PreparedWorldInstanceRequest; import net.firedevops.firemud.worldmanagement.entity.Room; +import net.firedevops.firemud.worldmanagement.entity.RoomExit; +import net.firedevops.firemud.worldmanagement.entity.RoomInstance; +import net.firedevops.firemud.worldmanagement.entity.RoomInstanceExit; import net.firedevops.firemud.worldmanagement.entity.WorldInstance; import net.firedevops.firemud.worldmanagement.entity.Zone; import net.firedevops.firemud.worldmanagement.repository.RegionInstanceRepository; @@ -44,6 +48,7 @@ import net.firedevops.firemud.worldmanagement.repository.ZoneRepository; import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.Test; +import org.mockito.ArgumentCaptor; import org.springframework.transaction.support.TransactionCallback; import org.springframework.transaction.support.TransactionOperations; @@ -161,13 +166,30 @@ public T execute(TransactionCallback action) { } @Test - void prepareWorldInstancePersistsPreparingLifecycle() { + void prepareWorldInstanceMaterializesSeededRoomIdentityAndActivatesOwnerLifecycle() { + Room starterRoom = templateRoom(42L, 1021L); + starterRoom.setName("Candle-lit Antechamber"); + Room secondaryRoom = templateRoom(42L, 2045L); + secondaryRoom.setName("Smith's Annex"); + when(roomRepository.findByTenantIdAndVersionIdOrderByIdAsc(42L, 11L)) + .thenReturn(List.of(starterRoom, secondaryRoom)); + when(roomExitRepository.findByTenantIdAndVersionIdOrderByIdAsc(42L, 11L)) + .thenReturn( + List.of( + templateExit(42L, 11L, starterRoom, secondaryRoom, "NORTH"), + templateExit(42L, 11L, secondaryRoom, starterRoom, "SOUTH"))); + AtomicReference storedInstance = new AtomicReference<>(); when(worldInstanceRepository.findByTenantIdAndGameInstanceId(42L, 101L)) - .thenReturn(Optional.empty()); + .thenAnswer(invocation -> Optional.ofNullable(storedInstance.get())); when(worldInstanceRepository.save(any(WorldInstance.class))) - .thenAnswer(invocation -> invocation.getArgument(0)); + .thenAnswer( + invocation -> { + WorldInstance worldInstance = invocation.getArgument(0); + storedInstance.set(worldInstance); + return worldInstance; + }); - var snapshot = + var prepared = service.prepareWorldInstance( new PreparedWorldInstanceRequest( 42L, @@ -183,11 +205,42 @@ void prepareWorldInstancePersistsPreparingLifecycle() { "prb:42:11:77", 77L)); - assertEquals("PREPARING", snapshot.status()); - assertEquals(1L, snapshot.lifecycleEpoch()); + assertEquals("PREPARING", prepared.status()); + assertEquals(1L, prepared.lifecycleEpoch()); + assertEquals(42L, storedInstance.get().getTenantId()); + assertEquals(101L, storedInstance.get().getGameInstanceId()); + assertEquals(11L, storedInstance.get().getVersionId()); verify(regionInstanceRepository).save(any()); verify(zoneInstanceRepository).save(any()); - verify(roomInstanceRepository).save(any()); + ArgumentCaptor roomCaptor = ArgumentCaptor.forClass(RoomInstance.class); + verify(roomInstanceRepository, times(2)).save(roomCaptor.capture()); + List rooms = roomCaptor.getAllValues(); + assertEquals( + List.of(1021L, 2045L), rooms.stream().map(RoomInstance::getRoomInstanceRowId).toList()); + assertEquals( + List.of(1021L, 2045L), rooms.stream().map(RoomInstance::getTemplateRoomId).toList()); + assertEquals(List.of(42L, 42L), rooms.stream().map(RoomInstance::getTenantId).toList()); + assertEquals(List.of(101L, 101L), rooms.stream().map(RoomInstance::getGameInstanceId).toList()); + + ArgumentCaptor exitCaptor = ArgumentCaptor.forClass(RoomInstanceExit.class); + verify(roomInstanceExitRepository, times(2)).save(exitCaptor.capture()); + assertEquals( + List.of("NORTH", "SOUTH"), + exitCaptor.getAllValues().stream().map(RoomInstanceExit::getDirection).toList()); + assertEquals( + List.of(1021L, 2045L), + exitCaptor.getAllValues().stream() + .map(exit -> exit.getFromRoomInstance().getRoomInstanceRowId()) + .toList()); + assertEquals( + List.of(2045L, 1021L), + exitCaptor.getAllValues().stream() + .map(exit -> exit.getToRoomInstance().getRoomInstanceRowId()) + .toList()); + + var activated = service.activatePreparedWorldInstance(42L, 101L, prepared.lifecycleEpoch()); + assertEquals("ACTIVE", activated.status()); + assertEquals(2L, activated.lifecycleEpoch()); } @Test @@ -692,6 +745,17 @@ private Room templateRoom(long tenantId, long roomId) { return room; } + private RoomExit templateExit( + long tenantId, long versionId, Room fromRoom, Room toRoom, String direction) { + RoomExit exit = new RoomExit(); + exit.setTenantId(tenantId); + exit.setVersionId(versionId); + exit.setFromRoom(fromRoom); + exit.setToRoom(toRoom); + exit.setDirection(direction); + return exit; + } + private Zone templateZone(long tenantId, long zoneId) { Zone zone = new Zone(); zone.setId(zoneId); diff --git a/services/world-management-service/src/test/java/unit/net/firedevops/firemud/worldmanagement/service/impl/WorldManagementGrpcServiceTest.java b/services/world-management-service/src/test/java/unit/net/firedevops/firemud/worldmanagement/service/impl/WorldManagementGrpcServiceTest.java index f7eac74fc5..efe6e396fb 100644 --- a/services/world-management-service/src/test/java/unit/net/firedevops/firemud/worldmanagement/service/impl/WorldManagementGrpcServiceTest.java +++ b/services/world-management-service/src/test/java/unit/net/firedevops/firemud/worldmanagement/service/impl/WorldManagementGrpcServiceTest.java @@ -185,6 +185,16 @@ void initialAdmissionHoldAcquireDeniesMissingOrWrongWorkloadProof() { wrongPeerResponse.set( invokeInitialBindAcquire(service, initialBindAcquireRequest()))); assertEquals("PERMISSION_DENIED", wrongPeerResponse.get().getError().getCode()); + + AtomicReference wrongNamespaceResponse = + new AtomicReference<>(); + runWithPeer( + new GrpcPeerIdentity( + "spiffe://firemud/ns/other/sa/game-session-service", "other", "game-session-service"), + () -> + wrongNamespaceResponse.set( + invokeInitialBindAcquire(service, initialBindAcquireRequest()))); + assertEquals("PERMISSION_DENIED", wrongNamespaceResponse.get().getError().getCode()); Mockito.verifyNoInteractions(holdService); } From 7a4f92dbbfe912ad6d5a781f9ee6a789447dc987 Mon Sep 17 00:00:00 2001 From: Ben Hook <5009589+benhook1013@users.noreply.github.com> Date: Fri, 2 Oct 2026 22:23:01 +1300 Subject: [PATCH 03/20] Supply explicit transport-test catalog without restoring raw bootstrap authority --- .../MutableDefaultDemoCatalogTest.java | 188 ++++++++++++++++++ .../gamesession/CrossServiceAppHarness.java | 21 ++ .../support/TestGameplayWorldCatalogs.java | 177 +++++++++++++++++ .../GameplayCrossServiceStack.java | 53 +++-- 4 files changed, 427 insertions(+), 12 deletions(-) create mode 100644 services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/support/MutableDefaultDemoCatalogTest.java diff --git a/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/support/MutableDefaultDemoCatalogTest.java b/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/support/MutableDefaultDemoCatalogTest.java new file mode 100644 index 0000000000..234cefe5c7 --- /dev/null +++ b/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/support/MutableDefaultDemoCatalogTest.java @@ -0,0 +1,188 @@ +package unit.net.firedevops.firemud.gamesession.support; + +import static org.assertj.core.api.Assertions.assertThat; +import static org.assertj.core.api.Assertions.assertThatThrownBy; + +import java.util.ArrayList; +import java.util.List; +import java.util.Optional; +import java.util.UUID; +import net.firedevops.firemud.gamesession.command.text.GameplayWorldCatalog; +import net.firedevops.firemud.gamesession.service.GameplayAdmissionPointerAuditEntry; +import net.firedevops.firemud.gamesession.service.GameplayAdmissionPointerAuthorityService; +import net.firedevops.firemud.gamesession.service.GameplayAdmissionPointerMutation; +import net.firedevops.firemud.gamesession.service.GameplayAdmissionPointerSnapshot; +import net.firedevops.firemud.gamesession.support.TestGameplayWorldCatalogs; +import org.junit.jupiter.api.Test; + +class MutableDefaultDemoCatalogTest { + private static final long TENANT_ID = 41L; + private static final long BASELINE_GAME_INSTANCE_ID = 73L; + + @Test + void defaultDemoIsAbsentUntilTheTestBaselineIsEnabled() { + MutablePointerAuthority authority = new MutablePointerAuthority(); + TestGameplayWorldCatalogs.MutableDefaultDemoCatalog fixture = fixture(authority); + GameplayWorldCatalog catalog = fixture.catalog(); + + assertThat(catalog.resolveWorld("demo")).isEmpty(); + + fixture.useDefaultDemo(TENANT_ID, BASELINE_GAME_INSTANCE_ID); + + GameplayWorldCatalog.RealmView realm = + catalog.resolveDefaultRealm(catalog.resolveWorld("demo").orElseThrow()).orElseThrow(); + assertThat(realm.tenantId()).isEqualTo(TENANT_ID); + assertThat(realm.gameInstanceId()).isEqualTo(BASELINE_GAME_INSTANCE_ID); + assertThat(realm.pointerVersion()).isEqualTo(1L); + assertThat(realm.catalogRevision()).isEqualTo(1L); + assertThat(realm.realmId()).isNotNull(); + assertThat(realm.playableStateNamespaceId()).isNotNull(); + assertThat(catalog.hasValidPublicProductionRealm(TENANT_ID)).isTrue(); + } + + @Test + void persistedMatchingPointerTakesPrecedenceOverTheBaselineFallback() { + MutablePointerAuthority authority = new MutablePointerAuthority(); + TestGameplayWorldCatalogs.MutableDefaultDemoCatalog fixture = fixture(authority); + fixture.useDefaultDemo(TENANT_ID, BASELINE_GAME_INSTANCE_ID); + authority.setPointers(List.of(pointer("demo", "production", TENANT_ID, 99L, 8L, 12L))); + + GameplayWorldCatalog.RealmView realm = + fixture + .catalog() + .resolveDefaultRealm(fixture.catalog().resolveWorld("demo").orElseThrow()) + .orElseThrow(); + + assertThat(realm.gameInstanceId()).isEqualTo(99L); + assertThat(realm.pointerVersion()).isEqualTo(8L); + assertThat(realm.catalogRevision()).isEqualTo(12L); + } + + @Test + void clearingTheFallbackRestoresMissingAuthority() { + MutablePointerAuthority authority = new MutablePointerAuthority(); + TestGameplayWorldCatalogs.MutableDefaultDemoCatalog fixture = fixture(authority); + fixture.useDefaultDemo(TENANT_ID, BASELINE_GAME_INSTANCE_ID); + assertThat(fixture.catalog().resolveWorld("demo")).isPresent(); + + fixture.clearDefaultDemo(); + + assertThat(fixture.catalog().resolveWorld("demo")).isEmpty(); + } + + @Test + void incompletePersistedPointerIsNotReplacedByTheFallback() { + MutablePointerAuthority authority = new MutablePointerAuthority(); + TestGameplayWorldCatalogs.MutableDefaultDemoCatalog fixture = fixture(authority); + fixture.useDefaultDemo(TENANT_ID, BASELINE_GAME_INSTANCE_ID); + authority.setPointers( + List.of( + new GameplayAdmissionPointerSnapshot( + "demo", + "Demo World", + "production", + "Live Realm", + TENANT_ID, + 99L, + 8L, + true, + true, + false, + "SHARED", + "ALLOW_NEW", + 12L))); + + assertThatThrownBy(() -> fixture.catalog().resolveWorld("demo")) + .isInstanceOf(IllegalArgumentException.class) + .hasMessage("test catalog pointer is incomplete"); + } + + @Test + void ambiguousPersistedPublicAuthorityIsNotHiddenByTheFallback() { + MutablePointerAuthority authority = new MutablePointerAuthority(); + TestGameplayWorldCatalogs.MutableDefaultDemoCatalog fixture = fixture(authority); + fixture.useDefaultDemo(TENANT_ID, BASELINE_GAME_INSTANCE_ID); + authority.setPointers(List.of(pointer("other", "production", TENANT_ID, 99L, 8L, 12L))); + + assertThatThrownBy(() -> fixture.catalog().resolveWorld("demo")) + .isInstanceOf(IllegalArgumentException.class) + .hasMessage("test catalog requires exactly one visible public production realm per tenant"); + } + + private static TestGameplayWorldCatalogs.MutableDefaultDemoCatalog fixture( + MutablePointerAuthority authority) { + return new TestGameplayWorldCatalogs.MutableDefaultDemoCatalog(authority); + } + + private static GameplayAdmissionPointerSnapshot pointer( + String worldSlug, + String realmSlug, + long tenantId, + long gameInstanceId, + long pointerVersion, + long catalogRevision) { + return new GameplayAdmissionPointerSnapshot( + worldSlug, + worldSlug.equals("demo") ? "Demo World" : "Other World", + realmSlug, + "Live Realm", + tenantId, + gameInstanceId, + pointerVersion, + true, + true, + false, + "SHARED", + "ALLOW_NEW", + catalogRevision, + UUID.nameUUIDFromBytes( + (worldSlug + ":realm").getBytes(java.nio.charset.StandardCharsets.UTF_8)), + UUID.nameUUIDFromBytes( + (worldSlug + ":namespace").getBytes(java.nio.charset.StandardCharsets.UTF_8))); + } + + private static final class MutablePointerAuthority + implements GameplayAdmissionPointerAuthorityService { + private List pointers = List.of(); + + private void setPointers(List pointers) { + this.pointers = new ArrayList<>(pointers); + } + + @Override + public List listPointers() { + return List.copyOf(pointers); + } + + @Override + public Optional findPointer( + long tenantId, String worldSlug, String realmSlug) { + return pointers.stream() + .filter(pointer -> pointer.tenantId() == tenantId) + .filter(pointer -> pointer.worldSlug().equals(worldSlug)) + .filter(pointer -> pointer.realmSlug().equals(realmSlug)) + .findFirst(); + } + + @Override + public List listByRuntimeTarget( + long tenantId, long gameInstanceId) { + return pointers.stream() + .filter(pointer -> pointer.tenantId() == tenantId) + .filter(pointer -> pointer.gameInstanceId() == gameInstanceId) + .toList(); + } + + @Override + public GameplayAdmissionPointerSnapshot upsertPointer( + GameplayAdmissionPointerMutation mutation) { + throw new UnsupportedOperationException("catalog tests do not mutate persisted pointers"); + } + + @Override + public List listPointerAudit( + long tenantId, String worldSlug, String realmSlug) { + return List.of(); + } + } +} diff --git a/services/game-session-service/src/testFixtures/java/net/firedevops/firemud/gamesession/CrossServiceAppHarness.java b/services/game-session-service/src/testFixtures/java/net/firedevops/firemud/gamesession/CrossServiceAppHarness.java index d2fc5c62ff..61133601f2 100644 --- a/services/game-session-service/src/testFixtures/java/net/firedevops/firemud/gamesession/CrossServiceAppHarness.java +++ b/services/game-session-service/src/testFixtures/java/net/firedevops/firemud/gamesession/CrossServiceAppHarness.java @@ -21,10 +21,13 @@ import net.firedevops.firemud.common.settings.SharedSettingsAuthorityReader; import net.firedevops.firemud.gamesession.client.AutomationScriptingClient; import net.firedevops.firemud.gamesession.client.ModerationPolicyClient; +import net.firedevops.firemud.gamesession.command.text.GameplayWorldCatalog; import net.firedevops.firemud.gamesession.dto.GameInstanceDto; import net.firedevops.firemud.gamesession.dto.StartSessionRequest; import net.firedevops.firemud.gamesession.service.GameInstanceService; +import net.firedevops.firemud.gamesession.service.GameplayAdmissionPointerAuthorityService; import net.firedevops.firemud.gamesession.service.RunOwnedInitialLaunchResult; +import net.firedevops.firemud.gamesession.support.TestGameplayWorldCatalogs; import org.springframework.beans.factory.annotation.Qualifier; import org.springframework.boot.builder.SpringApplicationBuilder; import org.springframework.boot.test.context.TestConfiguration; @@ -362,6 +365,24 @@ public RunOwnedInitialLaunchResult startRunOwnedInitialLaunch(StartSessionReques } } + /** Test-only catalog authority for the default demo cross-service transport fixture. */ + @TestConfiguration + public static class DefaultDemoCatalogTestOverrides { + @Bean + @Primary + TestGameplayWorldCatalogs.MutableDefaultDemoCatalog defaultDemoCatalogFixture( + GameplayAdmissionPointerAuthorityService pointerAuthority) { + return new TestGameplayWorldCatalogs.MutableDefaultDemoCatalog(pointerAuthority); + } + + @Bean + @Primary + GameplayWorldCatalog defaultDemoTestGameplayWorldCatalog( + TestGameplayWorldCatalogs.MutableDefaultDemoCatalog fixture) { + return fixture.catalog(); + } + } + public static final class GameLogicHolder { private final ConfigurableApplicationContext context; private final int grpcPort; diff --git a/services/game-session-service/src/testFixtures/java/net/firedevops/firemud/gamesession/support/TestGameplayWorldCatalogs.java b/services/game-session-service/src/testFixtures/java/net/firedevops/firemud/gamesession/support/TestGameplayWorldCatalogs.java index d9dd2b3cf1..39881475c4 100644 --- a/services/game-session-service/src/testFixtures/java/net/firedevops/firemud/gamesession/support/TestGameplayWorldCatalogs.java +++ b/services/game-session-service/src/testFixtures/java/net/firedevops/firemud/gamesession/support/TestGameplayWorldCatalogs.java @@ -1,10 +1,20 @@ package net.firedevops.firemud.gamesession.support; import java.util.ArrayList; +import java.util.Comparator; +import java.util.HashMap; +import java.util.HashSet; +import java.util.LinkedHashMap; import java.util.List; +import java.util.Map; import java.util.Objects; +import java.util.Set; +import java.util.UUID; +import java.util.concurrent.atomic.AtomicReference; import net.firedevops.firemud.common.gameplay.GameplayCatalogProperties; import net.firedevops.firemud.gamesession.command.text.GameplayWorldCatalog; +import net.firedevops.firemud.gamesession.service.GameplayAdmissionPointerAuthorityService; +import net.firedevops.firemud.gamesession.service.GameplayAdmissionPointerSnapshot; public final class TestGameplayWorldCatalogs { private TestGameplayWorldCatalogs() {} @@ -14,6 +24,173 @@ public static GameplayWorldCatalog fromProperties(GameplayCatalogProperties prop return GameplayWorldCatalog.forWorldSupplier(() -> toWorldViews(properties.getWorlds())); } + /** + * Test-only catalog seam for cross-service transport fixtures that need a healthy demo route + * without claiming that a World-owned initial admission bind occurred. + */ + public static final class MutableDefaultDemoCatalog { + private final GameplayAdmissionPointerAuthorityService pointerAuthority; + private final AtomicReference defaultDemo = + new AtomicReference<>(); + + public MutableDefaultDemoCatalog(GameplayAdmissionPointerAuthorityService pointerAuthority) { + this.pointerAuthority = + Objects.requireNonNull(pointerAuthority, "pointerAuthority must not be null"); + } + + public GameplayWorldCatalog catalog() { + return GameplayWorldCatalog.forWorldSupplier(this::worlds); + } + + public void useDefaultDemo(long tenantId, long gameInstanceId) { + if (tenantId <= 0 || gameInstanceId <= 0) { + throw new IllegalArgumentException( + "test demo tenant and game instance IDs must be positive"); + } + defaultDemo.set( + new GameplayAdmissionPointerSnapshot( + "demo", + "Demo World", + "production", + "Live Realm", + tenantId, + gameInstanceId, + 1L, + true, + true, + false, + "SHARED", + "ALLOW_NEW", + 1L, + stableId("realm", tenantId, "demo", "production"), + stableId("namespace", tenantId, "demo", "production"))); + } + + public void clearDefaultDemo() { + defaultDemo.set(null); + } + + private List worlds() { + List pointers = + new ArrayList<>(pointerAuthority.listPointers()); + GameplayAdmissionPointerSnapshot fallback = defaultDemo.get(); + if (fallback != null + && pointers.stream() + .noneMatch( + pointer -> + pointer.tenantId() == fallback.tenantId() + && pointer.worldSlug().equals(fallback.worldSlug()) + && pointer.realmSlug().equals(fallback.realmSlug()))) { + pointers.add(fallback); + } + return fromPointers(pointers); + } + } + + private static List fromPointers( + List pointers) { + Map>> grouped = + new LinkedHashMap<>(); + Map displayNames = new HashMap<>(); + Map publicRealmCounts = new HashMap<>(); + Set realmIds = new HashSet<>(); + pointers.forEach(TestGameplayWorldCatalogs::requireComplete); + List orderedPointers = + pointers.stream() + .sorted( + Comparator.comparing(GameplayAdmissionPointerSnapshot::worldSlug) + .thenComparing(GameplayAdmissionPointerSnapshot::realmSlug) + .thenComparingLong(GameplayAdmissionPointerSnapshot::tenantId)) + .toList(); + for (GameplayAdmissionPointerSnapshot pointer : orderedPointers) { + if (!realmIds.add(pointer.realmId())) { + throw new IllegalArgumentException("test catalog contains a duplicate realm ID"); + } + if (pointer.visible() && pointer.publicProductionRealm()) { + publicRealmCounts.merge(pointer.tenantId(), 1L, Long::sum); + } + grouped + .computeIfAbsent(pointer.worldSlug(), ignored -> new LinkedHashMap<>()) + .computeIfAbsent(pointer.realmSlug(), ignored -> new ArrayList<>()) + .add(pointer); + displayNames.putIfAbsent(pointer.worldSlug(), pointer.worldDisplayName()); + } + Set tenants = + pointers.stream() + .map(GameplayAdmissionPointerSnapshot::tenantId) + .collect(java.util.stream.Collectors.toSet()); + for (long tenantId : tenants) { + if (publicRealmCounts.getOrDefault(tenantId, 0L) != 1L) { + throw new IllegalArgumentException( + "test catalog requires exactly one visible public production realm per tenant"); + } + } + return grouped.entrySet().stream() + .map( + world -> + new GameplayWorldCatalog.WorldView( + world.getKey(), + displayNames.get(world.getKey()), + world.getValue().entrySet().stream() + .map( + realm -> { + if (realm.getValue().size() != 1) { + throw new IllegalArgumentException( + "test catalog contains a duplicate world/realm selector"); + } + return toRealmView(realm.getValue().getFirst()); + }) + .toList())) + .toList(); + } + + private static void requireComplete(GameplayAdmissionPointerSnapshot pointer) { + if (pointer == null + || pointer.worldSlug() == null + || pointer.worldSlug().isBlank() + || pointer.worldDisplayName() == null + || pointer.worldDisplayName().isBlank() + || pointer.realmSlug() == null + || pointer.realmSlug().isBlank() + || pointer.realmDisplayName() == null + || pointer.realmDisplayName().isBlank() + || pointer.tenantId() <= 0 + || pointer.gameInstanceId() <= 0 + || pointer.pointerVersion() <= 0 + || pointer.catalogRevision() <= 0 + || pointer.realmId() == null + || pointer.playableStateNamespaceId() == null + || !("SHARED".equals(pointer.stateScope()) || "ISOLATED".equals(pointer.stateScope())) + || pointer.characterCreationPolicy() == null + || pointer.characterCreationPolicy().isBlank()) { + throw new IllegalArgumentException("test catalog pointer is incomplete"); + } + } + + private static GameplayWorldCatalog.RealmView toRealmView( + GameplayAdmissionPointerSnapshot pointer) { + return new GameplayWorldCatalog.RealmView( + pointer.realmSlug(), + pointer.realmDisplayName(), + pointer.tenantId(), + pointer.gameInstanceId(), + pointer.pointerVersion(), + pointer.visible(), + pointer.publicProductionRealm(), + pointer.requiresCharacterSelection(), + pointer.stateScope(), + pointer.characterCreationPolicy(), + pointer.catalogRevision(), + pointer.realmId(), + pointer.playableStateNamespaceId()); + } + + private static UUID stableId(String kind, long tenantId, String worldSlug, String realmSlug) { + return UUID.nameUUIDFromBytes( + ("firemud-test-catalog:" + kind + ":" + tenantId + ":" + worldSlug + ":" + realmSlug) + .getBytes(java.nio.charset.StandardCharsets.UTF_8)); + } + private static List toWorldViews( List worlds) { if (worlds == null) { 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 309203b51e..e85974177e 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 @@ -13,6 +13,7 @@ import net.firedevops.firemud.gamesession.repository.RuntimeRegionStatusRepository; import net.firedevops.firemud.gamesession.service.SessionContext; import net.firedevops.firemud.gamesession.service.SessionContextService; +import net.firedevops.firemud.gamesession.support.TestGameplayWorldCatalogs; import net.firedevops.firemud.gamesession.test.GameInstanceTestFixtures; import net.firedevops.firemud.gamesession.test.LookTestFixtures; import net.firedevops.firemud.gamesession.test.stubs.EntityManagementStubServer; @@ -41,6 +42,7 @@ public final class GameplayCrossServiceStack implements AutoCloseable { private final ListFriendPresenceResponse baselineFriendPresenceResponse; private CrossServiceAppHarness.GameLogicHolder gameLogic; private final CrossServiceAppHarness.GameSessionHolder gameSession; + private final TestGameplayWorldCatalogs.MutableDefaultDemoCatalog defaultDemoCatalogFixture; private GameplayCrossServiceStack( AccountRuntimeStubServer accountStub, @@ -51,7 +53,8 @@ private GameplayCrossServiceStack( net.firedevops.firemud.entitymanagement.v1.ListRoomEntitiesResponse baselineRoomEntities, ListFriendPresenceResponse baselineFriendPresenceResponse, CrossServiceAppHarness.GameLogicHolder gameLogic, - CrossServiceAppHarness.GameSessionHolder gameSession) { + CrossServiceAppHarness.GameSessionHolder gameSession, + TestGameplayWorldCatalogs.MutableDefaultDemoCatalog defaultDemoCatalogFixture) { this.accountStub = accountStub; this.gameDesignStub = gameDesignStub; this.worldStub = worldStub; @@ -61,6 +64,7 @@ private GameplayCrossServiceStack( this.baselineFriendPresenceResponse = baselineFriendPresenceResponse; this.gameLogic = gameLogic; this.gameSession = gameSession; + this.defaultDemoCatalogFixture = defaultDemoCatalogFixture; } public static Builder builder() { @@ -69,15 +73,18 @@ public static Builder builder() { public static Builder defaultDemoBuilder( PostgreSQLContainer postgres, GenericContainer redis, long defaultAccountId) { - return builder() - .withPostgres( - postgres.getHost(), - postgres.getMappedPort(5432), - postgres.getDatabaseName(), - postgres.getUsername(), - postgres.getPassword()) - .withRedis(redis.getHost(), redis.getMappedPort(6379)) - .withDefaultAccountId(defaultAccountId); + Builder builder = + builder() + .withPostgres( + postgres.getHost(), + postgres.getMappedPort(5432), + postgres.getDatabaseName(), + postgres.getUsername(), + postgres.getPassword()) + .withRedis(redis.getHost(), redis.getMappedPort(6379)) + .withDefaultAccountId(defaultAccountId); + builder.useDefaultDemoCatalogFixture = true; + return builder; } @SuppressFBWarnings( @@ -186,9 +193,19 @@ public long freshGameplayBaseline( GameInstanceTestFixtures.insertRunningGameInstance( jdbc, tenantId, ownerAccountId, gameTemplateId); seedRuntimeOwnership(tenantId, gameInstanceId); + if (defaultDemoCatalogFixture != null) { + defaultDemoCatalogFixture.useDefaultDemo(tenantId, gameInstanceId); + } return gameInstanceId; } + /** Removes only the test catalog fallback; persisted pointer authority remains untouched. */ + public void clearDefaultDemoCatalogFixture() { + if (defaultDemoCatalogFixture != null) { + defaultDemoCatalogFixture.clearDefaultDemo(); + } + } + private void clearSyntheticAdmissionPointerState(JdbcTemplate jdbc) { // Audit rows are removed first so this remains safe if a future schema adds an FK to the // current pointer row. The world prefix is reserved for this fixture; keep canonical demo and @@ -352,6 +369,7 @@ public static final class Builder { private final Map gameSessionProps = new LinkedHashMap<>(); private Class[] gameLogicConfigs = new Class[0]; private Class[] gameSessionConfigs = new Class[0]; + private boolean useDefaultDemoCatalogFixture; private Builder() {} @@ -439,6 +457,14 @@ public GameplayCrossServiceStack start() throws IOException { socialStub.setFriendPresenceResponse(initialFriendPresenceResponse); } + Class[] selectedGameSessionConfigs = gameSessionConfigs; + if (useDefaultDemoCatalogFixture) { + selectedGameSessionConfigs = + java.util.Arrays.copyOf(gameSessionConfigs, gameSessionConfigs.length + 1); + selectedGameSessionConfigs[gameSessionConfigs.length] = + CrossServiceAppHarness.DefaultDemoCatalogTestOverrides.class; + } + CrossServiceAppHarness.GameLogicHolder gameLogic = CrossServiceAppHarness.startGameLogic( 0, @@ -472,7 +498,7 @@ public GameplayCrossServiceStack start() throws IOException { } props.putAll(gameSessionProps); }, - gameSessionConfigs); + selectedGameSessionConfigs); return new GameplayCrossServiceStack( accountStub, @@ -483,7 +509,10 @@ public GameplayCrossServiceStack start() throws IOException { initialRoomEntities, initialFriendPresenceResponse, gameLogic, - gameSession); + gameSession, + useDefaultDemoCatalogFixture + ? gameSession.bean(TestGameplayWorldCatalogs.MutableDefaultDemoCatalog.class) + : null); } private void requireConfigured() { From fe4855100df1af70bbf753aa665e2a793a4c6718 Mon Sep 17 00:00:00 2001 From: Ben Hook <5009589+benhook1013@users.noreply.github.com> Date: Fri, 2 Oct 2026 23:51:54 +1300 Subject: [PATCH 04/20] test(gameplay): prove bounded owner bootstrap retry and same-claim restart --- ...e-session-runtime-and-tick-coordination.md | 2 +- ...nitialAdmissionFixtureCoordinatorTest.java | 174 +++++++++++++++++- 2 files changed, 173 insertions(+), 3 deletions(-) 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 5f32d4a3f3..cf74dc6f18 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 @@ -8,7 +8,7 @@ This is a non-normative implementation tracker for Game Session runtime and tick This tracker consolidates the live Game Session execution substrate by capability. The recorded boundaries describe current implementation status and bounded follow-up work. -The initial-admission/catalog foundation includes pointer and audit persistence for a separately advancing 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. Durable initial-bind intent and pointer/audit commit/abort proof components, a method-specific Game Session owner-proof read connected to World’s hold reconciler, and an opt-in run-owned local Compose coordinator are wired. The coordinator validates a read-only fixture capability, resumes the descriptor-validated Game Session launch under its stable operation identity, persists initial-bind intent before requesting the World hold, and completes the owner transaction through authenticated proof. This does not implement the strict Account `JOIN` validation-through-commit gate, production activation, or generalized runtime-ID migration; default startup remains closed, and configured seed validation does not create startup authority rows without World-owned 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, covering unit proof and compilation of PostgreSQL migration tests. Cross-service PostgreSQL race/restart and live Compose execution proof are not claimed; ambiguous outcomes continue to fence World termination. See the [Game Session API status](../../architecture/microservices/game-session-service/api-contracts.md#initial-admission-bind) and canonical [World contract](../../architecture/microservices/world-management-service/api-contracts.md#initial-admission-bind-hold-contract). +The initial-admission/catalog foundation includes pointer and audit persistence for a separately advancing 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. Durable initial-bind intent and pointer/audit commit/abort proof components, a method-specific Game Session owner-proof read connected to World’s hold reconciler, and an opt-in run-owned local Compose coordinator are wired. The coordinator validates a read-only fixture capability, resumes the descriptor-validated Game Session launch under its stable operation identity, persists initial-bind intent before requesting the World hold, and completes the owner transaction through authenticated proof. This does not implement the strict Account `JOIN` validation-through-commit gate, production activation, or generalized runtime-ID migration; default startup remains closed, and configured seed validation does not create startup authority rows without World-owned 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, covering unit proof and compilation of PostgreSQL migration tests. The coordinator’s retry budget is per process; exhaustion requires an operator-mediated process restart under the same run claim, capability, and operation identity (or operator intervention), keeps World fenced, and does not establish live cross-service restart recovery or automatic generalized abort. A deterministic coordinator orchestration unit test covers budget exhaustion and fresh-coordinator replay under that same identity; it does not prove TLS capability validation, cross-service PostgreSQL races/restart, or live Compose execution. Ambiguous outcomes continue to fence World termination. See the [Game Session API status](../../architecture/microservices/game-session-service/api-contracts.md#initial-admission-bind) and canonical [World contract](../../architecture/microservices/world-management-service/api-contracts.md#initial-admission-bind-hold-contract). 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). 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 index c30a776360..1e136ea6fb 100644 --- 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 @@ -8,18 +8,24 @@ import static org.mockito.ArgumentMatchers.eq; import static org.mockito.Mockito.doAnswer; 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.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.InitialAdmissionBindAttempt.Status; import net.firedevops.firemud.gamesession.entity.InitialAdmissionBindCatalog; @@ -35,11 +41,14 @@ import net.firedevops.firemud.worldmanagement.v1.InitialAdmissionBindHold; import net.firedevops.firemud.worldmanagement.v1.InitialAdmissionBindHoldStatus; import org.junit.jupiter.api.Test; +import org.mockito.ArgumentCaptor; import org.mockito.InOrder; +import org.mockito.MockedStatic; 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 OPERATION_ID = "d2db8478-9c56-42ab-99c2-9fbead6841ba"; 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"); @@ -177,6 +186,154 @@ void disabledCoordinatorDoesNotLoadCapabilityOrCallOwners() { verifyNoInteractions(gameInstanceService, ownerService, worldClient); } + @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); + + // 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()); + 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 = @@ -295,7 +452,7 @@ private static Fixture fixture(InitialAdmissionBindHoldStatus holdStatus) { RunOwnedInitialAdmissionFixtureCoordinator coordinator = new RunOwnedInitialAdmissionFixtureCoordinator( true, - "/unused-for-direct-coordination.json", + CAPABILITY_PATH, RUN_ID, PROJECT_NAME, grpc, @@ -303,7 +460,19 @@ private static Fixture fixture(InitialAdmissionBindHoldStatus holdStatus) { ownerService, worldClient); return new Fixture( - coordinator, capability, gameInstanceService, ownerService, worldClient, request); + coordinator, capability, grpc, gameInstanceService, ownerService, worldClient, request); + } + + private static RunOwnedInitialAdmissionFixtureCoordinator newCoordinator(Fixture fixture) { + return new RunOwnedInitialAdmissionFixtureCoordinator( + true, + CAPABILITY_PATH, + RUN_ID, + PROJECT_NAME, + fixture.grpcProperties, + fixture.gameInstanceService, + fixture.ownerService, + fixture.worldClient); } private static InitialAdmissionBindAttempt attempt( @@ -389,6 +558,7 @@ private static InitialAdmissionBindOwnerProof proof( private record Fixture( RunOwnedInitialAdmissionFixtureCoordinator coordinator, RunOwnedInitialAdmissionFixtureCapability capability, + CommonGrpcClientProperties grpcProperties, GameInstanceService gameInstanceService, InitialAdmissionBindOwnerService ownerService, WorldManagementClient worldClient, From 8c734600a3d58d4d461ca6d1f1bce4965aaaa3df Mon Sep 17 00:00:00 2001 From: Ben Hook <5009589+benhook1013@users.noreply.github.com> Date: Sat, 3 Oct 2026 01:11:06 +1300 Subject: [PATCH 05/20] fix(gameplay): order child migrations after catalog repair --- .../game-session-runtime-and-tick-coordination.md | 2 +- ..._identity.sql => V10__run_owned_initial_launch_identity.sql} | 0 ...r_ledger.sql => V9__initial_admission_bind_owner_ledger.sql} | 0 3 files changed, 1 insertion(+), 1 deletion(-) rename services/game-session-service/src/main/resources/db/migration/{V9__run_owned_initial_launch_identity.sql => V10__run_owned_initial_launch_identity.sql} (100%) rename services/game-session-service/src/main/resources/db/migration/{V8__initial_admission_bind_owner_ledger.sql => V9__initial_admission_bind_owner_ledger.sql} (100%) 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 332e01a6d0..7342fe764d 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 @@ -42,7 +42,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 (see [Game Session API implementation status](../../architecture/microservices/game-session-service/api-contracts.md#implementation-status)); lease-owner forwarding for independently partitioned regions is not | `proven`: [GameSessionWebSocketHandlerTest](../../../services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/websocket/GameSessionWebSocketHandlerTest.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) cover the shipped front-door and routing seams | [Game Session API contracts](../../architecture/microservices/game-session-service/api-contracts.md); [Game Session runtime/data](../../architecture/microservices/game-session-service/runtime-and-data.md); [reconnection](../../architecture/system-architecture-reconnection.md) | [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) | [GameSessionWebSocketHandlerTest](../../../services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/websocket/GameSessionWebSocketHandlerTest.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); [GameSessionGrpcServiceTest](../../../services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/service/impl/GameSessionGrpcServiceTest.java) | `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 API contract requires front-end-to-lease-owner forwarding to be fenced, with retry/ambiguity handling. The current owner boundary is game-instance scoped and does not implement that forwarding or true region partitioning; no new design decision is recorded. | -| Initial-admission pointer bootstrap and owner readback | `partial`: durable catalog/intent and pointer/audit commit/abort proof, typed owner-proof receiver/client, run-owned launch resume, and the opt-in local Compose fixture coordinator are wired; the general `StartSession` retry path is not claimed | `in progress`: focused Game Session owner tests passed; cross-service PostgreSQL race/restart and live Compose proof are not claimed | [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); [run-owned player-flow smoke boundary](../../architecture/system-architecture-testing.md#player-flow-smoke-and-reset-boundaries) | [DatabaseInitialAdmissionBindOwnerService.java](../../../services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/service/impl/DatabaseInitialAdmissionBindOwnerService.java); [RunOwnedInitialAdmissionFixtureCoordinator.java](../../../services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/data/RunOwnedInitialAdmissionFixtureCoordinator.java); [RunOwnedInitialAdmissionFixtureCapability.java](../../../services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/data/RunOwnedInitialAdmissionFixtureCapability.java); [GameInstanceServiceImpl.java](../../../services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/service/impl/GameInstanceServiceImpl.java); [V8 initial-admission owner ledger](../../../services/game-session-service/src/main/resources/db/migration/V8__initial_admission_bind_owner_ledger.sql); [GetInitialAdmissionBindProof](../../../protos/game-session/v1/game_session_service.proto); [InitialAdmissionBindOwnerReadWorkloadGuard.java](../../../services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/service/impl/InitialAdmissionBindOwnerReadWorkloadGuard.java); [GrpcGameSessionInitialAdmissionBindProofClient.java](../../../services/world-management-service/src/main/java/net/firedevops/firemud/worldmanagement/client/GrpcGameSessionInitialAdmissionBindProofClient.java) | [InitialAdmissionBindServiceTest.java](../../../services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/service/impl/InitialAdmissionBindServiceTest.java); [InitialAdmissionBindOwnerReadTest.java](../../../services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/service/impl/InitialAdmissionBindOwnerReadTest.java); [RunOwnedInitialAdmissionFixtureCapabilityTest.java](../../../services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/data/RunOwnedInitialAdmissionFixtureCapabilityTest.java); [RunOwnedInitialAdmissionFixtureCoordinatorTest.java](../../../services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/data/RunOwnedInitialAdmissionFixtureCoordinatorTest.java); [GameInstanceServiceImplTest.java](../../../services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/service/impl/GameInstanceServiceImplTest.java); [GrpcGameSessionInitialAdmissionBindProofClientTest.java](../../../services/world-management-service/src/test/java/unit/net/firedevops/firemud/worldmanagement/client/GrpcGameSessionInitialAdmissionBindProofClientTest.java); [InitialAdmissionBindPostgresIntegrationTest.java](../../../services/game-session-service/src/test/java/integration/net/firedevops/firemud/gamesession/service/InitialAdmissionBindPostgresIntegrationTest.java) | World owns the separate hold and termination fence; see the [World runtime tracker](./world-runtime-and-movement.md) | The bounded local Compose coordinator does not complete the strict Account `JOIN` gate, production activation, or generalized runtime-ID migration. General `StartSession` retry integration and live cross-service PostgreSQL restart proof remain open; no ambiguous result releases World termination. | +| Initial-admission pointer bootstrap and owner readback | `partial`: durable catalog/intent and pointer/audit commit/abort proof, typed owner-proof receiver/client, run-owned launch resume, and the opt-in local Compose fixture coordinator are wired; the general `StartSession` retry path is not claimed | `in progress`: focused Game Session owner tests passed; cross-service PostgreSQL race/restart and live Compose proof are not claimed | [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); [run-owned player-flow smoke boundary](../../architecture/system-architecture-testing.md#player-flow-smoke-and-reset-boundaries) | [DatabaseInitialAdmissionBindOwnerService.java](../../../services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/service/impl/DatabaseInitialAdmissionBindOwnerService.java); [RunOwnedInitialAdmissionFixtureCoordinator.java](../../../services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/data/RunOwnedInitialAdmissionFixtureCoordinator.java); [RunOwnedInitialAdmissionFixtureCapability.java](../../../services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/data/RunOwnedInitialAdmissionFixtureCapability.java); [GameInstanceServiceImpl.java](../../../services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/service/impl/GameInstanceServiceImpl.java); [V9 initial-admission owner ledger](../../../services/game-session-service/src/main/resources/db/migration/V9__initial_admission_bind_owner_ledger.sql); [GetInitialAdmissionBindProof](../../../protos/game-session/v1/game_session_service.proto); [InitialAdmissionBindOwnerReadWorkloadGuard.java](../../../services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/service/impl/InitialAdmissionBindOwnerReadWorkloadGuard.java); [GrpcGameSessionInitialAdmissionBindProofClient.java](../../../services/world-management-service/src/main/java/net/firedevops/firemud/worldmanagement/client/GrpcGameSessionInitialAdmissionBindProofClient.java) | [InitialAdmissionBindServiceTest.java](../../../services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/service/impl/InitialAdmissionBindServiceTest.java); [InitialAdmissionBindOwnerReadTest.java](../../../services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/service/impl/InitialAdmissionBindOwnerReadTest.java); [RunOwnedInitialAdmissionFixtureCapabilityTest.java](../../../services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/data/RunOwnedInitialAdmissionFixtureCapabilityTest.java); [RunOwnedInitialAdmissionFixtureCoordinatorTest.java](../../../services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/data/RunOwnedInitialAdmissionFixtureCoordinatorTest.java); [GameInstanceServiceImplTest.java](../../../services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/service/impl/GameInstanceServiceImplTest.java); [GrpcGameSessionInitialAdmissionBindProofClientTest.java](../../../services/world-management-service/src/test/java/unit/net/firedevops/firemud/worldmanagement/client/GrpcGameSessionInitialAdmissionBindProofClientTest.java); [InitialAdmissionBindPostgresIntegrationTest.java](../../../services/game-session-service/src/test/java/integration/net/firedevops/firemud/gamesession/service/InitialAdmissionBindPostgresIntegrationTest.java) | World owns the separate hold and termination fence; see the [World runtime tracker](./world-runtime-and-movement.md) | The bounded local Compose coordinator does not complete the strict Account `JOIN` gate, production activation, or generalized runtime-ID migration. General `StartSession` retry integration and live cross-service PostgreSQL restart proof remain open; no ambiguous result releases World termination. | | `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/services/game-session-service/src/main/resources/db/migration/V9__run_owned_initial_launch_identity.sql b/services/game-session-service/src/main/resources/db/migration/V10__run_owned_initial_launch_identity.sql similarity index 100% rename from services/game-session-service/src/main/resources/db/migration/V9__run_owned_initial_launch_identity.sql rename to services/game-session-service/src/main/resources/db/migration/V10__run_owned_initial_launch_identity.sql diff --git a/services/game-session-service/src/main/resources/db/migration/V8__initial_admission_bind_owner_ledger.sql b/services/game-session-service/src/main/resources/db/migration/V9__initial_admission_bind_owner_ledger.sql similarity index 100% rename from services/game-session-service/src/main/resources/db/migration/V8__initial_admission_bind_owner_ledger.sql rename to services/game-session-service/src/main/resources/db/migration/V9__initial_admission_bind_owner_ledger.sql From c0f3db884da1f8472fe01c03b35a39cb54751565 Mon Sep 17 00:00:00 2001 From: Ben Hook <5009589+benhook1013@users.noreply.github.com> Date: Sat, 3 Oct 2026 02:19:40 +1300 Subject: [PATCH 06/20] fix(gameplay): strengthen initial-admission fixtures and proof records --- .../system-architecture-multi-tenancy.md | 3 +- ...e-session-runtime-and-tick-coordination.md | 5 +- .../world-runtime-and-movement.md | 5 +- ...wnedInitialAdmissionFixtureCapability.java | 2 +- ...InitialAdmissionBindAttemptRepository.java | 8 +- ...lAdmissionBindPostgresIntegrationTest.java | 2 +- ...dInitialLaunchPostgresIntegrationTest.java | 73 ++++++++++----- .../CrossServiceAppHarnessTest.java | 90 +++++++++++++++++++ ...InitialAdmissionFixtureCapabilityTest.java | 17 +++- .../gamesession/data/TestDataSeederTest.java | 4 - .../MutableDefaultDemoCatalogTest.java | 15 ++++ .../gamesession/CrossServiceAppHarness.java | 38 +++++++- .../support/TestGameplayWorldCatalogs.java | 3 +- ...essionInitialAdmissionBindProofClient.java | 2 +- .../repository/RoomRepository.java | 31 ++++++- .../InitialAdmissionBindHoldReconciler.java | 4 +- ...RoomRepositoryPostgresIntegrationTest.java | 5 +- 17 files changed, 250 insertions(+), 57 deletions(-) create mode 100644 services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/CrossServiceAppHarnessTest.java diff --git a/design/architecture/system-architecture-multi-tenancy.md b/design/architecture/system-architecture-multi-tenancy.md index 96e34fc46f..3dfbaaf974 100644 --- a/design/architecture/system-architecture-multi-tenancy.md +++ b/design/architecture/system-architecture-multi-tenancy.md @@ -14,7 +14,8 @@ The complete playtest initialization and lifecycle contract is owned by [ADR 013 ## Implementation Status -The realm-catalog, admission-pointer, realm-local character, explicit first-join, and quota-boundary contracts below are normative target behavior. Current runtime proof is partial: `IssueConnectToken` and text `PLAY` consume the current Account membership adapter evidence `membershipExists`, `gameplayAdmissionAllowed`, `membershipVersion`, and `evaluatedAt`, and admit only when the membership and admission flags are true. Text `PLAY` validates the applicable private/playtest realm grant; `IssueConnectToken` checks the selected pointer/visibility and membership inputs but does not yet validate that applicable grant, so token grant validation remains an incomplete implementation/proof gap. The adapter has no lifecycle-state field. The obsolete implicit membership-writer surface has been removed; the membership-generation live reread at connect-token issuance is not implemented; pointer updates still use a read-then-write check with separate pointer/audit/prepared-execution writes; scoped-role population and tenant switching are not fully implemented/proved; authoritative entitlement freshness plus complete owning-service quota enforcement remain incomplete; and broader authority-generation claims, durable projections, and enforcement remain incomplete across issuer, account, tenant, and membership scopes. Explicit `JOIN`/`Join & Play` remains unimplemented, so the first-join flow remains target-state only. Playtest fork creation, reset, expiry automation, owner manifests, and lifecycle routes are also not implemented or end-to-end proved; this status does not weaken the target namespace and isolation rules above. Current Game Session bootstrap/reconnect context remains on the implementation-local `sessionctx:*` family, including the unscoped bootstrap key `sessionctx:session::context` and the tenant-scoped keys `sessionctx:::context`, `sessionctx::identity:::context`, and `sessionctx::identity::name::context`; these old per-instance identity keys and the current `{tenantId, gameInstanceId, characterId}` uniqueness are implementation drift. The target-only `session:game:{tenantGameplayTag}:...` family uses `{tenantGameplayTag}` as a server-derived, deterministic, injective projection of authoritative `tenantId`, allocated through an authoritative persisted tenant-to-tag mapping with an immutable allocation version. Its character uniqueness projection is keyed by `{tenantId, playableStateNamespaceId, characterId}`; server-derived `playableStateScope` remains binding/routing evidence, while its value/evidence retains `{sessionId, gameInstanceId, bindingGeneration}`. The controller-transfer authority is summarized by [ADR 0132](./decisions/adr-0132-namespace-scoped-single-character-controller.md) and [Session Behavior](./system-architecture-session-behavior.md#namespace-scoped-controller-transfer-session-02). Existing mappings are always reused; a new allocation is committed atomically with uniqueness for both the tenant and tag, and a candidate tag already mapped to another tenant is rejected even when the candidate allocation version differs. Algorithm or encoding-version changes preserve existing mappings and may affect only future tenants. Its concrete encoding and version remain opaque to clients and other services; `tenantId` remains authoritative in APIs and persistence. Required focused proof covers distinct-tenant separation, same-tenant stability across process restart with the persisted assignment/version, concurrent first allocation returning one assignment, rejection of a tag collision across allocation versions, and rejection of an active-binding `bindingRef` whose tenant differs from the requested tenant. No end-to-end proof yet demonstrates these target invariants. The remaining gaps do not change the distinct stable `tenantSlug` and tenant-scoped authored-world `worldSlug` selectors, tenant-local `realmSlug` to durable `realmId` resolution, exact-tenant quota binding, or required `GetAdmissionPointer(tenantId, realmId)` contract. +The realm-catalog, admission-pointer, realm-local character, explicit first-join, and quota-boundary contracts below are normative target behavior. Current runtime proof is partial: `IssueConnectToken` and text `PLAY` consume the current Account membership adapter evidence `membershipExists`, `gameplayAdmissionAllowed`, `membershipVersion`, and `evaluatedAt`, and admit only when the membership and admission flags are true. Text `PLAY` validates the applicable private/playtest realm grant; `IssueConnectToken` checks the selected pointer/visibility and membership inputs but does not yet validate that applicable grant, so token grant validation remains an incomplete implementation/proof gap. The adapter has no lifecycle-state field. The obsolete implicit membership-writer surface has been removed; the membership-generation live reread at connect-token issuance is not implemented; Game Session now stores a positive `catalogRevision` and stable UUID `realmId`/`playableStateNamespaceId` with pointer/audit rows and compare-and-sets pointer version plus catalog revision; initial-admission binding is wired only for the opt-in local Compose fixture, not general `StartSession`, strict `JOIN`, or production startup (see the [Game Session runtime status](../project-management/implementation-tracking/game-session-runtime-and-tick-coordination.md#capability-status)); scoped-role population and tenant switching are not fully implemented/proved; authoritative entitlement freshness plus complete owning-service quota enforcement remain incomplete; and broader authority-generation claims, durable projections, and enforcement remain incomplete across issuer, account, tenant, and membership scopes. Explicit `JOIN`/`Join & Play` remains unimplemented, so the first-join flow remains target-state only. Playtest fork creation, reset, expiry automation, owner manifests, and lifecycle routes are also not implemented or end-to-end proved; this status does not weaken the target namespace and isolation rules above. Current Game Session bootstrap/reconnect context remains on the implementation-local `sessionctx:*` family, including the unscoped bootstrap key `sessionctx:session::context` and the tenant-scoped keys `sessionctx:::context`, `sessionctx::identity:::context`, and `sessionctx::identity::name::context`; these old per-instance identity keys and the current `{tenantId, gameInstanceId, characterId}` uniqueness are implementation drift. The target-only `session:game:{tenantGameplayTag}:...` family uses `{tenantGameplayTag}` as a server-derived, deterministic, injective projection of authoritative `tenantId`, allocated through an authoritative persisted tenant-to-tag mapping with an immutable allocation version. Its character uniqueness projection is keyed by `{tenantId, playableStateNamespaceId, characterId}`; server-derived `playableStateScope` remains binding/routing evidence, while its value/evidence retains `{sessionId, gameInstanceId, bindingGeneration}`. The controller-transfer authority is summarized by [ADR 0132](./decisions/adr-0132-namespace-scoped-single-character-controller.md) and [Session Behavior](./system-architecture-session-behavior.md#namespace-scoped-controller-transfer-session-02). Existing mappings are always reused; a new allocation is committed atomically with uniqueness for both the tenant and tag, and a candidate tag already mapped to another tenant is rejected even when the candidate allocation version differs. Algorithm or encoding-version changes preserve existing mappings and may affect only future tenants. Its concrete encoding and version remain opaque to clients and other services; `tenantId` remains authoritative in APIs and persistence. Required focused proof covers distinct-tenant separation, same-tenant stability across process restart with the persisted assignment/version, concurrent first allocation returning one assignment, rejection of a tag collision across allocation versions, and rejection of an active-binding `bindingRef` whose tenant differs from the requested tenant. No end-to-end proof yet demonstrates these target invariants. The remaining gaps do not change the distinct stable `tenantSlug` and tenant-scoped authored-world `worldSlug` selectors, tenant-local `realmSlug` to durable `realmId` resolution, exact-tenant quota binding, or required `GetAdmissionPointer(tenantId, realmId)` 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 3242fe061a..e9c4707f6c 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 @@ -12,7 +12,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 existing configuration-driven pointer initializer and GS/WMS raw seed behavior remain legacy bootstrap inputs, not 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: Durable initial-bind intent and pointer/audit commit/abort proof components, a method-specific Game Session owner-proof read connected to World’s hold reconciler, and an opt-in run-owned local Compose coordinator are wired. The coordinator validates a read-only fixture capability, resumes the descriptor-validated Game Session launch under its stable operation identity, persists initial-bind intent before requesting the World hold, and completes the owner transaction through authenticated proof. This does not implement the strict Account `JOIN` validation-through-commit gate, production activation, or generalized runtime-ID migration; default startup remains closed, and configured seed validation does not create startup authority rows without World-owned 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, covering unit proof and compilation of PostgreSQL migration tests. The coordinator’s retry budget is per process; exhaustion requires an operator-mediated process restart under the same run claim, capability, and operation identity (or operator intervention), keeps World fenced, and does not establish live cross-service restart recovery or automatic generalized abort. A deterministic coordinator orchestration unit test covers budget exhaustion and fresh-coordinator replay under that same identity; it does not prove TLS capability validation, cross-service PostgreSQL races/restart, or live Compose execution. Ambiguous outcomes continue to fence World termination. See the [Game Session API status](../../architecture/microservices/game-session-service/api-contracts.md#initial-admission-bind) and canonical [World contract](../../architecture/microservices/world-management-service/api-contracts.md#initial-admission-bind-hold-contract). +Initial-admission owner boundary: Durable initial-bind intent and pointer/audit commit/abort proof components, a method-specific Game Session owner-proof read connected to World’s hold reconciler, and an opt-in run-owned local Compose coordinator are wired. The coordinator validates a read-only fixture capability, resumes the descriptor-validated Game Session launch under its stable operation identity, persists initial-bind intent before requesting the World hold, and completes the owner transaction through authenticated proof. This does not implement the strict Account `JOIN` validation-through-commit gate, production activation, or generalized runtime-ID migration; default startup remains closed, and configured seed validation does not create startup authority rows without World-owned lifecycle proof. The recorded 85-path check passed 1,781 Game Session unit tests, generated Game Session jOOQ sources, compiled both integration-test source sets, and passed Flyway-version, Markdown link, and Markdown lint checks using `dev-tools/validation/run-locked-gradle.sh :game-session-service:generateJooq :game-session-service:test :game-session-service:compileIntegrationTestJava :world-management-service:compileIntegrationTestJava checkFlywayVersions linkCheck lintMarkdown --no-configuration-cache`. The 145 World Management unit tests are retained from prior validation and were not rerun at the pinned `6ffcbb663f84e0a77c5236f2029ca816923eb7b5` head; this command compiled its integration-test sources only. PostgreSQL and live Compose execution were not performed. The coordinator’s retry budget is per process; exhaustion requires an operator-mediated process restart under the same run claim, capability, and operation identity (or operator intervention), keeps World fenced, and does not establish live cross-service restart recovery or automatic generalized abort. A deterministic coordinator orchestration unit test covers budget exhaustion and fresh-coordinator replay under that same identity; it does not prove TLS capability validation, cross-service PostgreSQL races/restart, or live Compose execution. Ambiguous outcomes continue to fence World termination. See the [Game Session API status](../../architecture/microservices/game-session-service/api-contracts.md#initial-admission-bind) and canonical [World contract](../../architecture/microservices/world-management-service/api-contracts.md#initial-admission-bind-hold-contract). 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). @@ -45,8 +45,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 (see [Game Session API implementation status](../../architecture/microservices/game-session-service/api-contracts.md#implementation-status)); lease-owner forwarding for independently partitioned regions is not | `proven`: [GameSessionWebSocketHandlerTest](../../../services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/websocket/GameSessionWebSocketHandlerTest.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) cover the shipped front-door and routing seams | [Game Session API contracts](../../architecture/microservices/game-session-service/api-contracts.md); [Game Session runtime/data](../../architecture/microservices/game-session-service/runtime-and-data.md); [reconnection](../../architecture/system-architecture-reconnection.md) | [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) | [GameSessionWebSocketHandlerTest](../../../services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/websocket/GameSessionWebSocketHandlerTest.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); [GameSessionGrpcServiceTest](../../../services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/service/impl/GameSessionGrpcServiceTest.java) | `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 API contract requires front-end-to-lease-owner forwarding to be fenced, with retry/ambiguity handling. The current owner boundary is game-instance scoped and does not implement that forwarding or true region partitioning; no new design decision is recorded. | -| Initial-admission pointer bootstrap and owner readback | `partial`: durable catalog/intent and pointer/audit commit/abort proof, typed owner-proof receiver/client, run-owned launch resume, and the opt-in local Compose fixture coordinator are wired; the general `StartSession` retry path is not claimed | `in progress`: focused Game Session owner tests passed; cross-service PostgreSQL race/restart and live Compose proof are not claimed | [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); [run-owned player-flow smoke boundary](../../architecture/system-architecture-testing.md#player-flow-smoke-and-reset-boundaries) | [DatabaseInitialAdmissionBindOwnerService.java](../../../services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/service/impl/DatabaseInitialAdmissionBindOwnerService.java); [RunOwnedInitialAdmissionFixtureCoordinator.java](../../../services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/data/RunOwnedInitialAdmissionFixtureCoordinator.java); [RunOwnedInitialAdmissionFixtureCapability.java](../../../services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/data/RunOwnedInitialAdmissionFixtureCapability.java); [GameInstanceServiceImpl.java](../../../services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/service/impl/GameInstanceServiceImpl.java); [V9 initial-admission owner ledger](../../../services/game-session-service/src/main/resources/db/migration/V9__initial_admission_bind_owner_ledger.sql); [GetInitialAdmissionBindProof](../../../protos/game-session/v1/game_session_service.proto); [InitialAdmissionBindOwnerReadWorkloadGuard.java](../../../services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/service/impl/InitialAdmissionBindOwnerReadWorkloadGuard.java); [GrpcGameSessionInitialAdmissionBindProofClient.java](../../../services/world-management-service/src/main/java/net/firedevops/firemud/worldmanagement/client/GrpcGameSessionInitialAdmissionBindProofClient.java) | [InitialAdmissionBindServiceTest.java](../../../services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/service/impl/InitialAdmissionBindServiceTest.java); [InitialAdmissionBindOwnerReadTest.java](../../../services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/service/impl/InitialAdmissionBindOwnerReadTest.java); [RunOwnedInitialAdmissionFixtureCapabilityTest.java](../../../services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/data/RunOwnedInitialAdmissionFixtureCapabilityTest.java); [RunOwnedInitialAdmissionFixtureCoordinatorTest.java](../../../services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/data/RunOwnedInitialAdmissionFixtureCoordinatorTest.java); [GameInstanceServiceImplTest.java](../../../services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/service/impl/GameInstanceServiceImplTest.java); [GrpcGameSessionInitialAdmissionBindProofClientTest.java](../../../services/world-management-service/src/test/java/unit/net/firedevops/firemud/worldmanagement/client/GrpcGameSessionInitialAdmissionBindProofClientTest.java); [InitialAdmissionBindPostgresIntegrationTest.java](../../../services/game-session-service/src/test/java/integration/net/firedevops/firemud/gamesession/service/InitialAdmissionBindPostgresIntegrationTest.java) | World owns the separate hold and termination fence; see the [World runtime tracker](./world-runtime-and-movement.md) | The bounded local Compose coordinator does not complete the strict Account `JOIN` gate, production activation, or generalized runtime-ID migration. General `StartSession` retry integration and live cross-service PostgreSQL restart proof remain open; no ambiguous result releases World termination. | +| `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 (see [Game Session API implementation status](../../architecture/microservices/game-session-service/api-contracts.md#implementation-status)); lease-owner forwarding for independently partitioned regions is not. Its initial-admission owner sub-boundary contributes to `AR-3.1`: durable catalog/intent and pointer/audit commit/abort components, typed owner-proof receiver/client, run-owned launch resume, and the opt-in fixture coordinator are wired; general `StartSession` retry integration is not claimed. | `proven` for the front-door and routing seams: [GameSessionWebSocketHandlerTest](../../../services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/websocket/GameSessionWebSocketHandlerTest.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); `audited` for the initial-admission sub-boundary: local owner/coordinator tests cover their unit seams, but cross-service PostgreSQL race/restart proof and live Compose execution are not established. | [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); [RunOwnedInitialAdmissionFixtureCoordinator.java](../../../services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/data/RunOwnedInitialAdmissionFixtureCoordinator.java); [RunOwnedInitialAdmissionFixtureCapability.java](../../../services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/data/RunOwnedInitialAdmissionFixtureCapability.java); [GameInstanceServiceImpl.java](../../../services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/service/impl/GameInstanceServiceImpl.java); [V9 initial-admission owner ledger](../../../services/game-session-service/src/main/resources/db/migration/V9__initial_admission_bind_owner_ledger.sql); [GetInitialAdmissionBindProof](../../../protos/game-session/v1/game_session_service.proto); [InitialAdmissionBindOwnerReadWorkloadGuard.java](../../../services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/service/impl/InitialAdmissionBindOwnerReadWorkloadGuard.java); [GrpcGameSessionInitialAdmissionBindProofClient.java](../../../services/world-management-service/src/main/java/net/firedevops/firemud/worldmanagement/client/GrpcGameSessionInitialAdmissionBindProofClient.java) | [GameSessionWebSocketHandlerTest](../../../services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/websocket/GameSessionWebSocketHandlerTest.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); [GameSessionGrpcServiceTest](../../../services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/service/impl/GameSessionGrpcServiceTest.java); [InitialAdmissionBindServiceTest.java](../../../services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/service/impl/InitialAdmissionBindServiceTest.java); [InitialAdmissionBindOwnerReadTest.java](../../../services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/service/impl/InitialAdmissionBindOwnerReadTest.java); [RunOwnedInitialAdmissionFixtureCapabilityTest.java](../../../services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/data/RunOwnedInitialAdmissionFixtureCapabilityTest.java); [RunOwnedInitialAdmissionFixtureCoordinatorTest.java](../../../services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/data/RunOwnedInitialAdmissionFixtureCoordinatorTest.java); [GameInstanceServiceImplTest.java](../../../services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/service/impl/GameInstanceServiceImplTest.java); [GrpcGameSessionInitialAdmissionBindProofClientTest.java](../../../services/world-management-service/src/test/java/unit/net/firedevops/firemud/worldmanagement/client/GrpcGameSessionInitialAdmissionBindProofClientTest.java); [InitialAdmissionBindPostgresIntegrationTest.java](../../../services/game-session-service/src/test/java/integration/net/firedevops/firemud/gamesession/service/InitialAdmissionBindPostgresIntegrationTest.java) | `AR-3.1` runtime lifecycle in [Game Authoring](./game-authoring-publishing-and-activation.md#capability-status); `GR-2.1` World hold and termination fence in the [World runtime tracker](./world-runtime-and-movement.md#capability-status); `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; an ambiguous result continues to fence World termination. The API contract requires front-end-to-lease-owner forwarding to be fenced, with retry/ambiguity handling. The current owner boundary is game-instance scoped and does not implement that forwarding or true region partitioning; no new design decision is recorded. | | `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/world-runtime-and-movement.md b/design/project-management/implementation-tracking/world-runtime-and-movement.md index abd05d48b2..a43c4229a5 100644 --- a/design/project-management/implementation-tracking/world-runtime-and-movement.md +++ b/design/project-management/implementation-tracking/world-runtime-and-movement.md @@ -8,7 +8,7 @@ This is a non-normative implementation tracker for world runtime and movement. C This tracker is the permanent reader-facing implementation record for world runtime, room reads, movement, lifecycle orchestration, and Draft topology mutation. Canonical target-state design remains under [design/architecture](../../architecture/README.md). -The initial-admission implementation now includes the typed Game Session workload-only acquire RPC, a durable World hold, lifecycle-row termination serialization, scheduled fail-closed reconciliation, and a method-specific authenticated Game Session owner-read adapter. The opt-in run-owned local Compose coordinator now drives the hold from Game Session’s durable initial-bind intent and resolves it only through exact authenticated owner proof. Raw Game Session `RUNNING` and World `ACTIVE` runtime seeds have been removed; local World metadata seeding retains versioned template rooms `1021` and `2045` for the current transitional movement contract. All 144 World unit tests pass; PostgreSQL race/restart and live Compose proof remain unclaimed. See the [World initial-bind contract](../../architecture/microservices/world-management-service/api-contracts.md#initial-admission-bind-hold-contract) and the [Game Session implementation status](../../architecture/microservices/game-session-service/api-contracts.md#initial-admission-bind). +The initial-admission implementation now includes the typed Game Session workload-only acquire RPC, a durable World hold, lifecycle-row termination serialization, scheduled fail-closed reconciliation, and a method-specific authenticated Game Session owner-read adapter. The opt-in run-owned local Compose coordinator now drives the hold from Game Session’s durable initial-bind intent and resolves it only through exact authenticated owner proof. Raw Game Session `RUNNING` and World `ACTIVE` runtime seeds have been removed; local World metadata seeding retains versioned template rooms `1021` and `2045` for the current transitional movement contract. The focused unit-test anchors in the capability table cover service-local seams; PostgreSQL race/restart and live Compose proof remain unclaimed. See the [World initial-bind contract](../../architecture/microservices/world-management-service/api-contracts.md#initial-admission-bind-hold-contract) and the [Game Session implementation status](../../architecture/microservices/game-session-service/api-contracts.md#initial-admission-bind). ## Packet 4 Status and Proof Gaps @@ -26,8 +26,7 @@ These links add decision provenance only; they do not upgrade world runtime, lif | Capability | Implementation | Verification | Design | Implementation anchors | Proof anchors | Secondary handoffs | Gap or decision | | --- | --- | --- | --- | --- | --- | --- | --- | -| `GR-2.1` World topology, rooms, regions, and runtime instances | `partial` | `audited` | [World Management ownership](../../architecture/microservices/world-management-service/README.md); [World API contracts](../../architecture/microservices/world-management-service/api-contracts.md); [runtime and data](../../architecture/microservices/world-management-service/runtime-and-data.md); [world creation workflow](../../architecture/microservices/world-management-service/world-creation-workflow.md); [ADR 0093](../../architecture/decisions/adr-0093-game-design-coordinated-digest-attested-content-publication.md); [ADR 0098](../../architecture/decisions/adr-0098-request-bounded-generation-replay-and-explicit-regeneration.md); [ADR 0099](../../architecture/decisions/adr-0099-bounded-atomic-generation-with-staging-for-large-outputs.md); [ADR 0100](../../architecture/decisions/adr-0100-separate-generation-ingress-with-one-world-owned-engine.md); [ADR 0101](../../architecture/decisions/adr-0101-explicit-destructive-regeneration-with-previewed-scope.md); [ADR 0102](../../architecture/decisions/adr-0102-first-class-sparse-and-full-grid-world-topologies.md) | [WorldDesignMutationServiceImpl.java](../../../services/world-management-service/src/main/java/net/firedevops/firemud/worldmanagement/service/impl/WorldDesignMutationServiceImpl.java); [WorldInstanceActivationServiceImpl.java](../../../services/world-management-service/src/main/java/net/firedevops/firemud/worldmanagement/service/impl/WorldInstanceActivationServiceImpl.java); [WorldLifecycleCommandServiceImpl.java](../../../services/world-management-service/src/main/java/net/firedevops/firemud/worldmanagement/service/impl/WorldLifecycleCommandServiceImpl.java); [V18 version-scoped templates](../../../services/world-management-service/src/main/resources/db/migration/V18__version_scoped_world_templates.sql); [V19 mutation ledger](../../../services/world-management-service/src/main/resources/db/migration/V19__world_design_mutation_ledger.sql) | [WorldDesignMutationServiceImplTest.java](../../../services/world-management-service/src/test/java/unit/net/firedevops/firemud/worldmanagement/service/impl/WorldDesignMutationServiceImplTest.java); [WorldDraftDesignDigestServiceImplTest.java](../../../services/world-management-service/src/test/java/unit/net/firedevops/firemud/worldmanagement/service/impl/WorldDraftDesignDigestServiceImplTest.java); [WorldLifecycleCommandServiceImplTest.java](../../../services/world-management-service/src/test/java/unit/net/firedevops/firemud/worldmanagement/service/impl/WorldLifecycleCommandServiceImplTest.java); [WorldManagementGrpcServiceTest.java](../../../services/world-management-service/src/test/java/unit/net/firedevops/firemud/worldmanagement/service/impl/WorldManagementGrpcServiceTest.java) | [authoring](./game-authoring-publishing-and-activation.md); [realm routing](./realm-routing-and-playable-state.md); [Game Session runtime](./game-session-runtime-and-tick-coordination.md) | Partial: version-scoped topology, Draft mutation, and instance lifecycle exist, but generation still has hardcoded inputs, initial event scheduling is absent, and lifecycle prepare/activate retain blocking attestation calls. Accepted publication and procedural-generation decisions now define World-owned topology, request-bounded replay, atomic visibility, explicit replacement, and sparse/full-grid boundaries; typed ingress, destructive plans, staging bounds, and large-grid proof remain incomplete. | -| `GR-2.1` World-owned initial-admission hold and termination fence | `partial`: exact hold acquisition, serialized termination blocking, fail-closed reconciliation, authenticated Game Session owner proof, and the run-owned local Compose caller are wired; the general `StartSession` retry path is not claimed | `drift-found`: all 144 World unit tests pass; PostgreSQL race/restart proof remains outstanding | [World initial-admission bind hold contract](../../architecture/microservices/world-management-service/api-contracts.md#initial-admission-bind-hold-contract); [ADR 0123](../../architecture/decisions/adr-0123-database-authoritative-temporal-coordinated-world-lifecycle.md); [run-owned player-flow smoke boundary](../../architecture/system-architecture-testing.md#player-flow-smoke-and-reset-boundaries) | [WorldManagementGrpcService.java](../../../services/world-management-service/src/main/java/net/firedevops/firemud/worldmanagement/service/impl/WorldManagementGrpcService.java); [InitialAdmissionBindHoldServiceImpl.java](../../../services/world-management-service/src/main/java/net/firedevops/firemud/worldmanagement/service/impl/InitialAdmissionBindHoldServiceImpl.java); [InitialAdmissionBindHoldRepository.java](../../../services/world-management-service/src/main/java/net/firedevops/firemud/worldmanagement/repository/InitialAdmissionBindHoldRepository.java); [V23 initial-admission hold](../../../services/world-management-service/src/main/resources/db/migration/V23__initial_admission_bind_hold.sql); [GrpcGameSessionInitialAdmissionBindProofClient.java](../../../services/world-management-service/src/main/java/net/firedevops/firemud/worldmanagement/client/GrpcGameSessionInitialAdmissionBindProofClient.java) | [WorldManagementGrpcServiceTest.java](../../../services/world-management-service/src/test/java/unit/net/firedevops/firemud/worldmanagement/service/impl/WorldManagementGrpcServiceTest.java); [InitialAdmissionBindHoldServiceImplTest.java](../../../services/world-management-service/src/test/java/unit/net/firedevops/firemud/worldmanagement/service/impl/InitialAdmissionBindHoldServiceImplTest.java); [InitialAdmissionBindHoldRepositoryTest.java](../../../services/world-management-service/src/test/java/unit/net/firedevops/firemud/worldmanagement/repository/InitialAdmissionBindHoldRepositoryTest.java); [InitialAdmissionBindHoldPostgresIntegrationTest.java](../../../services/world-management-service/src/test/java/integration/net/firedevops/firemud/worldmanagement/InitialAdmissionBindHoldPostgresIntegrationTest.java) | [Game Session runtime tracker](./game-session-runtime-and-tick-coordination.md) | Run-owned Compose reaches the World hold from durable Game Session intent, but does not complete the strict Account `JOIN` gate, production activation, or generalized runtime-ID migration. PostgreSQL race/restart and live Compose proof remain open; ambiguity must continue fencing termination. | +| `GR-2.1` World topology, rooms, regions, and runtime instances | `partial`: version-scoped topology, Draft mutation, and instance lifecycle exist, but generation still has hardcoded inputs, initial event scheduling is absent, and lifecycle prepare/activate retain blocking attestation calls. The World-owned initial-admission hold is a lifecycle sub-boundary under `GR-2.1` that contributes to the `AR-3.1` runtime lifecycle handoff: exact hold acquisition, serialized termination blocking, fail-closed reconciliation, authenticated Game Session owner readback, and the run-owned local Compose caller are wired; general `StartSession` retry integration is not claimed. Accepted publication and procedural-generation decisions now define World-owned topology, request-bounded replay, atomic visibility, explicit replacement, and sparse/full-grid boundaries; typed ingress, destructive plans, staging bounds, and large-grid proof remain incomplete. | `audited`: focused unit tests cover topology, lifecycle, hold acquisition, termination blocking, and reconciliation; PostgreSQL hold/termination race and restart proof and live Compose execution are not established for this boundary. | [World Management ownership](../../architecture/microservices/world-management-service/README.md); [World API contracts](../../architecture/microservices/world-management-service/api-contracts.md); [initial-admission bind hold contract](../../architecture/microservices/world-management-service/api-contracts.md#initial-admission-bind-hold-contract); [runtime and data](../../architecture/microservices/world-management-service/runtime-and-data.md); [world creation workflow](../../architecture/microservices/world-management-service/world-creation-workflow.md); [ADR 0093](../../architecture/decisions/adr-0093-game-design-coordinated-digest-attested-content-publication.md); [ADR 0098](../../architecture/decisions/adr-0098-request-bounded-generation-replay-and-explicit-regeneration.md); [ADR 0099](../../architecture/decisions/adr-0099-bounded-atomic-generation-with-staging-for-large-outputs.md); [ADR 0100](../../architecture/decisions/adr-0100-separate-generation-ingress-with-one-world-owned-engine.md); [ADR 0101](../../architecture/decisions/adr-0101-explicit-destructive-regeneration-with-previewed-scope.md); [ADR 0102](../../architecture/decisions/adr-0102-first-class-sparse-and-full-grid-world-topologies.md); [ADR 0123](../../architecture/decisions/adr-0123-database-authoritative-temporal-coordinated-world-lifecycle.md); [run-owned player-flow smoke boundary](../../architecture/system-architecture-testing.md#player-flow-smoke-and-reset-boundaries) | [WorldDesignMutationServiceImpl.java](../../../services/world-management-service/src/main/java/net/firedevops/firemud/worldmanagement/service/impl/WorldDesignMutationServiceImpl.java); [WorldInstanceActivationServiceImpl.java](../../../services/world-management-service/src/main/java/net/firedevops/firemud/worldmanagement/service/impl/WorldInstanceActivationServiceImpl.java); [WorldLifecycleCommandServiceImpl.java](../../../services/world-management-service/src/main/java/net/firedevops/firemud/worldmanagement/service/impl/WorldLifecycleCommandServiceImpl.java); [InitialAdmissionBindHoldServiceImpl.java](../../../services/world-management-service/src/main/java/net/firedevops/firemud/worldmanagement/service/impl/InitialAdmissionBindHoldServiceImpl.java); [InitialAdmissionBindHoldRepository.java](../../../services/world-management-service/src/main/java/net/firedevops/firemud/worldmanagement/repository/InitialAdmissionBindHoldRepository.java); [GrpcGameSessionInitialAdmissionBindProofClient.java](../../../services/world-management-service/src/main/java/net/firedevops/firemud/worldmanagement/client/GrpcGameSessionInitialAdmissionBindProofClient.java); [V18 version-scoped templates](../../../services/world-management-service/src/main/resources/db/migration/V18__version_scoped_world_templates.sql); [V19 mutation ledger](../../../services/world-management-service/src/main/resources/db/migration/V19__world_design_mutation_ledger.sql); [V23 initial-admission hold](../../../services/world-management-service/src/main/resources/db/migration/V23__initial_admission_bind_hold.sql) | [WorldDesignMutationServiceImplTest.java](../../../services/world-management-service/src/test/java/unit/net/firedevops/firemud/worldmanagement/service/impl/WorldDesignMutationServiceImplTest.java); [WorldDraftDesignDigestServiceImplTest.java](../../../services/world-management-service/src/test/java/unit/net/firedevops/firemud/worldmanagement/service/impl/WorldDraftDesignDigestServiceImplTest.java); [WorldLifecycleCommandServiceImplTest.java](../../../services/world-management-service/src/test/java/unit/net/firedevops/firemud/worldmanagement/service/impl/WorldLifecycleCommandServiceImplTest.java); [WorldManagementGrpcServiceTest.java](../../../services/world-management-service/src/test/java/unit/net/firedevops/firemud/worldmanagement/service/impl/WorldManagementGrpcServiceTest.java); [InitialAdmissionBindHoldServiceImplTest.java](../../../services/world-management-service/src/test/java/unit/net/firedevops/firemud/worldmanagement/service/impl/InitialAdmissionBindHoldServiceImplTest.java); [InitialAdmissionBindHoldRepositoryTest.java](../../../services/world-management-service/src/test/java/unit/net/firedevops/firemud/worldmanagement/repository/InitialAdmissionBindHoldRepositoryTest.java); [InitialAdmissionBindHoldPostgresIntegrationTest.java](../../../services/world-management-service/src/test/java/integration/net/firedevops/firemud/worldmanagement/InitialAdmissionBindHoldPostgresIntegrationTest.java) | [AR-3.1 lifecycle in Game Authoring](./game-authoring-publishing-and-activation.md#capability-status); [realm routing](./realm-routing-and-playable-state.md); [Game Session runtime](./game-session-runtime-and-tick-coordination.md) | The hold keeps ambiguous initial-admission outcomes fenced and does not complete the strict Account `JOIN` gate, production activation, or generalized runtime-ID migration. PostgreSQL race/restart proof and live Compose execution remain open. | | `GR-2.2` Location, occupancy, movement, exits, and spatial reads | `partial` | `audited` | [World API contracts](../../architecture/microservices/world-management-service/api-contracts.md); [World runtime and data](../../architecture/microservices/world-management-service/runtime-and-data.md); [system architecture](../../architecture/system-architecture-overview.md); [spatial and ambient effects](../../architecture/system-architecture-spatial-and-ambient-effects-catalog.md); [ADR 0102](../../architecture/decisions/adr-0102-first-class-sparse-and-full-grid-world-topologies.md) | [WorldManagementGrpcService.java](../../../services/world-management-service/src/main/java/net/firedevops/firemud/worldmanagement/service/impl/WorldManagementGrpcService.java); [LookAggregationService.java](../../../services/game-logic-service/src/main/java/net/firedevops/firemud/gamelogic/service/LookAggregationService.java); [MoveAggregationService.java](../../../services/game-logic-service/src/main/java/net/firedevops/firemud/gamelogic/service/MoveAggregationService.java); [MoveCommandHandler.java](../../../services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/command/text/MoveCommandHandler.java); [room contract](../../../protos/world-management/v1/world_management_service.proto) | [WorldManagementGrpcServiceTest.java](../../../services/world-management-service/src/test/java/unit/net/firedevops/firemud/worldmanagement/service/impl/WorldManagementGrpcServiceTest.java); [LookAggregationServiceTest.java](../../../services/game-logic-service/src/test/java/net/firedevops/firemud/gamelogic/service/LookAggregationServiceTest.java); [MoveAggregationServiceTest.java](../../../services/game-logic-service/src/test/java/net/firedevops/firemud/gamelogic/service/MoveAggregationServiceTest.java); [MoveCommandHandlerTest.java](../../../services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/command/text/MoveCommandHandlerTest.java); [movement idempotency test](../../../services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/service/impl/RedisMovementEffectIdempotencyServiceTest.java) | [authoring](./game-authoring-publishing-and-activation.md); [gameplay](./gameplay-rules-entities-and-effects.md); [Game Session runtime](./game-session-runtime-and-tick-coordination.md); [player experience](./player-experience-commands-and-communication.md) | Partial: directional LOOK and movement primitives exist, but the WMS `ListRoomOccupants` handler and target-only `character_location`/`npc_location` location and occupancy persistence are absent. Live `room_instance` topology and the Game Session room binding are not the World-owned location authority, and the final LOOK identity is not yet the causal floor plus opaque World/Entity component versions; served-through proofs remain separate participant validation evidence. DROP/PICKUP also lack the target World `TargetingFactSnapshot` location/version validation in the Entity-local commit. [ADR 0054](../../architecture/decisions/adr-0054-split-spatial-authority-with-causal-read-composition.md) remains applied; implementation and proof gaps remain. Accepted full-grid topology decision now defines density-independent movement semantics and opaque scalable representation; large-grid identity, chunk/root finalization, base-plus-delta recovery, and movement-policy proof remain incomplete. | | `GR-2.3` Ambient, environmental, and scheduled world state | `partial` | `audited` | [World API contracts](../../architecture/microservices/world-management-service/api-contracts.md); [World runtime and data](../../architecture/microservices/world-management-service/runtime-and-data.md); [spatial and ambient effects](../../architecture/system-architecture-spatial-and-ambient-effects-catalog.md); [world creation workflow](../../architecture/microservices/world-management-service/world-creation-workflow.md) | [WorldEventServiceImpl.java](../../../services/world-management-service/src/main/java/net/firedevops/firemud/worldmanagement/service/impl/WorldEventServiceImpl.java); [WorldManagementGrpcService.java](../../../services/world-management-service/src/main/java/net/firedevops/firemud/worldmanagement/service/impl/WorldManagementGrpcService.java); [RoomSnapshotDto.java](../../../services/world-management-service/src/main/java/net/firedevops/firemud/worldmanagement/dto/RoomSnapshotDto.java); [V3 world events](../../../services/world-management-service/src/main/resources/db/migration/V3__world_events.sql); [V16 runtime event scope](../../../services/world-management-service/src/main/resources/db/migration/V16__runtime_world_event_scope.sql) | [WorldEventServiceImplTest.java](../../../services/world-management-service/src/test/java/unit/net/firedevops/firemud/worldmanagement/service/impl/WorldEventServiceImplTest.java); [RoomSnapshotDtoTest.java](../../../services/world-management-service/src/test/java/unit/net/firedevops/firemud/worldmanagement/dto/RoomSnapshotDtoTest.java); [WorldManagementGrpcServiceTest.java](../../../services/world-management-service/src/test/java/unit/net/firedevops/firemud/worldmanagement/service/impl/WorldManagementGrpcServiceTest.java) | [authoring](./game-authoring-publishing-and-activation.md); [automation](./automation-and-scheduler-runtime.md); [Game Session runtime](./game-session-runtime-and-tick-coordination.md); [gameplay](./gameplay-rules-entities-and-effects.md) | Partial: scheduled non-Weather event processing and ambient snapshot shape exist, but `ApplyRoomAmbientStatePatch` has no Java handler, durable effect-idempotency and general ambient patches are absent, and the creation workflow does not schedule initial events. Live `WorldEventService` rejects new `WEATHER_CHANGE` scheduling and leaves retained Weather rows unprocessed; the unresolved selector/fenced effect contract still blocks safe ambient mutation, so current code is not proof of the target World-owned fenced ambient-mutation contract. [ADR 0054](../../architecture/decisions/adr-0054-split-spatial-authority-with-causal-read-composition.md) remains the target owner; its World-side handler, durable replay guard, and focused proof remain unimplemented. | diff --git a/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/data/RunOwnedInitialAdmissionFixtureCapability.java b/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/data/RunOwnedInitialAdmissionFixtureCapability.java index 663cca43de..bf6d7bc031 100644 --- a/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/data/RunOwnedInitialAdmissionFixtureCapability.java +++ b/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/data/RunOwnedInitialAdmissionFixtureCapability.java @@ -288,7 +288,7 @@ private static String fingerprint(X509Certificate certificate) { } } - private static byte[] readCapability(Path path) { + static byte[] readCapability(Path path) { if (path == null || !path.isAbsolute()) { throw invalidCapability(); } diff --git a/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/repository/InitialAdmissionBindAttemptRepository.java b/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/repository/InitialAdmissionBindAttemptRepository.java index 38184c7e6f..d416468e94 100644 --- a/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/repository/InitialAdmissionBindAttemptRepository.java +++ b/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/repository/InitialAdmissionBindAttemptRepository.java @@ -230,7 +230,7 @@ public GameplayAdmissionPointer insertPointer( record.setCreatedAt(toLocalDateTime(now)); record.setUpdatedAt(toLocalDateTime(now)); record.store(); - return findPointerById(record.getId()).orElseThrow(); + return findPointerById(record.getId().longValue()).orElseThrow(); } public Optional findPointerById(long pointerId) { @@ -239,12 +239,6 @@ public Optional findPointerById(long pointerId) { .fetchOptional(this::toPointer); } - private Optional findPointerById(Long pointerId) { - return dsl.selectFrom(GAMEPLAY_ADMISSION_POINTER) - .where(GAMEPLAY_ADMISSION_POINTER.ID.eq(pointerId)) - .fetchOptional(this::toPointer); - } - private void lock(String key) { dsl.fetch("select pg_advisory_xact_lock(hashtextextended(cast(? as text), 0))", key); } diff --git a/services/game-session-service/src/test/java/integration/net/firedevops/firemud/gamesession/service/InitialAdmissionBindPostgresIntegrationTest.java b/services/game-session-service/src/test/java/integration/net/firedevops/firemud/gamesession/service/InitialAdmissionBindPostgresIntegrationTest.java index 4b7c3fe997..8e7340f7bc 100644 --- a/services/game-session-service/src/test/java/integration/net/firedevops/firemud/gamesession/service/InitialAdmissionBindPostgresIntegrationTest.java +++ b/services/game-session-service/src/test/java/integration/net/firedevops/firemud/gamesession/service/InitialAdmissionBindPostgresIntegrationTest.java @@ -33,7 +33,7 @@ class InitialAdmissionBindPostgresIntegrationTest { static PostgreSQLContainer postgres = new PostgreSQLContainer<>("postgres:16-alpine"); @Test - void v8LedgerCommitsPointerAuditAndAttemptTogetherAndReadbackFailsClosed() { + void initialAdmissionLedgerCommitsPointerAuditAndAttemptTogetherAndReadbackFailsClosed() { DriverManagerDataSource dataSource = dataSource(); Flyway.configure().dataSource(dataSource).locations(MIGRATION_LOCATION).load().migrate(); DSLContext dsl = diff --git a/services/game-session-service/src/test/java/integration/net/firedevops/firemud/gamesession/service/RunOwnedInitialLaunchPostgresIntegrationTest.java b/services/game-session-service/src/test/java/integration/net/firedevops/firemud/gamesession/service/RunOwnedInitialLaunchPostgresIntegrationTest.java index cbb92efe3b..eae9d18e0e 100644 --- a/services/game-session-service/src/test/java/integration/net/firedevops/firemud/gamesession/service/RunOwnedInitialLaunchPostgresIntegrationTest.java +++ b/services/game-session-service/src/test/java/integration/net/firedevops/firemud/gamesession/service/RunOwnedInitialLaunchPostgresIntegrationTest.java @@ -4,6 +4,7 @@ import static org.assertj.core.api.Assertions.assertThatThrownBy; import java.nio.file.Path; +import java.sql.SQLException; import java.util.concurrent.CountDownLatch; import java.util.concurrent.Executors; import java.util.concurrent.TimeUnit; @@ -61,36 +62,42 @@ void concurrentExactIdentityAllocationConvergesAndOrdinaryRowsRemainNullable() t long secondId = second.get(15, TimeUnit.SECONDS); assertThat(firstId).isEqualTo(secondId); assertThat( - dsl.fetchValue( - "SELECT count(*) FROM game_instances WHERE tenant_id = ? " - + "AND run_owned_start_request_id = ?", - Integer.class, - TENANT_ID, - REQUEST_ID)) - .isEqualTo(1); + dsl.fetchOne( + "SELECT count(*) FROM game_instances WHERE tenant_id = ? " + + "AND run_owned_start_request_id = ?", + TENANT_ID, + REQUEST_ID) + .get(0, Long.class)) + .isEqualTo(1L); assertThat( - dsl.fetchValue( + dsl.fetchOne( "SELECT run_owned_start_request_digest FROM game_instances WHERE id = ?", - String.class, - firstId)) + firstId) + .get(0, String.class)) .isEqualTo(REQUEST_DIGEST); assertThatThrownBy(() -> insertDuplicateIdentity(dsl, firstId + 1L)) - .isInstanceOf(DataAccessException.class); - - GameInstance ordinaryOne = ordinaryInstance(1001L); - GameInstance ordinaryTwo = ordinaryInstance(1002L); - repository.save(ordinaryOne); - repository.save(ordinaryTwo); - assertThat(ordinaryOne.getRunOwnedStartRequestId()).isNull(); - assertThat(ordinaryTwo.getRunOwnedStartRequestId()).isNull(); + .isInstanceOf(DataAccessException.class) + .satisfies( + failure -> { + assertThat(sqlState(failure)).isEqualTo("23505"); + assertThat( + hasCauseMessage( + failure, "game_instances_run_owned_start_request_unique")) + .isTrue(); + }); + + GameInstance savedOrdinaryOne = repository.save(ordinaryInstance(1001L)); + GameInstance savedOrdinaryTwo = repository.save(ordinaryInstance(1002L)); + assertThat(savedOrdinaryOne.getRunOwnedStartRequestId()).isNull(); + assertThat(savedOrdinaryTwo.getRunOwnedStartRequestId()).isNull(); assertThat( - dsl.fetchValue( - "SELECT count(*) FROM game_instances WHERE tenant_id = ? " - + "AND run_owned_start_request_id IS NULL", - Integer.class, - TENANT_ID)) - .isEqualTo(2); + dsl.fetchOne( + "SELECT count(*) FROM game_instances WHERE tenant_id = ? " + + "AND run_owned_start_request_id IS NULL", + TENANT_ID) + .get(0, Long.class)) + .isEqualTo(2L); } } @@ -139,6 +146,24 @@ private static void insertDuplicateIdentity(DSLContext dsl, long id) { REQUEST_DIGEST); } + private static String sqlState(Throwable failure) { + for (Throwable current = failure; current != null; current = current.getCause()) { + if (current instanceof SQLException sqlException) { + return sqlException.getSQLState(); + } + } + return null; + } + + private static boolean hasCauseMessage(Throwable failure, String message) { + for (Throwable current = failure; current != null; current = current.getCause()) { + if (current.getMessage() != null && current.getMessage().contains(message)) { + return true; + } + } + return false; + } + private static DriverManagerDataSource dataSource() { DriverManagerDataSource dataSource = new DriverManagerDataSource(); dataSource.setDriverClassName("org.postgresql.Driver"); diff --git a/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/CrossServiceAppHarnessTest.java b/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/CrossServiceAppHarnessTest.java new file mode 100644 index 0000000000..a22fef1865 --- /dev/null +++ b/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/CrossServiceAppHarnessTest.java @@ -0,0 +1,90 @@ +package net.firedevops.firemud.gamesession; + +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.anyBoolean; +import static org.mockito.Mockito.mock; +import static org.mockito.Mockito.never; +import static org.mockito.Mockito.verify; + +import java.util.Map; +import javax.sql.DataSource; +import net.firedevops.firemud.gamesession.dto.StartSessionRequest; +import net.firedevops.firemud.gamesession.service.GameInstanceService; +import net.firedevops.firemud.gamesession.service.impl.GameInstanceServiceImpl; +import org.junit.jupiter.api.Test; +import org.springframework.boot.test.context.TestConfiguration; +import org.springframework.context.annotation.AnnotationConfigApplicationContext; +import org.springframework.context.annotation.Bean; +import org.springframework.core.env.MapPropertySource; + +class CrossServiceAppHarnessTest { + private static final StartSessionRequest REQUEST = + new StartSessionRequest(41L, 810L, "cross-service-fixture", 1001L); + + @Test + void databaseDisabledOrMissingReplacesTheRealServiceWithTheStub() { + for (String databaseEnabled : new String[] {"false", null}) { + try (AnnotationConfigApplicationContext context = context(databaseEnabled)) { + assertThat(context.getBeanNamesForType(DataSource.class)).isEmpty(); + assertThat(context.getBean("gameInstanceServiceImpl")) + .isNotInstanceOf(GameInstanceServiceImpl.class); + + GameInstanceService service = context.getBean(GameInstanceService.class); + assertThat(service.startSession(REQUEST, false).id()).isEqualTo(-1L); + assertThatThrownBy(() -> service.startRunOwnedInitialLaunch(REQUEST)) + .isInstanceOf(IllegalStateException.class) + .hasMessage("run-owned launch requires a database-enabled test context"); + } + } + } + + @Test + void databaseEnabledWrapperDelegatesOnlyRunOwnedLaunchToTheNamedService() { + try (AnnotationConfigApplicationContext context = + context("true", EnabledGameInstanceServiceConfiguration.class)) { + GameInstanceService actualService = + context.getBean("gameInstanceServiceImpl", GameInstanceService.class); + GameInstanceService harnessService = context.getBean(GameInstanceService.class); + + assertThat(harnessService.startSession(REQUEST, false).id()).isEqualTo(-1L); + assertThat(harnessService.startRunOwnedInitialLaunch(REQUEST)).isNull(); + + verify(actualService).startRunOwnedInitialLaunch(REQUEST); + verify(actualService, never()).startSession(any(), anyBoolean()); + } + } + + private static AnnotationConfigApplicationContext context( + String databaseEnabled, Class... extraConfigurations) { + AnnotationConfigApplicationContext context = new AnnotationConfigApplicationContext(); + context.getDefaultListableBeanFactory().setAllowBeanDefinitionOverriding(true); + if (databaseEnabled != null) { + context + .getEnvironment() + .getPropertySources() + .addFirst( + new MapPropertySource( + "cross-service-harness-test", + Map.of("firemud.database.enabled", databaseEnabled))); + } + if (databaseEnabled != null && databaseEnabled.equals("true")) { + context.register(extraConfigurations); + context.register(CrossServiceAppHarness.GameSessionTestOverrides.class); + } else { + context.register(GameInstanceServiceImpl.class); + context.register(CrossServiceAppHarness.GameSessionTestOverrides.class); + } + context.refresh(); + return context; + } + + @TestConfiguration(proxyBeanMethods = false) + static class EnabledGameInstanceServiceConfiguration { + @Bean(name = "gameInstanceServiceImpl") + GameInstanceService gameInstanceServiceImpl() { + return mock(GameInstanceService.class); + } + } +} 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 f0f59f5d88..bb582c7ca3 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 @@ -7,9 +7,11 @@ import java.nio.file.Files; import java.nio.file.Path; +import java.nio.file.attribute.PosixFilePermission; import java.security.PublicKey; import java.security.cert.X509Certificate; import java.util.List; +import java.util.Set; import net.firedevops.firemud.gamesession.data.RunOwnedInitialAdmissionFixtureCapability.CertificatePins; import org.junit.jupiter.api.Test; import org.junit.jupiter.api.io.TempDir; @@ -70,12 +72,21 @@ void rejectsWritableCapabilityFile(@TempDir Path directory) throws Exception { Files.writeString(directory.resolve("fixture-capability.json"), validJson()); assertThatThrownBy( - () -> - RunOwnedInitialAdmissionFixtureCapability.load( - capabilityFile, RUN_ID, PROJECT_NAME, null)) + () -> RunOwnedInitialAdmissionFixtureCapability.readCapability(capabilityFile)) .isInstanceOf(RunOwnedInitialAdmissionFixtureCapability.InvalidCapabilityException.class); } + @Test + void readsReadOnlyCapabilityFile(@TempDir Path directory) throws Exception { + String json = validJson(); + Path capabilityFile = + Files.writeString(directory.resolve("fixture-capability.json"), json); + Files.setPosixFilePermissions(capabilityFile, Set.of(PosixFilePermission.OWNER_READ)); + + assertThat(RunOwnedInitialAdmissionFixtureCapability.readCapability(capabilityFile)) + .isEqualTo(json.getBytes(java.nio.charset.StandardCharsets.UTF_8)); + } + @Test void derivesPinsFromActualLeafAndCaCertificatesAndRequiresOneExactUriSan() throws Exception { X509Certificate leaf = diff --git a/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/data/TestDataSeederTest.java b/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/data/TestDataSeederTest.java index aa2a4bd832..11cb584668 100644 --- a/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/data/TestDataSeederTest.java +++ b/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/data/TestDataSeederTest.java @@ -2,13 +2,11 @@ import static org.mockito.ArgumentMatchers.any; import static org.mockito.Mockito.verify; -import static org.mockito.Mockito.verifyNoInteractions; import static org.mockito.Mockito.when; import net.firedevops.firemud.gamesession.entity.FeatureFlag; import net.firedevops.firemud.gamesession.entity.GameManifest; import net.firedevops.firemud.gamesession.repository.FeatureFlagRepository; -import net.firedevops.firemud.gamesession.repository.GameInstanceRepository; import net.firedevops.firemud.gamesession.repository.GameManifestRepository; import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.Test; @@ -21,7 +19,6 @@ class TestDataSeederTest { @Mock GameManifestRepository gameManifestRepository; @Mock FeatureFlagRepository featureFlagRepository; - @Mock GameInstanceRepository gameInstanceRepository; private TestDataSeeder seeder; @@ -40,6 +37,5 @@ void runSeedsCanonicalNonRuntimeData() throws Exception { verify(gameManifestRepository).save(any(GameManifest.class)); verify(featureFlagRepository).save(any(FeatureFlag.class)); - verifyNoInteractions(gameInstanceRepository); } } diff --git a/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/support/MutableDefaultDemoCatalogTest.java b/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/support/MutableDefaultDemoCatalogTest.java index a14949d59e..d7dce9e9b2 100644 --- a/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/support/MutableDefaultDemoCatalogTest.java +++ b/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/support/MutableDefaultDemoCatalogTest.java @@ -58,6 +58,21 @@ void persistedMatchingPointerTakesPrecedenceOverTheBaselineFallback() { assertThat(realm.catalogRevision()).isEqualTo(12L); } + @Test + void selectorForAnotherTenantAlsoOccupiesTheDefaultFallbackSelector() { + MutablePointerAuthority authority = new MutablePointerAuthority(); + TestGameplayWorldCatalogs.MutableDefaultDemoCatalog fixture = fixture(authority); + fixture.useDefaultDemo(TENANT_ID, BASELINE_GAME_INSTANCE_ID); + authority.setPointers(List.of(pointer("demo", "production", TENANT_ID + 1L, 99L, 8L, 12L))); + + GameplayWorldCatalog catalog = fixture.catalog(); + GameplayWorldCatalog.RealmView realm = + catalog.resolveDefaultRealm(catalog.resolveWorld("demo").orElseThrow()).orElseThrow(); + + assertThat(realm.tenantId()).isEqualTo(TENANT_ID + 1L); + assertThat(realm.gameInstanceId()).isEqualTo(99L); + } + @Test void clearingTheFallbackRestoresMissingAuthority() { MutablePointerAuthority authority = new MutablePointerAuthority(); diff --git a/services/game-session-service/src/testFixtures/java/net/firedevops/firemud/gamesession/CrossServiceAppHarness.java b/services/game-session-service/src/testFixtures/java/net/firedevops/firemud/gamesession/CrossServiceAppHarness.java index 61133601f2..ba2e3413b6 100644 --- a/services/game-session-service/src/testFixtures/java/net/firedevops/firemud/gamesession/CrossServiceAppHarness.java +++ b/services/game-session-service/src/testFixtures/java/net/firedevops/firemud/gamesession/CrossServiceAppHarness.java @@ -29,6 +29,7 @@ import net.firedevops.firemud.gamesession.service.RunOwnedInitialLaunchResult; import net.firedevops.firemud.gamesession.support.TestGameplayWorldCatalogs; import org.springframework.beans.factory.annotation.Qualifier; +import org.springframework.boot.autoconfigure.condition.ConditionalOnProperty; import org.springframework.boot.builder.SpringApplicationBuilder; import org.springframework.boot.test.context.TestConfiguration; import org.springframework.boot.web.server.context.WebServerApplicationContext; @@ -322,10 +323,44 @@ public void clear(long tenantId, long gameInstanceId, long characterId) { }; } + @Bean(name = "gameInstanceServiceImpl") + @ConditionalOnProperty( + name = "firemud.database.enabled", havingValue = "false", matchIfMissing = true) + GameInstanceService gameInstanceServiceImpl() { + return stubGameInstanceService(); + } + @Bean(name = "crossServiceTestGameInstanceService") @Primary + @ConditionalOnProperty(name = "firemud.database.enabled", havingValue = "true") GameInstanceService gameInstanceService( @Qualifier("gameInstanceServiceImpl") GameInstanceService actualGameInstanceService) { + GameInstanceService stubGameInstanceService = stubGameInstanceService(); + return new GameInstanceService() { + @Override + public GameInstanceDto startSession( + StartSessionRequest request, boolean replaceExistingFirst) { + return stubGameInstanceService.startSession(request, replaceExistingFirst); + } + + @Override + public GameInstanceDto stopSession(long sessionId) { + return stubGameInstanceService.stopSession(sessionId); + } + + @Override + public GameInstanceDto restartSession(long sessionId) { + return stubGameInstanceService.restartSession(sessionId); + } + + @Override + public RunOwnedInitialLaunchResult startRunOwnedInitialLaunch(StartSessionRequest request) { + return actualGameInstanceService.startRunOwnedInitialLaunch(request); + } + }; + } + + private static GameInstanceService stubGameInstanceService() { return new GameInstanceService() { @Override public GameInstanceDto startSession( @@ -359,7 +394,8 @@ public GameInstanceDto restartSession(long sessionId) { @Override public RunOwnedInitialLaunchResult startRunOwnedInitialLaunch(StartSessionRequest request) { - return actualGameInstanceService.startRunOwnedInitialLaunch(request); + throw new IllegalStateException( + "run-owned launch requires a database-enabled test context"); } }; } diff --git a/services/game-session-service/src/testFixtures/java/net/firedevops/firemud/gamesession/support/TestGameplayWorldCatalogs.java b/services/game-session-service/src/testFixtures/java/net/firedevops/firemud/gamesession/support/TestGameplayWorldCatalogs.java index 39881475c4..39ff3de318 100644 --- a/services/game-session-service/src/testFixtures/java/net/firedevops/firemud/gamesession/support/TestGameplayWorldCatalogs.java +++ b/services/game-session-service/src/testFixtures/java/net/firedevops/firemud/gamesession/support/TestGameplayWorldCatalogs.java @@ -78,8 +78,7 @@ private List worlds() { && pointers.stream() .noneMatch( pointer -> - pointer.tenantId() == fallback.tenantId() - && pointer.worldSlug().equals(fallback.worldSlug()) + pointer.worldSlug().equals(fallback.worldSlug()) && pointer.realmSlug().equals(fallback.realmSlug()))) { pointers.add(fallback); } diff --git a/services/world-management-service/src/main/java/net/firedevops/firemud/worldmanagement/client/GameSessionInitialAdmissionBindProofClient.java b/services/world-management-service/src/main/java/net/firedevops/firemud/worldmanagement/client/GameSessionInitialAdmissionBindProofClient.java index df12533b33..aa09750a17 100644 --- a/services/world-management-service/src/main/java/net/firedevops/firemud/worldmanagement/client/GameSessionInitialAdmissionBindProofClient.java +++ b/services/world-management-service/src/main/java/net/firedevops/firemud/worldmanagement/client/GameSessionInitialAdmissionBindProofClient.java @@ -3,7 +3,7 @@ import net.firedevops.firemud.worldmanagement.dto.InitialAdmissionBindOwnerProof; import net.firedevops.firemud.worldmanagement.entity.InitialAdmissionBindHold; -/** Authenticated Game Session owner-read boundary; no implementation is wired in this slice. */ +/** Authenticated Game Session owner-read boundary used by World hold reconciliation. */ public interface GameSessionInitialAdmissionBindProofClient { InitialAdmissionBindOwnerProof readOwnerProof(InitialAdmissionBindHold hold); } diff --git a/services/world-management-service/src/main/java/net/firedevops/firemud/worldmanagement/repository/RoomRepository.java b/services/world-management-service/src/main/java/net/firedevops/firemud/worldmanagement/repository/RoomRepository.java index cb91c3f047..29f96fffe6 100644 --- a/services/world-management-service/src/main/java/net/firedevops/firemud/worldmanagement/repository/RoomRepository.java +++ b/services/world-management-service/src/main/java/net/firedevops/firemud/worldmanagement/repository/RoomRepository.java @@ -157,11 +157,34 @@ private boolean sameSeededTemplateIdentity(Room existing, Room requested) { } private void advanceRoomIdSequence() { - dsl.fetchValue( - "SELECT setval(pg_get_serial_sequence('room', 'id'), " + Record sequenceRecord = + dsl.fetchOne("SELECT pg_catalog.pg_get_serial_sequence('room', 'id')"); + String sequenceName = sequenceRecord == null ? null : sequenceRecord.get(0, String.class); + if (sequenceName == null) { + throw new IllegalStateException("Room ID sequence could not be resolved"); + } + Record quotedSequenceRecord = + dsl.fetchOne( + "SELECT pg_catalog.format('%I.%I', sequence_namespace.nspname, sequence_class.relname) " + + "FROM pg_catalog.pg_class AS sequence_class " + + "JOIN pg_catalog.pg_namespace AS sequence_namespace " + + "ON sequence_namespace.oid = sequence_class.relnamespace " + + "WHERE sequence_class.oid = ?::pg_catalog.regclass", + sequenceName); + String quotedSequenceName = + quotedSequenceRecord == null + ? null + : quotedSequenceRecord.get(0, String.class); + if (quotedSequenceName == null) { + throw new IllegalStateException("Resolved Room ID sequence name is invalid"); + } + dsl.fetchOne( + "SELECT pg_catalog.setval(?::pg_catalog.regclass, " + "GREATEST(COALESCE((SELECT MAX(id) FROM room), 1), " - + "COALESCE((SELECT last_value FROM room_id_seq), 1)), true)", - Long.class); + + "COALESCE((SELECT last_value FROM " + + quotedSequenceName + + "), 1)), true)", + sequenceName); } private Room toEntity(Record record) { diff --git a/services/world-management-service/src/main/java/net/firedevops/firemud/worldmanagement/service/impl/InitialAdmissionBindHoldReconciler.java b/services/world-management-service/src/main/java/net/firedevops/firemud/worldmanagement/service/impl/InitialAdmissionBindHoldReconciler.java index 034331688a..d8a6425293 100644 --- a/services/world-management-service/src/main/java/net/firedevops/firemud/worldmanagement/service/impl/InitialAdmissionBindHoldReconciler.java +++ b/services/world-management-service/src/main/java/net/firedevops/firemud/worldmanagement/service/impl/InitialAdmissionBindHoldReconciler.java @@ -12,7 +12,9 @@ import org.springframework.scheduling.annotation.Scheduled; import org.springframework.stereotype.Component; -/** Automatically reconciles World holds; until a GS adapter is wired, it stays fail-closed. */ +/** + * Automatically reconciles World holds and keeps them fenced when owner readback is unavailable. + */ @Component public class InitialAdmissionBindHoldReconciler { private static final Logger logger = diff --git a/services/world-management-service/src/test/java/integration/net/firedevops/firemud/worldmanagement/RoomRepositoryPostgresIntegrationTest.java b/services/world-management-service/src/test/java/integration/net/firedevops/firemud/worldmanagement/RoomRepositoryPostgresIntegrationTest.java index 0f1712ca91..552e786667 100644 --- a/services/world-management-service/src/test/java/integration/net/firedevops/firemud/worldmanagement/RoomRepositoryPostgresIntegrationTest.java +++ b/services/world-management-service/src/test/java/integration/net/firedevops/firemud/worldmanagement/RoomRepositoryPostgresIntegrationTest.java @@ -13,6 +13,7 @@ import net.firedevops.firemud.worldmanagement.repository.RegionRepository; import net.firedevops.firemud.worldmanagement.repository.RoomRepository; import net.firedevops.firemud.worldmanagement.repository.ZoneRepository; +import org.jooq.DSLContext; import org.junit.jupiter.api.Test; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.boot.test.context.SpringBootTest; @@ -51,6 +52,7 @@ static void configure(DynamicPropertyRegistry registry) { @Autowired private RegionRepository regionRepository; @Autowired private RoomRepository roomRepository; @Autowired private ZoneRepository zoneRepository; + @Autowired private DSLContext dsl; @MockitoBean private GrpcServerLifecycle grpcServerLifecycle; @MockitoBean private EntityManagementClient entityManagementClient; @@ -58,7 +60,8 @@ static void configure(DynamicPropertyRegistry registry) { @MockitoBean private GameSessionClient gameSessionClient; @Test - void seededRoomIdentityInsertAdvancesSequenceAndRejectsForeignCollision() { + void seededRoomIdentityInsertAdvancesRenamedSequenceAndRejectsForeignCollision() { + dsl.execute("ALTER SEQUENCE room_id_seq RENAME TO room_id_seq_fixture_rename"); Region region = new Region(); region.setTenantId(TENANT_ID); region.setVersionId(VERSION_ID); From 9c4fde85259b5ff0ce0ebe4bcfb9cdd5b1c35620 Mon Sep 17 00:00:00 2001 From: Ben Hook <5009589+benhook1013@users.noreply.github.com> Date: Sat, 3 Oct 2026 02:40:39 +1300 Subject: [PATCH 07/20] fix: validate database-free harness and narrow fixture identity checks --- .../system-architecture-multi-tenancy.md | 1 - ...wnedInitialAdmissionFixtureCapability.java | 8 ++- ...nedInitialAdmissionFixtureCoordinator.java | 10 ++- ...dInitialLaunchPostgresIntegrationTest.java | 7 +- .../CrossServiceAppHarnessTest.java | 1 + ...InitialAdmissionFixtureCapabilityTest.java | 9 ++- ...nitialAdmissionFixtureCoordinatorTest.java | 66 +++++++++++++++++++ .../gamesession/CrossServiceAppHarness.java | 29 ++++++-- .../repository/RoomRepository.java | 7 +- 9 files changed, 118 insertions(+), 20 deletions(-) diff --git a/design/architecture/system-architecture-multi-tenancy.md b/design/architecture/system-architecture-multi-tenancy.md index 3dfbaaf974..edddbdf005 100644 --- a/design/architecture/system-architecture-multi-tenancy.md +++ b/design/architecture/system-architecture-multi-tenancy.md @@ -15,7 +15,6 @@ The complete playtest initialization and lifecycle contract is owned by [ADR 013 ## Implementation Status The realm-catalog, admission-pointer, realm-local character, explicit first-join, and quota-boundary contracts below are normative target behavior. Current runtime proof is partial: `IssueConnectToken` and text `PLAY` consume the current Account membership adapter evidence `membershipExists`, `gameplayAdmissionAllowed`, `membershipVersion`, and `evaluatedAt`, and admit only when the membership and admission flags are true. Text `PLAY` validates the applicable private/playtest realm grant; `IssueConnectToken` checks the selected pointer/visibility and membership inputs but does not yet validate that applicable grant, so token grant validation remains an incomplete implementation/proof gap. The adapter has no lifecycle-state field. The obsolete implicit membership-writer surface has been removed; the membership-generation live reread at connect-token issuance is not implemented; Game Session now stores a positive `catalogRevision` and stable UUID `realmId`/`playableStateNamespaceId` with pointer/audit rows and compare-and-sets pointer version plus catalog revision; initial-admission binding is wired only for the opt-in local Compose fixture, not general `StartSession`, strict `JOIN`, or production startup (see the [Game Session runtime status](../project-management/implementation-tracking/game-session-runtime-and-tick-coordination.md#capability-status)); scoped-role population and tenant switching are not fully implemented/proved; authoritative entitlement freshness plus complete owning-service quota enforcement remain incomplete; and broader authority-generation claims, durable projections, and enforcement remain incomplete across issuer, account, tenant, and membership scopes. Explicit `JOIN`/`Join & Play` remains unimplemented, so the first-join flow remains target-state only. Playtest fork creation, reset, expiry automation, owner manifests, and lifecycle routes are also not implemented or end-to-end proved; this status does not weaken the target namespace and isolation rules above. Current Game Session bootstrap/reconnect context remains on the implementation-local `sessionctx:*` family, including the unscoped bootstrap key `sessionctx:session::context` and the tenant-scoped keys `sessionctx:::context`, `sessionctx::identity:::context`, and `sessionctx::identity::name::context`; these old per-instance identity keys and the current `{tenantId, gameInstanceId, characterId}` uniqueness are implementation drift. The target-only `session:game:{tenantGameplayTag}:...` family uses `{tenantGameplayTag}` as a server-derived, deterministic, injective projection of authoritative `tenantId`, allocated through an authoritative persisted tenant-to-tag mapping with an immutable allocation version. Its character uniqueness projection is keyed by `{tenantId, playableStateNamespaceId, characterId}`; server-derived `playableStateScope` remains binding/routing evidence, while its value/evidence retains `{sessionId, gameInstanceId, bindingGeneration}`. The controller-transfer authority is summarized by [ADR 0132](./decisions/adr-0132-namespace-scoped-single-character-controller.md) and [Session Behavior](./system-architecture-session-behavior.md#namespace-scoped-controller-transfer-session-02). Existing mappings are always reused; a new allocation is committed atomically with uniqueness for both the tenant and tag, and a candidate tag already mapped to another tenant is rejected even when the candidate allocation version differs. Algorithm or encoding-version changes preserve existing mappings and may affect only future tenants. Its concrete encoding and version remain opaque to clients and other services; `tenantId` remains authoritative in APIs and persistence. Required focused proof covers distinct-tenant separation, same-tenant stability across process restart with the persisted assignment/version, concurrent first allocation returning one assignment, rejection of a tag collision across allocation versions, and rejection of an active-binding `bindingRef` whose tenant differs from the requested tenant. No end-to-end proof yet demonstrates these target invariants. The remaining gaps do not change the distinct stable `tenantSlug` and tenant-scoped authored-world `worldSlug` selectors, tenant-local `realmSlug` to durable `realmId` resolution, exact-tenant quota binding, or required `GetAdmissionPointer(tenantId, realmId)` contract. ---- --- diff --git a/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/data/RunOwnedInitialAdmissionFixtureCapability.java b/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/data/RunOwnedInitialAdmissionFixtureCapability.java index bf6d7bc031..beaade5843 100644 --- a/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/data/RunOwnedInitialAdmissionFixtureCapability.java +++ b/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/data/RunOwnedInitialAdmissionFixtureCapability.java @@ -15,6 +15,7 @@ import java.nio.file.StandardOpenOption; import java.nio.file.attribute.BasicFileAttributes; import java.nio.file.attribute.PosixFilePermission; +import java.security.GeneralSecurityException; import java.security.MessageDigest; import java.security.NoSuchAlgorithmException; import java.security.cert.Certificate; @@ -219,7 +220,7 @@ static CertificatePins certificatePins(X509Certificate leaf, X509Certificate ca) ca.checkValidity(); leaf.verify(ca.getPublicKey()); return new CertificatePins(fingerprint(leaf), uriSan, fingerprint(ca)); - } catch (Exception exception) { + } catch (GeneralSecurityException exception) { throw invalidCapability(); } } @@ -403,9 +404,12 @@ private static void requireExpectedRunBinding(String runId, String projectName) } private static boolean isCanonicalUuid(String value) { + if (value == null) { + return false; + } try { return UUID.fromString(value).toString().equals(value); - } catch (IllegalArgumentException | NullPointerException exception) { + } catch (IllegalArgumentException exception) { return false; } } 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 index ed548a8347..0843a55343 100644 --- 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 @@ -461,18 +461,24 @@ private static String asCanonicalUuid(UUID value) { } private static boolean isCanonicalUuid(String value) { + if (value == null) { + return false; + } try { return UUID.fromString(value).toString().equals(value); - } catch (IllegalArgumentException | NullPointerException exception) { + } 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 | NullPointerException exception) { + } catch (NumberFormatException exception) { return false; } } diff --git a/services/game-session-service/src/test/java/integration/net/firedevops/firemud/gamesession/service/RunOwnedInitialLaunchPostgresIntegrationTest.java b/services/game-session-service/src/test/java/integration/net/firedevops/firemud/gamesession/service/RunOwnedInitialLaunchPostgresIntegrationTest.java index eae9d18e0e..e220598559 100644 --- a/services/game-session-service/src/test/java/integration/net/firedevops/firemud/gamesession/service/RunOwnedInitialLaunchPostgresIntegrationTest.java +++ b/services/game-session-service/src/test/java/integration/net/firedevops/firemud/gamesession/service/RunOwnedInitialLaunchPostgresIntegrationTest.java @@ -71,8 +71,8 @@ void concurrentExactIdentityAllocationConvergesAndOrdinaryRowsRemainNullable() t .isEqualTo(1L); assertThat( dsl.fetchOne( - "SELECT run_owned_start_request_digest FROM game_instances WHERE id = ?", - firstId) + "SELECT run_owned_start_request_digest FROM game_instances WHERE id = ?", + firstId) .get(0, String.class)) .isEqualTo(REQUEST_DIGEST); @@ -82,8 +82,7 @@ void concurrentExactIdentityAllocationConvergesAndOrdinaryRowsRemainNullable() t failure -> { assertThat(sqlState(failure)).isEqualTo("23505"); assertThat( - hasCauseMessage( - failure, "game_instances_run_owned_start_request_unique")) + hasCauseMessage(failure, "game_instances_run_owned_start_request_unique")) .isTrue(); }); diff --git a/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/CrossServiceAppHarnessTest.java b/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/CrossServiceAppHarnessTest.java index a22fef1865..818c6986fb 100644 --- a/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/CrossServiceAppHarnessTest.java +++ b/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/CrossServiceAppHarnessTest.java @@ -28,6 +28,7 @@ void databaseDisabledOrMissingReplacesTheRealServiceWithTheStub() { for (String databaseEnabled : new String[] {"false", null}) { try (AnnotationConfigApplicationContext context = context(databaseEnabled)) { assertThat(context.getBeanNamesForType(DataSource.class)).isEmpty(); + assertThat(context.getBeanNamesForType(GameInstanceServiceImpl.class)).isEmpty(); assertThat(context.getBean("gameInstanceServiceImpl")) .isNotInstanceOf(GameInstanceServiceImpl.class); 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 bb582c7ca3..938dc0fa38 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 @@ -52,6 +52,12 @@ void rejectsUnknownDuplicateMismatchedAndNoncanonicalCapabilityFields() { assertInvalid(validJson().replace("\"schema\":", "\"extra\":true,\"schema\":")); assertInvalid(validJson().replace("\"schema\":", "\"schema\":\"wrong\",\"schema\":")); assertInvalid(validJson().replace(RUN_ID, "different-run")); + assertInvalid(validJson().replace(OPERATION_ID, "not-a-uuid")); + assertInvalid( + validJson() + .replace( + "\"operationId\": \"" + OPERATION_ID + "\"", + "\"operationId\": null")); assertInvalid(validJson().replace("\"tenantId\": 7", "\"tenantId\": \"7\"")); assertInvalid( validJson().replace("\"stateScope\": \"SHARED\"", "\"stateScope\": \"ISOLATED\"")); @@ -79,8 +85,7 @@ void rejectsWritableCapabilityFile(@TempDir Path directory) throws Exception { @Test void readsReadOnlyCapabilityFile(@TempDir Path directory) throws Exception { String json = validJson(); - Path capabilityFile = - Files.writeString(directory.resolve("fixture-capability.json"), json); + Path capabilityFile = Files.writeString(directory.resolve("fixture-capability.json"), json); Files.setPosixFilePermissions(capabilityFile, Set.of(PosixFilePermission.OWNER_READ)); assertThat(RunOwnedInitialAdmissionFixtureCapability.readCapability(capabilityFile)) 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 index 1e136ea6fb..93db253776 100644 --- 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 @@ -144,6 +144,72 @@ void rejectsMismatchedWorldHoldBeforeAttachingOrCommitting() { 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)) + .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)) + .isInstanceOf(IllegalStateException.class); + } + } + @Test void terminalWorldAbortUsesExactReadbackWithoutTryingToCommit() { Fixture fixture = diff --git a/services/game-session-service/src/testFixtures/java/net/firedevops/firemud/gamesession/CrossServiceAppHarness.java b/services/game-session-service/src/testFixtures/java/net/firedevops/firemud/gamesession/CrossServiceAppHarness.java index ba2e3413b6..e404cbf03b 100644 --- a/services/game-session-service/src/testFixtures/java/net/firedevops/firemud/gamesession/CrossServiceAppHarness.java +++ b/services/game-session-service/src/testFixtures/java/net/firedevops/firemud/gamesession/CrossServiceAppHarness.java @@ -29,6 +29,10 @@ import net.firedevops.firemud.gamesession.service.RunOwnedInitialLaunchResult; import net.firedevops.firemud.gamesession.support.TestGameplayWorldCatalogs; import org.springframework.beans.factory.annotation.Qualifier; +import org.springframework.beans.factory.config.ConfigurableListableBeanFactory; +import org.springframework.beans.factory.support.BeanDefinitionRegistry; +import org.springframework.beans.factory.support.BeanDefinitionRegistryPostProcessor; +import org.springframework.beans.factory.support.RootBeanDefinition; import org.springframework.boot.autoconfigure.condition.ConditionalOnProperty; import org.springframework.boot.builder.SpringApplicationBuilder; import org.springframework.boot.test.context.TestConfiguration; @@ -323,11 +327,28 @@ public void clear(long tenantId, long gameInstanceId, long characterId) { }; } - @Bean(name = "gameInstanceServiceImpl") + @Bean @ConditionalOnProperty( - name = "firemud.database.enabled", havingValue = "false", matchIfMissing = true) - GameInstanceService gameInstanceServiceImpl() { - return stubGameInstanceService(); + name = "firemud.database.enabled", + havingValue = "false", + matchIfMissing = true) + // Replace the scanned service before eager singleton creation in database-free tests. + static BeanDefinitionRegistryPostProcessor disabledDatabaseGameInstanceServiceStub() { + return new BeanDefinitionRegistryPostProcessor() { + @Override + public void postProcessBeanDefinitionRegistry(BeanDefinitionRegistry registry) { + if (registry.containsBeanDefinition("gameInstanceServiceImpl")) { + registry.removeBeanDefinition("gameInstanceServiceImpl"); + } + RootBeanDefinition stub = new RootBeanDefinition(GameInstanceService.class); + stub.setInstanceSupplier(GameSessionTestOverrides::stubGameInstanceService); + stub.setPrimary(true); + registry.registerBeanDefinition("gameInstanceServiceImpl", stub); + } + + @Override + public void postProcessBeanFactory(ConfigurableListableBeanFactory beanFactory) {} + }; } @Bean(name = "crossServiceTestGameInstanceService") diff --git a/services/world-management-service/src/main/java/net/firedevops/firemud/worldmanagement/repository/RoomRepository.java b/services/world-management-service/src/main/java/net/firedevops/firemud/worldmanagement/repository/RoomRepository.java index 29f96fffe6..e80692ea4b 100644 --- a/services/world-management-service/src/main/java/net/firedevops/firemud/worldmanagement/repository/RoomRepository.java +++ b/services/world-management-service/src/main/java/net/firedevops/firemud/worldmanagement/repository/RoomRepository.java @@ -157,8 +157,7 @@ private boolean sameSeededTemplateIdentity(Room existing, Room requested) { } private void advanceRoomIdSequence() { - Record sequenceRecord = - dsl.fetchOne("SELECT pg_catalog.pg_get_serial_sequence('room', 'id')"); + Record sequenceRecord = dsl.fetchOne("SELECT pg_catalog.pg_get_serial_sequence('room', 'id')"); String sequenceName = sequenceRecord == null ? null : sequenceRecord.get(0, String.class); if (sequenceName == null) { throw new IllegalStateException("Room ID sequence could not be resolved"); @@ -172,9 +171,7 @@ private void advanceRoomIdSequence() { + "WHERE sequence_class.oid = ?::pg_catalog.regclass", sequenceName); String quotedSequenceName = - quotedSequenceRecord == null - ? null - : quotedSequenceRecord.get(0, String.class); + quotedSequenceRecord == null ? null : quotedSequenceRecord.get(0, String.class); if (quotedSequenceName == null) { throw new IllegalStateException("Resolved Room ID sequence name is invalid"); } From 201363e4797861a2ae74212bda4cef82be597ff8 Mon Sep 17 00:00:00 2001 From: Ben Hook <5009589+benhook1013@users.noreply.github.com> Date: Sat, 3 Oct 2026 02:57:25 +1300 Subject: [PATCH 08/20] test: prove required query rows and portable bootstrap fixtures --- ...lAdmissionBindPostgresIntegrationTest.java | 39 ++++++++------- ...dInitialLaunchPostgresIntegrationTest.java | 31 +++++++----- ...InitialAdmissionFixtureCapabilityTest.java | 47 +++++++++---------- ...nitialAdmissionFixtureCoordinatorTest.java | 2 +- .../InitialAdmissionBindHoldRepository.java | 5 ++ 5 files changed, 69 insertions(+), 55 deletions(-) diff --git a/services/game-session-service/src/test/java/integration/net/firedevops/firemud/gamesession/service/InitialAdmissionBindPostgresIntegrationTest.java b/services/game-session-service/src/test/java/integration/net/firedevops/firemud/gamesession/service/InitialAdmissionBindPostgresIntegrationTest.java index 8e7340f7bc..00cacfbd04 100644 --- a/services/game-session-service/src/test/java/integration/net/firedevops/firemud/gamesession/service/InitialAdmissionBindPostgresIntegrationTest.java +++ b/services/game-session-service/src/test/java/integration/net/firedevops/firemud/gamesession/service/InitialAdmissionBindPostgresIntegrationTest.java @@ -4,6 +4,7 @@ import static org.assertj.core.api.Assertions.assertThatThrownBy; import java.nio.file.Path; +import java.util.Objects; import net.firedevops.firemud.gamesession.entity.GameInstance; import net.firedevops.firemud.gamesession.repository.GameInstanceRepository; import net.firedevops.firemud.gamesession.repository.GameplayAdmissionPointerEventRepository; @@ -111,26 +112,30 @@ void initialAdmissionLedgerCommitsPointerAuditAndAttemptTogetherAndReadbackFails assertThat(committed.pointerAuditRequestDigest()).isEqualTo(request.requestDigest()); assertThat(committed.pointerVersion()).isEqualTo(1L); assertThat( - dsl.fetchOne( - "SELECT pointer.catalog_revision AS pointer_revision, " - + "event.catalog_revision AS event_revision, pointer.realm_id, " - + "event.realm_id AS event_realm_id, pointer.playable_state_namespace_id, " - + "event.playable_state_namespace_id AS event_namespace_id " - + "FROM gameplay_initial_admission_bind_attempt attempt " - + "JOIN gameplay_admission_pointer pointer ON pointer.id = attempt.pointer_id " - + "JOIN gameplay_admission_pointer_event event ON event.id = attempt.audit_event_id " - + "WHERE attempt.attempt_id = ?", - attempt.attemptId()) + Objects.requireNonNull( + dsl.fetchOne( + "SELECT pointer.catalog_revision AS pointer_revision, " + + "event.catalog_revision AS event_revision, pointer.realm_id, " + + "event.realm_id AS event_realm_id, pointer.playable_state_namespace_id, " + + "event.playable_state_namespace_id AS event_namespace_id " + + "FROM gameplay_initial_admission_bind_attempt attempt " + + "JOIN gameplay_admission_pointer pointer ON pointer.id = attempt.pointer_id " + + "JOIN gameplay_admission_pointer_event event ON event.id = attempt.audit_event_id " + + "WHERE attempt.attempt_id = ?", + attempt.attemptId()), + "expected committed initial-admission pointer/audit row") .get("pointer_revision", Long.class)) .isEqualTo(1L); var evidence = - dsl.fetchOne( - "SELECT event.catalog_revision AS event_revision, event.realm_id AS event_realm_id, " - + "event.playable_state_namespace_id AS event_namespace_id " - + "FROM gameplay_initial_admission_bind_attempt attempt " - + "JOIN gameplay_admission_pointer_event event ON event.id = attempt.audit_event_id " - + "WHERE attempt.attempt_id = ?", - attempt.attemptId()); + Objects.requireNonNull( + dsl.fetchOne( + "SELECT event.catalog_revision AS event_revision, event.realm_id AS event_realm_id, " + + "event.playable_state_namespace_id AS event_namespace_id " + + "FROM gameplay_initial_admission_bind_attempt attempt " + + "JOIN gameplay_admission_pointer_event event ON event.id = attempt.audit_event_id " + + "WHERE attempt.attempt_id = ?", + attempt.attemptId()), + "expected committed initial-admission audit evidence row"); assertThat(evidence.get("event_revision", Long.class)).isEqualTo(1L); assertThat(evidence.get("event_realm_id", java.util.UUID.class).toString()) .isEqualTo(catalog.realmId()); diff --git a/services/game-session-service/src/test/java/integration/net/firedevops/firemud/gamesession/service/RunOwnedInitialLaunchPostgresIntegrationTest.java b/services/game-session-service/src/test/java/integration/net/firedevops/firemud/gamesession/service/RunOwnedInitialLaunchPostgresIntegrationTest.java index e220598559..d6766d3d57 100644 --- a/services/game-session-service/src/test/java/integration/net/firedevops/firemud/gamesession/service/RunOwnedInitialLaunchPostgresIntegrationTest.java +++ b/services/game-session-service/src/test/java/integration/net/firedevops/firemud/gamesession/service/RunOwnedInitialLaunchPostgresIntegrationTest.java @@ -5,6 +5,7 @@ import java.nio.file.Path; import java.sql.SQLException; +import java.util.Objects; import java.util.concurrent.CountDownLatch; import java.util.concurrent.Executors; import java.util.concurrent.TimeUnit; @@ -62,17 +63,21 @@ void concurrentExactIdentityAllocationConvergesAndOrdinaryRowsRemainNullable() t long secondId = second.get(15, TimeUnit.SECONDS); assertThat(firstId).isEqualTo(secondId); assertThat( - dsl.fetchOne( - "SELECT count(*) FROM game_instances WHERE tenant_id = ? " - + "AND run_owned_start_request_id = ?", - TENANT_ID, - REQUEST_ID) + Objects.requireNonNull( + dsl.fetchOne( + "SELECT count(*) FROM game_instances WHERE tenant_id = ? " + + "AND run_owned_start_request_id = ?", + TENANT_ID, + REQUEST_ID), + "expected run-owned allocation count row") .get(0, Long.class)) .isEqualTo(1L); assertThat( - dsl.fetchOne( - "SELECT run_owned_start_request_digest FROM game_instances WHERE id = ?", - firstId) + Objects.requireNonNull( + dsl.fetchOne( + "SELECT run_owned_start_request_digest FROM game_instances WHERE id = ?", + firstId), + "expected allocated run-owned game instance row") .get(0, String.class)) .isEqualTo(REQUEST_DIGEST); @@ -91,10 +96,12 @@ void concurrentExactIdentityAllocationConvergesAndOrdinaryRowsRemainNullable() t assertThat(savedOrdinaryOne.getRunOwnedStartRequestId()).isNull(); assertThat(savedOrdinaryTwo.getRunOwnedStartRequestId()).isNull(); assertThat( - dsl.fetchOne( - "SELECT count(*) FROM game_instances WHERE tenant_id = ? " - + "AND run_owned_start_request_id IS NULL", - TENANT_ID) + Objects.requireNonNull( + dsl.fetchOne( + "SELECT count(*) FROM game_instances WHERE tenant_id = ? " + + "AND run_owned_start_request_id IS NULL", + TENANT_ID), + "expected ordinary game-instance count row") .get(0, Long.class)) .isEqualTo(2L); } 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 938dc0fa38..ae05ad6384 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 @@ -54,10 +54,7 @@ void rejectsUnknownDuplicateMismatchedAndNoncanonicalCapabilityFields() { assertInvalid(validJson().replace(RUN_ID, "different-run")); assertInvalid(validJson().replace(OPERATION_ID, "not-a-uuid")); assertInvalid( - validJson() - .replace( - "\"operationId\": \"" + OPERATION_ID + "\"", - "\"operationId\": null")); + validJson().replace("\"operationId\": \"" + OPERATION_ID + "\"", "\"operationId\": null")); assertInvalid(validJson().replace("\"tenantId\": 7", "\"tenantId\": \"7\"")); assertInvalid( validJson().replace("\"stateScope\": \"SHARED\"", "\"stateScope\": \"ISOLATED\"")); @@ -127,27 +124,27 @@ private static CertificatePins pins() { private static String validJson() { 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" - } + {%n\ + "schema": "%s",%n\ + "runId": "%s",%n\ + "composeProjectName": "%s",%n\ + "operationId": "%s",%n\ + "tenantId": 7,%n\ + "gameTemplateId": 17,%n\ + "ownerAccountId": 27,%n\ + "worldSlug": "demo",%n\ + "worldDisplayName": "Demo World",%n\ + "realmSlug": "production",%n\ + "realmDisplayName": "Live Realm",%n\ + "visible": true,%n\ + "publicProductionRealm": true,%n\ + "requiresCharacterSelection": false,%n\ + "stateScope": "SHARED",%n\ + "characterCreationPolicy": "ALLOW_NEW",%n\ + "gameSessionLeafSha256": "%s",%n\ + "gameSessionUriSan": "%s",%n\ + "caCertificateSha256": "%s"%n\ + }%n\ """ .formatted( RunOwnedInitialAdmissionFixtureCapability.CAPABILITY_SCHEMA, 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 index 93db253776..be80bfe4be 100644 --- 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 @@ -48,7 +48,7 @@ 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 CAPABILITY_PATH = "fixture/capability.json"; private static final String OPERATION_ID = "d2db8478-9c56-42ab-99c2-9fbead6841ba"; 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"); diff --git a/services/world-management-service/src/main/java/net/firedevops/firemud/worldmanagement/repository/InitialAdmissionBindHoldRepository.java b/services/world-management-service/src/main/java/net/firedevops/firemud/worldmanagement/repository/InitialAdmissionBindHoldRepository.java index 090ea9e579..2f44d029a0 100644 --- a/services/world-management-service/src/main/java/net/firedevops/firemud/worldmanagement/repository/InitialAdmissionBindHoldRepository.java +++ b/services/world-management-service/src/main/java/net/firedevops/firemud/worldmanagement/repository/InitialAdmissionBindHoldRepository.java @@ -1,5 +1,6 @@ package net.firedevops.firemud.worldmanagement.repository; +import edu.umd.cs.findbugs.annotations.SuppressFBWarnings; import java.time.Instant; import java.time.LocalDateTime; import java.time.ZoneOffset; @@ -13,6 +14,10 @@ import org.springframework.stereotype.Repository; @Repository +@SuppressFBWarnings( + value = "EI_EXPOSE_REP2", + justification = + "The injected DSLContext is shared Spring infrastructure for repository transaction participation.") public class InitialAdmissionBindHoldRepository { private static final String SELECT_COLUMNS = "hold_id, hold_fence, tenant_id, realm_uuid, playable_state_namespace_uuid, " From c2209dd4cdb3fd29227bb65196ed9b8e29298d3f Mon Sep 17 00:00:00 2001 From: Ben Hook <5009589+benhook1013@users.noreply.github.com> Date: Sat, 3 Oct 2026 03:42:26 +1300 Subject: [PATCH 09/20] Fix initial-bind diagnostics and prove actual termination lock contention --- .../world-management-service/api-contracts.md | 4 + k8s/monitoring/prometheus-rules-firemud.yaml | 14 ++ ...nedInitialAdmissionFixtureCoordinator.java | 36 +++- ...nitialAdmissionFixtureCoordinatorTest.java | 67 +++++++ .../InitialAdmissionBindHoldRepository.java | 12 +- .../InitialAdmissionBindHoldReconciler.java | 96 +++++++-- ...issionBindHoldPostgresIntegrationTest.java | 53 +++++ ...nitialAdmissionBindHoldRepositoryTest.java | 41 ++++ ...nitialAdmissionBindHoldReconcilerTest.java | 183 +++++++++++++++++- 9 files changed, 480 insertions(+), 26 deletions(-) diff --git a/design/architecture/microservices/world-management-service/api-contracts.md b/design/architecture/microservices/world-management-service/api-contracts.md index 8bb7f741ff..340b01d865 100644 --- a/design/architecture/microservices/world-management-service/api-contracts.md +++ b/design/architecture/microservices/world-management-service/api-contracts.md @@ -271,6 +271,10 @@ World finalizes only after an authenticated exact Game Session owner readback pr Current implementation includes the typed `AcquireInitialAdmissionBindHold` RPC restricted to the authenticated Game Session workload, the separate durable World hold record, lifecycle-row serialization that blocks termination while the hold is unresolved, scheduled fail-closed reconciliation, and a method-specific authenticated Game Session owner-read adapter. The run-owned local Compose fixture coordinator now reaches this hold after Game Session records its durable initial-bind intent; the World-owned reconciler resolves it only from authenticated exact owner proof. This remains an opt-in fixture path, not a change to the hold contract or a production activation path. PostgreSQL race/restart proof remains outstanding, and unavailable or mismatched owner evidence continues to fence termination. See the [Game Session initial-admission implementation status](../game-session-service/api-contracts.md#initial-admission-bind), [World Runtime and Movement tracker](../../../project-management/implementation-tracking/world-runtime-and-movement.md) for implementation anchors and current proof state, and the [validation and runtime proof workflow](../../../developer-workflows/validation-and-runtime-proof.md) for check selection. The replacement hold contract above remains separate. +Overdue hold diagnostics are observational. World Management emits `world_initial_admission_bind_overdue_observations_total`, a counter whose unit is one nonterminal hold observation in a bounded reconciliation scan at or after its authoritative `diagnosticExpiresAt`; a repeated scan of the same hold increments it again, so it is not a unique-hold count. Its only label is `error_code`, limited to `none`, `GS_OWNER_READ_UNAVAILABLE`, `GS_OWNER_READ_FAILED`, `GS_OWNER_PROOF_MISSING`, `GS_OWNER_NOT_FOUND`, `GS_OWNER_PENDING`, `GS_OWNER_UNAVAILABLE`, `GS_OWNER_ERROR`, `GS_OWNER_PROOF_MISMATCH`, `GS_OWNER_TERMINAL_PROOF_INCOMPLETE`, `WORLD_LIFECYCLE_PROOF_MISMATCH`, or `other`. Unknown persisted codes map to `other`. The counter never carries tenant, hold, realm, or runtime identifiers; scoped structured reconciliation logs retain the exact `holdId`, `tenantId`, and `gameInstanceId` for diagnosis. The `InitialAdmissionBindHoldOverdueObservations` alert is a diagnostic signal only. Neither its firing nor its absence authorizes readiness, termination, or hold release. + +Operator procedure: use the scoped World reconciliation log fields to identify the exact hold, then inspect that World hold and the corresponding authenticated Game Session owner-read evidence against the complete bound identity in this contract. If owner transport or workload identity is unavailable, repair that dependency and retry through the existing scheduled reconciler using the same hold identity. Only exact authenticated `COMMITTED` or definitive `ABORTED` owner proof may resolve the hold. Never edit either database directly, release a hold because its diagnostic age elapsed, fabricate an abort, or use a raw pointer as proof; unavailable or mismatched evidence continues to fence termination. + ## Instance Termination Contract World Management owns the authoritative lifecycle row and monotonic epoch for `gameInstanceId` rows. The lifecycle state, owner registry, cleanup acknowledgements, and Temporal boundary are owned by [ADR 0123](../../decisions/adr-0123-database-authoritative-temporal-coordinated-world-lifecycle.md); this section records the World API consequence. Teardown is cross-service: diff --git a/k8s/monitoring/prometheus-rules-firemud.yaml b/k8s/monitoring/prometheus-rules-firemud.yaml index e8d0d5e368..f42a5c9cfb 100644 --- a/k8s/monitoring/prometheus-rules-firemud.yaml +++ b/k8s/monitoring/prometheus-rules-firemud.yaml @@ -258,6 +258,20 @@ spec: summary: Player-facing reopen was attempted without complete convergence description: A controller-authoritative recovery release was attempted before cold-start convergence completed. Keep traffic quarantined and investigate the operation evidence and participant dispositions immediately. + - name: firemud.alerts.world-management + rules: + - alert: InitialAdmissionBindHoldOverdueObservations + expr: sum by (error_code) (increase(world_initial_admission_bind_overdue_observations_total[5m])) > 0 + for: 10m + labels: + service: world-management-service + severity: P2 + owner: gameplay + runbook: design/architecture/microservices/world-management-service/api-contracts.md#initial-admission-bind-hold-contract + annotations: + summary: World observed unresolved initial-admission holds beyond diagnostic age + description: Repeated overdue observations require owner-proof and transport triage. This diagnostic alert does not authorize readiness, termination, or hold release; follow the exact owner-evidence procedure in the World initial-admission bind contract. + - name: firemud.recording.automation rules: - record: automation_retention_dead_letter_blocked_rows:max 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 index 0843a55343..807932a8cd 100644 --- 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 @@ -112,17 +112,26 @@ void retryRunOwnedFixtureBootstrap() { + " 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."); + + " 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.", + + " stable operation identity will be retried. exceptionType={} errorCode={}" + + " message={}", attempt, - MAX_ATTEMPTS); + MAX_ATTEMPTS, + diagnostic.exceptionType(), + diagnostic.errorCode(), + diagnostic.message()); } } finally { inProgress.set(false); @@ -487,6 +496,27 @@ 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/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 index be80bfe4be..83a07c8aae 100644 --- 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 @@ -7,6 +7,7 @@ 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; @@ -41,10 +42,14 @@ 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"; @@ -252,6 +257,68 @@ void disabledCoordinatorDoesNotLoadCapabilityOrCallOwners() { verifyNoInteractions(gameInstanceService, ownerService, 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()); + + 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); + + 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()); + + 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); + + 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 = diff --git a/services/world-management-service/src/main/java/net/firedevops/firemud/worldmanagement/repository/InitialAdmissionBindHoldRepository.java b/services/world-management-service/src/main/java/net/firedevops/firemud/worldmanagement/repository/InitialAdmissionBindHoldRepository.java index 2f44d029a0..7011b84675 100644 --- a/services/world-management-service/src/main/java/net/firedevops/firemud/worldmanagement/repository/InitialAdmissionBindHoldRepository.java +++ b/services/world-management-service/src/main/java/net/firedevops/firemud/worldmanagement/repository/InitialAdmissionBindHoldRepository.java @@ -70,14 +70,18 @@ public List findNonterminal(int limit) { } public boolean hasNonterminalForRealm(long tenantId, String realmUuid) { - return Boolean.TRUE.equals( - dsl.fetchValue( + Record result = + dsl.fetchOne( "SELECT EXISTS (SELECT 1 FROM initial_admission_bind_hold " + "WHERE tenant_id = ? AND realm_uuid = ?::uuid " + "AND status IN ('PENDING', 'RECONCILIATION_REQUIRED'))", - Boolean.class, tenantId, - UUID.fromString(realmUuid))); + UUID.fromString(realmUuid)); + if (result == null) { + throw new IllegalStateException( + "INITIAL_ADMISSION_BIND_HOLD_LOOKUP_FAILED: realm hold lookup returned no row"); + } + return Boolean.TRUE.equals(result.get(0, Boolean.class)); } public Optional insertIfNoUniqueConflict( diff --git a/services/world-management-service/src/main/java/net/firedevops/firemud/worldmanagement/service/impl/InitialAdmissionBindHoldReconciler.java b/services/world-management-service/src/main/java/net/firedevops/firemud/worldmanagement/service/impl/InitialAdmissionBindHoldReconciler.java index d8a6425293..dadcb6a870 100644 --- a/services/world-management-service/src/main/java/net/firedevops/firemud/worldmanagement/service/impl/InitialAdmissionBindHoldReconciler.java +++ b/services/world-management-service/src/main/java/net/firedevops/firemud/worldmanagement/service/impl/InitialAdmissionBindHoldReconciler.java @@ -1,8 +1,10 @@ package net.firedevops.firemud.worldmanagement.service.impl; +import io.micrometer.core.instrument.MeterRegistry; import java.time.Clock; import java.util.List; import net.firedevops.firemud.worldmanagement.client.GameSessionInitialAdmissionBindProofClient; +import net.firedevops.firemud.worldmanagement.dto.InitialAdmissionBindOwnerProof; import net.firedevops.firemud.worldmanagement.repository.InitialAdmissionBindHoldRepository; import net.firedevops.firemud.worldmanagement.service.InitialAdmissionBindHoldService; import org.slf4j.Logger; @@ -19,29 +21,35 @@ public class InitialAdmissionBindHoldReconciler { private static final Logger logger = LoggerFactory.getLogger(InitialAdmissionBindHoldReconciler.class); + private static final String OVERDUE_OBSERVATIONS_METRIC = + "world_initial_admission_bind_overdue_observations_total"; private final InitialAdmissionBindHoldRepository holdRepository; private final InitialAdmissionBindHoldService holdService; private final ObjectProvider proofClientProvider; private final Clock clock; + private final MeterRegistry meterRegistry; @Autowired public InitialAdmissionBindHoldReconciler( InitialAdmissionBindHoldRepository holdRepository, InitialAdmissionBindHoldService holdService, - ObjectProvider proofClientProvider) { - this(holdRepository, holdService, proofClientProvider, Clock.systemUTC()); + ObjectProvider proofClientProvider, + MeterRegistry meterRegistry) { + this(holdRepository, holdService, proofClientProvider, Clock.systemUTC(), meterRegistry); } InitialAdmissionBindHoldReconciler( InitialAdmissionBindHoldRepository holdRepository, InitialAdmissionBindHoldService holdService, ObjectProvider proofClientProvider, - Clock clock) { + Clock clock, + MeterRegistry meterRegistry) { this.holdRepository = holdRepository; this.holdService = holdService; this.proofClientProvider = proofClientProvider; this.clock = clock; + this.meterRegistry = meterRegistry; } @Scheduled(fixedDelayString = "${world.initial-admission-bind.reconcile-delay-ms:5000}") @@ -53,37 +61,93 @@ public void reconcilePendingHolds() { } GameSessionInitialAdmissionBindProofClient proofClient = proofClientProvider.getIfAvailable(); for (var hold : holds) { + boolean overdue = !hold.diagnosticExpiresAt().isAfter(clock.instant()); + String errorCode = boundedErrorCode(hold.reconciliationError()); try { - reconcileHold(hold, proofClient); + errorCode = reconcileHold(hold, proofClient); } catch (RuntimeException exception) { logger.warn( - "Initial admission bind reconciliation failed holdId={}", hold.holdId(), exception); + "Initial admission bind reconciliation failed holdId={} tenantId={} gameInstanceId={} errorType={}", + hold.holdId(), + hold.tenantId(), + hold.gameInstanceId(), + exception.getClass().getSimpleName()); + errorCode = "other"; + } finally { + if (overdue) { + String boundedCode = boundedErrorCode(errorCode); + meterRegistry.counter(OVERDUE_OBSERVATIONS_METRIC, "error_code", boundedCode).increment(); + logger.warn( + "Initial admission bind hold exceeded its diagnostic age holdId={} tenantId={} gameInstanceId={} errorCode={}", + hold.holdId(), + hold.tenantId(), + hold.gameInstanceId(), + boundedCode); + } } } } - private void reconcileHold( + private String reconcileHold( net.firedevops.firemud.worldmanagement.entity.InitialAdmissionBindHold hold, GameSessionInitialAdmissionBindProofClient proofClient) { if (proofClient == null) { holdService.requireReconciliation(hold.holdId(), "GS_OWNER_READ_UNAVAILABLE"); - return; - } - if (!hold.diagnosticExpiresAt().isAfter(clock.instant())) { - logger.warn( - "Initial admission bind hold exceeded its diagnostic age holdId={} tenant={} gameInstanceId={}", - hold.holdId(), - hold.tenantId(), - hold.gameInstanceId()); + return "GS_OWNER_READ_UNAVAILABLE"; } + + InitialAdmissionBindOwnerProof ownerProof; try { - holdService.reconcileOwnerProof(hold.holdId(), proofClient.readOwnerProof(hold)); + ownerProof = proofClient.readOwnerProof(hold); } catch (RuntimeException exception) { logger.warn( - "Initial admission bind owner readback failed holdId={} errorType={}", + "Initial admission bind owner readback failed holdId={} tenantId={} gameInstanceId={} errorType={}", hold.holdId(), + hold.tenantId(), + hold.gameInstanceId(), exception.getClass().getSimpleName()); holdService.requireReconciliation(hold.holdId(), "GS_OWNER_READ_FAILED"); + return "GS_OWNER_READ_FAILED"; + } + + var reconciled = holdService.reconcileOwnerProof(hold.holdId(), ownerProof); + if ("COMMITTED".equals(reconciled.status()) || "ABORTED".equals(reconciled.status())) { + return "none"; + } + return ownerProofErrorCode(ownerProof); + } + + private static String ownerProofErrorCode(InitialAdmissionBindOwnerProof ownerProof) { + if (ownerProof == null || ownerProof.outcome() == null) { + return "GS_OWNER_PROOF_MISSING"; + } + return switch (ownerProof.outcome()) { + case NOT_FOUND -> "GS_OWNER_NOT_FOUND"; + case PENDING -> "GS_OWNER_PENDING"; + case UNAVAILABLE -> "GS_OWNER_UNAVAILABLE"; + case ERROR -> "GS_OWNER_ERROR"; + case COMMITTED, ABORTED -> "other"; + }; + } + + private static String boundedErrorCode(String errorCode) { + if (errorCode == null || errorCode.isBlank()) { + return "none"; } + return switch (errorCode) { + case "none", + "GS_OWNER_READ_UNAVAILABLE", + "GS_OWNER_READ_FAILED", + "GS_OWNER_PROOF_MISSING", + "GS_OWNER_NOT_FOUND", + "GS_OWNER_PENDING", + "GS_OWNER_UNAVAILABLE", + "GS_OWNER_ERROR", + "GS_OWNER_PROOF_MISMATCH", + "GS_OWNER_TERMINAL_PROOF_INCOMPLETE", + "WORLD_LIFECYCLE_PROOF_MISMATCH" -> + errorCode; + default -> "other"; + }; } } diff --git a/services/world-management-service/src/test/java/integration/net/firedevops/firemud/worldmanagement/InitialAdmissionBindHoldPostgresIntegrationTest.java b/services/world-management-service/src/test/java/integration/net/firedevops/firemud/worldmanagement/InitialAdmissionBindHoldPostgresIntegrationTest.java index 77831ad9e6..64ff40f373 100644 --- a/services/world-management-service/src/test/java/integration/net/firedevops/firemud/worldmanagement/InitialAdmissionBindHoldPostgresIntegrationTest.java +++ b/services/world-management-service/src/test/java/integration/net/firedevops/firemud/worldmanagement/InitialAdmissionBindHoldPostgresIntegrationTest.java @@ -6,12 +6,14 @@ import static org.mockito.ArgumentMatchers.anyString; import static org.mockito.Mockito.doAnswer; +import java.util.Objects; import java.util.UUID; import java.util.concurrent.CountDownLatch; import java.util.concurrent.ExecutorService; import java.util.concurrent.Executors; import java.util.concurrent.Future; import java.util.concurrent.TimeUnit; +import java.util.concurrent.atomic.AtomicInteger; import net.firedevops.firemud.entitymanagement.v1.CleanupRuntimeInstanceResponse; import net.firedevops.firemud.test.PostgresBackedServiceTestSupport; import net.firedevops.firemud.worldmanagement.client.EntityManagementClient; @@ -26,6 +28,7 @@ import net.firedevops.firemud.worldmanagement.service.WorldLifecycleCommandService; import net.firedevops.firemud.worldmanagement.service.impl.InitialAdmissionBindHoldServiceImpl; import org.jooq.DSLContext; +import org.jooq.Record; import org.junit.jupiter.api.Test; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.boot.test.context.SpringBootTest; @@ -81,6 +84,7 @@ void holdAcquireWinsConcurrentTerminationAndExactRetrySurvivesServiceRecreation( InitialAdmissionBindHoldRequest request = request(tenantId, gameInstanceId); CountDownLatch lifecycleLocked = new CountDownLatch(1); CountDownLatch allowAcquireCommit = new CountDownLatch(1); + AtomicInteger acquisitionBackendPid = new AtomicInteger(); TransactionTemplate transactionTemplate = new TransactionTemplate(transactionManager); try (ExecutorService executor = Executors.newFixedThreadPool(2)) { @@ -92,11 +96,21 @@ void holdAcquireWinsConcurrentTerminationAndExactRetrySurvivesServiceRecreation( worldInstanceRepository .findByTenantIdAndGameInstanceIdForUpdate(tenantId, gameInstanceId) .orElseThrow(); + Record backendIdentity = + Objects.requireNonNull( + dsl.fetchOne("SELECT pg_backend_pid()"), + "PostgreSQL backend PID query returned no row"); + acquisitionBackendPid.set( + Objects.requireNonNull( + backendIdentity.get(0, Integer.class), + "PostgreSQL backend PID query returned a null PID")); lifecycleLocked.countDown(); await(allowAcquireCommit); return holdService.acquire(request); })); assertThat(lifecycleLocked.await(5, TimeUnit.SECONDS)).isTrue(); + int exactAcquisitionBackendPid = acquisitionBackendPid.get(); + assertThat(exactAcquisitionBackendPid).isPositive(); CountDownLatch terminationStarted = new CountDownLatch(1); Future terminationFuture = @@ -112,12 +126,21 @@ void holdAcquireWinsConcurrentTerminationAndExactRetrySurvivesServiceRecreation( } }); assertThat(terminationStarted.await(5, TimeUnit.SECONDS)).isTrue(); + int terminationBackendPid = awaitBackendBlockedBy(exactAcquisitionBackendPid); + assertThat(isBackendBlockedBy(terminationBackendPid, exactAcquisitionBackendPid)).isTrue(); allowAcquireCommit.countDown(); var acquired = acquireFuture.get(10, TimeUnit.SECONDS); String terminationResult = terminationFuture.get(10, TimeUnit.SECONDS); assertThat(acquired).isNotNull(); assertThat(terminationResult).startsWith("INITIAL_ADMISSION_BIND_HOLD_ACTIVE:"); + assertThat(holdRepository.hasNonterminalForRealm(tenantId, request.realmUuid())).isTrue(); + assertThat(holdRepository.hasNonterminalForRealm(tenantId + 1L, request.realmUuid())) + .isFalse(); + assertThat( + holdRepository.hasNonterminalForRealm( + tenantId, "00000000-0000-0000-0000-000000000099")) + .isFalse(); InitialAdmissionBindHoldServiceImpl restartedService = new InitialAdmissionBindHoldServiceImpl(holdRepository, worldInstanceRepository); var retry = transactionTemplate.execute(status -> restartedService.acquire(request)); @@ -223,6 +246,36 @@ private long uniqueGameInstanceId() { return Math.abs(System.nanoTime()) + 10_000L; } + private int awaitBackendBlockedBy(int blockerPid) throws InterruptedException { + long deadline = System.nanoTime() + TimeUnit.SECONDS.toNanos(5); + do { + Record blockedBackend = + dsl.fetchOne( + "SELECT pid FROM pg_stat_activity WHERE datname = current_database() " + + "AND pid <> ? AND wait_event_type = 'Lock' " + + "AND query ILIKE '%world_instance%' " + + "AND ? = ANY(pg_blocking_pids(pid)) ORDER BY pid LIMIT 1", + blockerPid, blockerPid); + Integer blockedPid = blockedBackend == null ? null : blockedBackend.get(0, Integer.class); + if (blockedPid != null && isBackendBlockedBy(blockedPid, blockerPid)) { + return blockedPid; + } + Thread.sleep(100L); + } while (System.nanoTime() < deadline); + throw new AssertionError( + "No PostgreSQL backend was observed waiting on acquisition backend " + blockerPid); + } + + private boolean isBackendBlockedBy(int blockedPid, int blockerPid) { + Record backendState = + dsl.fetchOne( + "SELECT wait_event_type = 'Lock' AND ? = ANY(pg_blocking_pids(pid)) " + + "FROM pg_stat_activity WHERE pid = ?", + blockerPid, + blockedPid); + return backendState != null && Boolean.TRUE.equals(backendState.get(0, Boolean.class)); + } + private void deleteFixture(long tenantId, long gameInstanceId) { dsl.execute( "DELETE FROM initial_admission_bind_hold WHERE tenant_id = ? AND game_instance_id = ?", diff --git a/services/world-management-service/src/test/java/unit/net/firedevops/firemud/worldmanagement/repository/InitialAdmissionBindHoldRepositoryTest.java b/services/world-management-service/src/test/java/unit/net/firedevops/firemud/worldmanagement/repository/InitialAdmissionBindHoldRepositoryTest.java index 2f485d63dc..11f2a47a53 100644 --- a/services/world-management-service/src/test/java/unit/net/firedevops/firemud/worldmanagement/repository/InitialAdmissionBindHoldRepositoryTest.java +++ b/services/world-management-service/src/test/java/unit/net/firedevops/firemud/worldmanagement/repository/InitialAdmissionBindHoldRepositoryTest.java @@ -1,7 +1,9 @@ package net.firedevops.firemud.worldmanagement.repository; +import static org.junit.jupiter.api.Assertions.assertArrayEquals; import static org.junit.jupiter.api.Assertions.assertEquals; import static org.junit.jupiter.api.Assertions.assertFalse; +import static org.junit.jupiter.api.Assertions.assertThrows; import static org.junit.jupiter.api.Assertions.assertTrue; import static org.mockito.ArgumentMatchers.any; import static org.mockito.ArgumentMatchers.anyString; @@ -12,8 +14,10 @@ import java.time.Instant; import java.time.LocalDateTime; import java.time.ZoneOffset; +import java.util.UUID; import net.firedevops.firemud.worldmanagement.entity.InitialAdmissionBindHold; import org.jooq.DSLContext; +import org.jooq.Record; import org.junit.jupiter.api.Test; import org.mockito.ArgumentCaptor; import org.mockito.Mockito; @@ -53,6 +57,43 @@ void reconciliationAttemptUpdatesTimestampAndRowVersionEvenForSameDiagnostic() { assertEquals(LocalDateTime.ofInstant(attemptedAt, ZoneOffset.UTC), bindings.getValue()[1]); } + @Test + void realmHoldPredicateBindsOnlyTenantAndRealmAndReadsTheBooleanColumn() { + DSLContext dsl = Mockito.mock(DSLContext.class); + Record result = Mockito.mock(Record.class); + when(dsl.fetchOne(anyString(), any(Object[].class))).thenReturn(result); + when(result.get(0, Boolean.class)).thenReturn(true); + InitialAdmissionBindHoldRepository repository = new InitialAdmissionBindHoldRepository(dsl); + + boolean hasHold = + repository.hasNonterminalForRealm(42L, "00000000-0000-0000-0000-000000000001"); + + assertTrue(hasHold); + ArgumentCaptor query = ArgumentCaptor.forClass(String.class); + ArgumentCaptor bindings = ArgumentCaptor.forClass(Object[].class); + verify(dsl).fetchOne(query.capture(), bindings.capture()); + assertTrue(query.getValue().contains("tenant_id = ? AND realm_uuid = ?::uuid")); + assertArrayEquals( + new Object[] {42L, UUID.fromString("00000000-0000-0000-0000-000000000001")}, + bindings.getValue()); + verify(result).get(0, Boolean.class); + verifyNoMoreInteractions(dsl); + } + + @Test + void realmHoldPredicateFailsClearlyWhenTheQueryReturnsNoRow() { + DSLContext dsl = Mockito.mock(DSLContext.class); + when(dsl.fetchOne(anyString(), any(Object[].class))).thenReturn(null); + InitialAdmissionBindHoldRepository repository = new InitialAdmissionBindHoldRepository(dsl); + + IllegalStateException exception = + assertThrows( + IllegalStateException.class, + () -> repository.hasNonterminalForRealm(42L, "00000000-0000-0000-0000-000000000001")); + + assertTrue(exception.getMessage().startsWith("INITIAL_ADMISSION_BIND_HOLD_LOOKUP_FAILED:")); + } + private InitialAdmissionBindHold hold() { Instant now = Instant.parse("2026-10-02T00:00:00Z"); return new InitialAdmissionBindHold( diff --git a/services/world-management-service/src/test/java/unit/net/firedevops/firemud/worldmanagement/service/impl/InitialAdmissionBindHoldReconcilerTest.java b/services/world-management-service/src/test/java/unit/net/firedevops/firemud/worldmanagement/service/impl/InitialAdmissionBindHoldReconcilerTest.java index c2acf3e573..9472f91fb1 100644 --- a/services/world-management-service/src/test/java/unit/net/firedevops/firemud/worldmanagement/service/impl/InitialAdmissionBindHoldReconcilerTest.java +++ b/services/world-management-service/src/test/java/unit/net/firedevops/firemud/worldmanagement/service/impl/InitialAdmissionBindHoldReconcilerTest.java @@ -1,13 +1,19 @@ package net.firedevops.firemud.worldmanagement.service.impl; +import static org.assertj.core.api.Assertions.assertThat; import static org.junit.jupiter.api.Assertions.assertNotNull; import static org.mockito.Mockito.doThrow; import static org.mockito.Mockito.verify; import static org.mockito.Mockito.when; +import io.micrometer.core.instrument.Tag; +import io.micrometer.core.instrument.simple.SimpleMeterRegistry; import java.time.Instant; import java.util.List; import net.firedevops.firemud.worldmanagement.client.GameSessionInitialAdmissionBindProofClient; +import net.firedevops.firemud.worldmanagement.dto.InitialAdmissionBindHoldDto; +import net.firedevops.firemud.worldmanagement.dto.InitialAdmissionBindOwnerProof; +import net.firedevops.firemud.worldmanagement.dto.InitialAdmissionBindOwnerProof.Outcome; import net.firedevops.firemud.worldmanagement.entity.InitialAdmissionBindHold; import net.firedevops.firemud.worldmanagement.repository.InitialAdmissionBindHoldRepository; import net.firedevops.firemud.worldmanagement.service.InitialAdmissionBindHoldService; @@ -17,6 +23,9 @@ import org.springframework.context.annotation.AnnotationConfigApplicationContext; class InitialAdmissionBindHoldReconcilerTest { + private static final String OVERDUE_OBSERVATIONS_METRIC = + "world_initial_admission_bind_overdue_observations_total"; + @Test void springContextSelectsAutowiredProductionConstructor() { try (AnnotationConfigApplicationContext context = new AnnotationConfigApplicationContext()) { @@ -29,6 +38,7 @@ void springContextSelectsAutowiredProductionConstructor() { context.registerBean( GameSessionInitialAdmissionBindProofClient.class, () -> Mockito.mock(GameSessionInitialAdmissionBindProofClient.class)); + context.registerBean(SimpleMeterRegistry.class); context.registerBean(InitialAdmissionBindHoldReconciler.class); context.refresh(); @@ -52,14 +62,181 @@ void failedReconciliationRequiredCasDoesNotStopTheRemainingBatch() { .requireReconciliation(first.holdId(), "GS_OWNER_READ_UNAVAILABLE"); InitialAdmissionBindHoldReconciler reconciler = - new InitialAdmissionBindHoldReconciler(repository, service, proofClientProvider); + new InitialAdmissionBindHoldReconciler( + repository, service, proofClientProvider, new SimpleMeterRegistry()); reconciler.reconcilePendingHolds(); verify(service).requireReconciliation(first.holdId(), "GS_OWNER_READ_UNAVAILABLE"); verify(service).requireReconciliation(second.holdId(), "GS_OWNER_READ_UNAVAILABLE"); } + @Test + void overdueObservationCountsBoundedOwnerPendingCodeWithoutIdentityLabels() { + InitialAdmissionBindHold hold = hold(5L, Instant.parse("2026-10-02T00:00:00Z"), null); + InitialAdmissionBindHoldRepository repository = repositoryWith(hold); + InitialAdmissionBindHoldService service = Mockito.mock(InitialAdmissionBindHoldService.class); + GameSessionInitialAdmissionBindProofClient proofClient = + Mockito.mock(GameSessionInitialAdmissionBindProofClient.class); + ObjectProvider proofClientProvider = + providerWith(proofClient); + InitialAdmissionBindOwnerProof ownerProof = ownerProof(Outcome.PENDING); + when(proofClient.readOwnerProof(hold)).thenReturn(ownerProof); + when(service.reconcileOwnerProof(hold.holdId(), ownerProof)) + .thenReturn(dto(hold, "RECONCILIATION_REQUIRED")); + SimpleMeterRegistry meterRegistry = new SimpleMeterRegistry(); + + reconciler(repository, service, proofClientProvider, meterRegistry).reconcilePendingHolds(); + + assertThat(counter(meterRegistry, "GS_OWNER_PENDING")).isEqualTo(1.0); + assertThat(meterRegistry.getMeters()) + .allSatisfy( + meter -> + assertThat(meter.getId().getTags()) + .containsExactly(Tag.of("error_code", "GS_OWNER_PENDING"))); + verify(service).reconcileOwnerProof(hold.holdId(), ownerProof); + } + + @Test + void holdBeforeDiagnosticExpiryDoesNotEmitAnOverdueObservation() { + InitialAdmissionBindHold hold = hold(6L, Instant.parse("2026-10-02T00:10:00Z"), null); + InitialAdmissionBindHoldRepository repository = repositoryWith(hold); + InitialAdmissionBindHoldService service = Mockito.mock(InitialAdmissionBindHoldService.class); + GameSessionInitialAdmissionBindProofClient proofClient = + Mockito.mock(GameSessionInitialAdmissionBindProofClient.class); + ObjectProvider proofClientProvider = + providerWith(proofClient); + InitialAdmissionBindOwnerProof ownerProof = ownerProof(Outcome.PENDING); + when(proofClient.readOwnerProof(hold)).thenReturn(ownerProof); + when(service.reconcileOwnerProof(hold.holdId(), ownerProof)) + .thenReturn(dto(hold, "RECONCILIATION_REQUIRED")); + SimpleMeterRegistry meterRegistry = new SimpleMeterRegistry(); + + reconciler(repository, service, proofClientProvider, meterRegistry).reconcilePendingHolds(); + + assertThat(meterRegistry.find(OVERDUE_OBSERVATIONS_METRIC).counter()).isNull(); + } + + @Test + void overdueObservationIsEmittedWhenOwnerProofClientIsUnavailable() { + InitialAdmissionBindHold hold = hold(7L, Instant.parse("2026-10-02T00:00:00Z"), null); + InitialAdmissionBindHoldRepository repository = repositoryWith(hold); + InitialAdmissionBindHoldService service = Mockito.mock(InitialAdmissionBindHoldService.class); + ObjectProvider proofClientProvider = + providerWith(null); + SimpleMeterRegistry meterRegistry = new SimpleMeterRegistry(); + + reconciler(repository, service, proofClientProvider, meterRegistry).reconcilePendingHolds(); + + assertThat(counter(meterRegistry, "GS_OWNER_READ_UNAVAILABLE")).isEqualTo(1.0); + verify(service).requireReconciliation(hold.holdId(), "GS_OWNER_READ_UNAVAILABLE"); + } + + @Test + void overdueObservationRecordsOwnerProofThatFinalizesTheHold() { + InitialAdmissionBindHold hold = hold(8L, Instant.parse("2026-10-02T00:00:00Z"), null); + InitialAdmissionBindHoldRepository repository = repositoryWith(hold); + InitialAdmissionBindHoldService service = Mockito.mock(InitialAdmissionBindHoldService.class); + GameSessionInitialAdmissionBindProofClient proofClient = + Mockito.mock(GameSessionInitialAdmissionBindProofClient.class); + ObjectProvider proofClientProvider = + providerWith(proofClient); + InitialAdmissionBindOwnerProof ownerProof = ownerProof(Outcome.COMMITTED); + when(proofClient.readOwnerProof(hold)).thenReturn(ownerProof); + when(service.reconcileOwnerProof(hold.holdId(), ownerProof)).thenReturn(dto(hold, "COMMITTED")); + SimpleMeterRegistry meterRegistry = new SimpleMeterRegistry(); + + reconciler(repository, service, proofClientProvider, meterRegistry).reconcilePendingHolds(); + + assertThat(counter(meterRegistry, "none")).isEqualTo(1.0); + verify(service).reconcileOwnerProof(hold.holdId(), ownerProof); + } + + private static InitialAdmissionBindHoldReconciler reconciler( + InitialAdmissionBindHoldRepository repository, + InitialAdmissionBindHoldService service, + ObjectProvider proofClientProvider, + SimpleMeterRegistry meterRegistry) { + return new InitialAdmissionBindHoldReconciler( + repository, + service, + proofClientProvider, + java.time.Clock.fixed(Instant.parse("2026-10-02T00:05:00Z"), java.time.ZoneOffset.UTC), + meterRegistry); + } + + private static InitialAdmissionBindHoldRepository repositoryWith(InitialAdmissionBindHold hold) { + InitialAdmissionBindHoldRepository repository = + Mockito.mock(InitialAdmissionBindHoldRepository.class); + when(repository.findNonterminal(32)).thenReturn(List.of(hold)); + return repository; + } + + private static InitialAdmissionBindOwnerProof ownerProof(Outcome outcome) { + return new InitialAdmissionBindOwnerProof( + outcome, + "00000000-0000-0000-0000-000000000001", + "00000000-0000-0000-0000-000000000002", + 42L, + "00000000-0000-0000-0000-000000000003", + "00000000-0000-0000-0000-000000000004", + "SHARED", + 101L, + 11L, + 7L, + "initial-admission-1", + "a".repeat(64), + true, + 1L, + "owner-proof-1", + null, + 0L, + null, + false); + } + + private static InitialAdmissionBindHoldDto dto(InitialAdmissionBindHold hold, String status) { + return new InitialAdmissionBindHoldDto( + hold.holdId(), + hold.holdFence(), + hold.tenantId(), + hold.realmUuid(), + hold.playableStateNamespaceUuid(), + hold.playableStateScope(), + hold.gameInstanceId(), + hold.versionId(), + hold.activeLifecycleEpoch(), + hold.initialAdmissionRequestId(), + hold.requestDigest(), + hold.expectedNoPriorPointer(), + hold.expectedCatalogRevision(), + status, + hold.diagnosticExpiresAt()); + } + + private static double counter(SimpleMeterRegistry meterRegistry, String errorCode) { + return meterRegistry + .get(OVERDUE_OBSERVATIONS_METRIC) + .tag("error_code", errorCode) + .counter() + .count(); + } + + @SuppressWarnings("unchecked") + private static ObjectProvider providerWith( + GameSessionInitialAdmissionBindProofClient client) { + ObjectProvider provider = + (ObjectProvider) + Mockito.mock(ObjectProvider.class); + when(provider.getIfAvailable()).thenReturn(client); + return provider; + } + private static InitialAdmissionBindHold hold(long suffix) { + return hold(suffix, Instant.now().plusSeconds(300), null); + } + + private static InitialAdmissionBindHold hold( + long suffix, Instant diagnosticExpiresAt, String reconciliationError) { String uuidSuffix = String.format("%012d", suffix); Instant now = Instant.now(); return new InitialAdmissionBindHold( @@ -77,12 +254,12 @@ private static InitialAdmissionBindHold hold(long suffix) { true, 1L, "PENDING", - now.plusSeconds(300), - null, + diagnosticExpiresAt, null, null, null, null, + reconciliationError, now, now, null, From cf83e1332ec1ca078d0d9e132758bd3ada2ce2fb Mon Sep 17 00:00:00 2001 From: Ben Hook <5009589+benhook1013@users.noreply.github.com> Date: Sat, 3 Oct 2026 03:47:23 +1300 Subject: [PATCH 10/20] Recognize archived addressed-thread metadata in Hosted completion proof --- dev-tools/pr_review/hosted.py | 260 +++++++++++++++++- dev-tools/pr_review/runtime.py | 13 +- .../test_pr_review_evidence_hosted.py | 199 ++++++++++++++ 3 files changed, 469 insertions(+), 3 deletions(-) diff --git a/dev-tools/pr_review/hosted.py b/dev-tools/pr_review/hosted.py index 7dddb638ed..1ec845af8c 100644 --- a/dev-tools/pr_review/hosted.py +++ b/dev-tools/pr_review/hosted.py @@ -10,7 +10,7 @@ import re import stat import tempfile -from collections.abc import Callable +from collections.abc import Callable, Mapping from dataclasses import dataclass from datetime import datetime, timedelta, timezone from pathlib import Path @@ -1532,6 +1532,236 @@ def _is_finished_action_response(body: str, *, allow_action_wrapper: bool) -> bo ) +_ADDRESSED_COMMIT_ANNOTATION = re.compile( + r"(?:\r?\n){2}✅ Addressed in commits ([0-9a-f]{7,40}) to ([0-9a-f]{7,40})\Z", + re.IGNORECASE, +) + + +def _archived_completed_thread_bodies( + repo: str, + pr_number: int, + head: str, + record: Mapping[str, Any] | None, + current_record_path: str | Path | None, +) -> dict[int, tuple[str, str]]: + """Read immutable prior Hosted thread bodies for exact trigger attribution.""" + + if not isinstance(record, Mapping): + return {} + current_attempt_id = record.get("sqlite_attempt_id") + trigger = record.get("trigger") + trigger_id = trigger.get("id") if isinstance(trigger, Mapping) else None + trigger_at = parse_timestamp(trigger.get("created_at")) if isinstance(trigger, Mapping) else None + if ( + not isinstance(current_attempt_id, str) + or not current_attempt_id + or type(trigger_id) is not int + or trigger_id <= 0 + or trigger_at is None + or not isinstance(record.get("head_sha"), str) + or record["head_sha"].casefold() != head.casefold() + ): + return {} + + selected_record = Path(current_record_path) if current_record_path is not None else default_trigger_record_path( + repo, pr_number + ) + if selected_record.is_symlink(): + return {} + common = _trigger_record_common_for_path(selected_record, repo, pr_number) + if common is None: + return {} + selected_state = state_path(common) + if selected_state.is_symlink() or not selected_state.is_dir(): + return {} + database = sqlite_state_path(selected_state) + try: + database_stat = database.stat(follow_symlinks=False) + except FileNotFoundError: + return {} + if database.is_symlink() or not stat.S_ISREG(database_stat.st_mode): + return {} + + try: + records = SqliteReviewRecords(database) + current_attempt = records.attempt(current_attempt_id) + attempt_history = records.attempt_history(pr_number) + current_history = [item for item in attempt_history if item.get("attempt_id") == current_attempt_id] + current_head = current_attempt.get("candidate_sha") + if ( + current_attempt.get("source_pr") != pr_number + or current_attempt.get("channel") != "hosted" + or not isinstance(current_head, str) + or current_head.casefold() != head.casefold() + or len(current_history) != 1 + or current_history[0].get("trigger_id") != str(trigger_id) + ): + return {} + + candidates: dict[int, list[tuple[str, str]]] = {} + for attempt in attempt_history: + candidate_head = attempt.get("candidate_sha") + started_at = parse_timestamp(attempt.get("started_at")) + finished_at = parse_timestamp(attempt.get("finished_at")) + if ( + attempt.get("channel") != "hosted" + or attempt.get("state") != "completed" + or not isinstance(candidate_head, str) + or not EXACT_SHA.fullmatch(candidate_head) + or started_at is None + or finished_at is None + or finished_at >= trigger_at + ): + continue + attempt_id = attempt.get("attempt_id") + provider_review_id = attempt.get("provider_review_id") + archived_trigger_id = attempt.get("trigger_id") + if ( + not isinstance(attempt_id, str) + or not attempt_id + or not isinstance(provider_review_id, str) + or not provider_review_id.isdecimal() + or not isinstance(archived_trigger_id, str) + or not archived_trigger_id.isdecimal() + ): + continue + artifacts = records.attempt_artifacts(attempt_id) + try: + metadata = json.loads(artifacts.get("metadata", "")) + archived = json.loads(artifacts.get("hosted_comments", "")) + reviews = json.loads(artifacts.get("hosted_review", "")) + except (TypeError, ValueError, json.JSONDecodeError): + continue + observed_at = parse_timestamp(metadata.get("observed_at")) if isinstance(metadata, dict) else None + metadata_repository = metadata.get("repository") if isinstance(metadata, dict) else None + metadata_head = metadata.get("head_sha") if isinstance(metadata, dict) else None + if ( + not isinstance(metadata, dict) + or metadata.get("state") != "completed" + or metadata.get("terminal") is not True + or metadata.get("attributable") is not True + or not isinstance(metadata_repository, str) + or metadata_repository.casefold() != repo.casefold() + or metadata.get("pull_request") != pr_number + or not isinstance(metadata_head, str) + or metadata_head.casefold() != candidate_head.casefold() + or type(metadata.get("trigger_id")) is not int + or str(metadata["trigger_id"]) != archived_trigger_id + or type(metadata.get("response_id")) is not int + or str(metadata["response_id"]) != provider_review_id + or observed_at is None + or observed_at != finished_at + or not isinstance(archived, dict) + or not isinstance(archived.get("comments"), list) + or not isinstance(archived.get("review_threads"), list) + or not isinstance(reviews, list) + ): + continue + + matching_reviews = [ + item + for item in reviews + if isinstance(item, dict) + and immutable_database_id(item) == metadata["response_id"] + and is_coderabbit_login((item.get("author") or {}).get("login")) + and item.get("state") != "DISMISSED" + and isinstance((item.get("commit") or {}).get("oid"), str) + and (item.get("commit") or {}).get("oid").casefold() == candidate_head.casefold() + ] + matching_triggers = [ + item + for item in archived["comments"] + if isinstance(item, dict) and immutable_database_id(item) == int(archived_trigger_id) + ] + if ( + len(matching_reviews) != 1 + or len(matching_triggers) != 1 + or is_coderabbit_login((matching_triggers[0].get("author") or {}).get("login")) + or normalize_command(matching_triggers[0].get("body") or "") != FULL_COMMAND + ): + continue + archived_trigger_at = parse_timestamp(matching_triggers[0].get("createdAt")) + review_submitted_at = parse_timestamp(matching_reviews[0].get("submittedAt")) + if ( + archived_trigger_at is None + or archived_trigger_at > finished_at + or review_submitted_at is None + or review_submitted_at < archived_trigger_at + or review_submitted_at > finished_at + ): + continue + + for thread in archived["review_threads"]: + comments = thread.get("comments") if isinstance(thread, dict) else None + nodes = comments.get("nodes") if isinstance(comments, dict) else None + if not isinstance(nodes, list): + continue + for item in nodes: + if not isinstance(item, dict) or not is_coderabbit_login((item.get("author") or {}).get("login")): + continue + comment_id = immutable_database_id(item) + created_at = item.get("createdAt") + created = parse_timestamp(created_at) + body = item.get("body") + if ( + comment_id is None + or not isinstance(created_at, str) + or created is None + or created < archived_trigger_at + or created > finished_at + or not isinstance(body, str) + ): + continue + candidates.setdefault(comment_id, []).append((created_at, body)) + + result: dict[int, tuple[str, str]] = {} + for comment_id, baselines in candidates.items(): + if len(baselines) == 1: + result[comment_id] = baselines[0] + except Exception: # noqa: BLE001 - unavailable or incompatible archive must remain fail closed + return {} + return result + + +def _addressed_thread_update_matches_archive( + item: dict[str, Any], + head: str, + after: datetime, + before: datetime | None, + archived_bodies: Mapping[int, tuple[str, str]], +) -> bool: + """Accept only the exact known addressed footer appended to an archived finding.""" + + comment_id = immutable_database_id(item) + if comment_id is None: + return False + archived = archived_bodies.get(comment_id) + body = item.get("body") + created_at = item.get("createdAt") + updated = parse_timestamp(item.get("updatedAt")) + created = parse_timestamp(created_at) + if ( + archived is None + or not isinstance(body, str) + or not isinstance(created_at, str) + or created_at != archived[0] + or not isinstance(archived[1], str) + or created is None + or created >= after + or updated is None + or updated <= after + or (before is not None and updated >= before) + ): + return False + annotation = _ADDRESSED_COMMIT_ANNOTATION.search(body) + return ( + annotation is not None + and annotation.group(2).casefold() == head[: len(annotation.group(2))].casefold() + and body[: annotation.start()] == archived[1] + ) + + def _summary_has_explicit_incompleteness(body: str) -> bool: text = _unquoted(body) not_reviewed_counts = [int(match.group(1)) for match in FILE_NOT_REVIEWED_COUNT.finditer(text)] @@ -1815,6 +2045,10 @@ def finished_reply_without_findings( after: datetime, response_id: int | None, before: datetime | None = None, + record: Mapping[str, Any] | None = None, + current_record_path: str | Path | None = None, + repo: str | None = None, + pr_number: int | None = None, ) -> bool: """Accept CodeRabbit's terminal full-review reply when its complete window is empty. @@ -1893,6 +2127,7 @@ def in_window(value: Any) -> bool | None: submitted_in_window = in_window(item.get("submittedAt")) if submitted_in_window is None or submitted_in_window: return False + archived_bodies: dict[int, tuple[str, str]] | None = None for thread in connections["reviewThreads"]: comments = thread.get("comments") nodes = comments.get("nodes") if isinstance(comments, dict) else None @@ -1903,7 +2138,24 @@ def in_window(value: Any) -> bool | None: continue created_in_window = in_window(item.get("createdAt")) updated_in_window = in_window(item.get("updatedAt")) - if created_in_window is None or updated_in_window is None or created_in_window or updated_in_window: + if created_in_window is None or updated_in_window is None: + return False + if created_in_window or updated_in_window: + if not created_in_window and updated_in_window: + if archived_bodies is None: + archived_bodies = ( + _archived_completed_thread_bodies( + repo, + pr_number, + head, + record, + current_record_path, + ) + if isinstance(repo, str) and type(pr_number) is int and pr_number > 0 + else {} + ) + if _addressed_thread_update_matches_archive(item, head, after, before, archived_bodies): + continue return False return True @@ -2083,6 +2335,10 @@ def trigger_state( trigger_dt, immutable_database_id(item), next_dt, + record, + current_record_path, + repo, + pr_number, ): state = ( "ambiguous_retired_predecessor" diff --git a/dev-tools/pr_review/runtime.py b/dev-tools/pr_review/runtime.py index 74d3cc0c2f..731730b2bf 100644 --- a/dev-tools/pr_review/runtime.py +++ b/dev-tools/pr_review/runtime.py @@ -1111,6 +1111,8 @@ def _hosted_zero_reply_proof( checkpoint: evidence.Checkpoint, response_id: int | None, response_duration_seconds: int | None, + repo: str, + pr_number: int, captured_head: str, record: dict[str, Any], payload: dict[str, Any], @@ -1182,7 +1184,14 @@ def _hosted_zero_reply_proof( next_trigger, ) finished_only = hosted.finished_reply_without_findings( - payload, captured_head, trigger_at, response_id, next_trigger + payload, + captured_head, + trigger_at, + response_id, + next_trigger, + record, + repo=repo, + pr_number=pr_number, ) if legacy_summary is None and provider_summary is None and not finished_only: return None @@ -1229,6 +1238,8 @@ def _hosted_trigger_for_checkpoint( checkpoint, state.response_id, state.duration_seconds, + self.repo, + pr, captured_head, record, payload, diff --git a/dev-tools/validation/test_pr_review_evidence_hosted.py b/dev-tools/validation/test_pr_review_evidence_hosted.py index 36f5099858..7b7c91d573 100644 --- a/dev-tools/validation/test_pr_review_evidence_hosted.py +++ b/dev-tools/validation/test_pr_review_evidence_hosted.py @@ -80,6 +80,145 @@ def trigger_record(head: str = HEAD): } +def archived_addressed_reply_fixture(common: Path, *, include_baseline: bool = True): + trigger_at = "2026-09-23T00:02:00Z" + old_trigger_at = "2026-09-23T00:00:50Z" + old_started_at = "2026-09-23T00:00:40Z" + old_finished_at = "2026-09-23T00:01:15Z" + old_body = "An archived CodeRabbit finding.\n\n" + addressed_body = f"{old_body}\n\n✅ Addressed in commits {'c' * 7} to {HEAD[:7]}" + inline = { + "databaseId": 30, + "author": {"login": "coderabbitai[bot]"}, + "body": addressed_body, + "createdAt": "2026-09-23T00:01:10Z", + "updatedAt": "2026-09-23T00:02:15Z", + } + old_review = { + "databaseId": 20, + "author": {"login": "coderabbitai[bot]"}, + "body": "\nReviewing the archived candidate.", + "state": "COMMENTED", + "submittedAt": old_finished_at, + "commit": {"oid": BASE}, + } + old_comments = { + "comments": [ + comment(9, "owner", hosted.FULL_COMMAND, old_trigger_at), + ], + "review_threads": ( + [ + { + "comments": { + "nodes": [ + { + **inline, + "body": old_body, + "createdAt": inline["createdAt"], + "updatedAt": old_finished_at, + } + ] + } + } + ] + if include_baseline + else [] + ), + } + old_metadata = { + "state": "completed", + "terminal": True, + "attributable": True, + "repository": REPO, + "pull_request": PR, + "head_sha": BASE, + "trigger_id": 9, + "response_id": 20, + "observed_at": old_finished_at, + } + + state_dir = common / "firemud" / "pr-review-stack.json" + state_dir.mkdir(parents=True) + database = common / "firemud" / "pr-review-stack.sqlite3" + SqliteStateStore(database).update(lambda state: state) + records = SqliteReviewRecords(database) + records.bootstrap() + records.start_attempt( + attempt_id="old-hosted-attempt", + source_pr=PR, + channel="hosted", + candidate_sha=BASE, + started_at=old_started_at, + ) + records.finish_attempt( + "old-hosted-attempt", + state="completed", + finished_at=old_finished_at, + trigger_id="9", + provider_review_id="20", + artifacts={ + "hosted_review": json.dumps([old_review]), + "hosted_comments": json.dumps(old_comments), + "metadata": json.dumps(old_metadata), + }, + ) + records.start_attempt( + attempt_id="current-hosted-attempt", + source_pr=PR, + channel="hosted", + candidate_sha=HEAD, + started_at="2026-09-23T00:01:50Z", + ) + records.finish_attempt( + "current-hosted-attempt", + state="ambiguous", + finished_at="2026-09-23T00:02:08Z", + trigger_id="10", + provider_review_id="11", + artifacts={ + "hosted_review": "[]", + "hosted_comments": json.dumps({"comments": []}), + "metadata": json.dumps({"state": "ambiguous"}), + }, + ) + + trigger = comment(10, "owner", hosted.FULL_COMMAND, trigger_at) + summary = comment( + 12, + "coderabbitai[bot]", + "No actionable comments were generated in the recent review.\n" + f"Reviewing files that changed from the base of the PR and between {BASE} and {HEAD}.", + "2026-09-23T00:01:40Z", + ) + summary["updatedAt"] = "2026-09-23T00:02:30Z" + response = comment( + 11, + "coderabbitai[bot]", + "\n" + f"\n" + "

\n✅ Action performed\n" + "Full review finished.\n
", + "2026-09-23T00:02:08Z", + ) + response["updatedAt"] = "2026-09-23T00:02:20Z" + payload = review_payload( + [trigger, summary, response], + threads=[{"comments": {"nodes": [inline]}}], + ) + record = trigger_record() + record["sqlite_attempt_id"] = "current-hosted-attempt" + record["trigger"].update( + { + "id": 10, + "created_at": trigger_at, + "url": trigger["url"], + } + ) + record_path = hosted.default_trigger_record_path(REPO, PR, common) + record_path.parent.mkdir(parents=True, exist_ok=True) + return payload, record, record_path + + class GithubAndEvidenceTests(unittest.TestCase): def test_cli_result_exposes_human_duration_without_changing_seconds_or_marker(self): result = ReviewResult( @@ -1749,6 +1888,66 @@ def test_finished_reply_with_empty_complete_history_is_clean_completion(self): with self.assertRaisesRegex(ValueError, "invalid full-review identity"): hosted.trigger_state(REPO, PR, review_payload([trigger, finished]), bool_record) + def test_finished_reply_accepts_only_exact_archived_addressed_thread_updates(self): + with tempfile.TemporaryDirectory() as directory: + payload, record, record_path = archived_addressed_reply_fixture(Path(directory)) + + state = hosted.trigger_state(REPO, PR, payload, record, record_path) + + self.assertEqual(state.state, "completed") + self.assertTrue(state.attributed) + self.assertEqual(state.response_id, 11) + + def test_finished_reply_keeps_unproven_or_changed_thread_output_ambiguous(self): + cases = ( + ("unknown baseline", False, None), + ("modified archived body", True, "modified_body"), + ("addressed range ends on another head", True, "mismatched_range"), + ("new inline comment", True, "new_comment"), + ("positive finding count", True, "positive_count"), + ("incomplete coverage", True, "incomplete_coverage"), + ("mismatched summary head", True, "mismatched_summary_head"), + ) + for label, include_baseline, mutation in cases: + with self.subTest(case=label), tempfile.TemporaryDirectory() as directory: + payload, record, record_path = archived_addressed_reply_fixture( + Path(directory), include_baseline=include_baseline + ) + thread_nodes = payload["data"]["repository"]["pullRequest"]["reviewThreads"]["nodes"][0][ + "comments" + ]["nodes"] + if mutation == "modified_body": + thread_nodes[0]["body"] = thread_nodes[0]["body"].replace( + "An archived CodeRabbit finding.", "A changed CodeRabbit finding." + ) + elif mutation == "mismatched_range": + thread_nodes[0]["body"] = thread_nodes[0]["body"].replace( + f"to {HEAD[:7]}", f"to {BASE[:7]}" + ) + elif mutation == "new_comment": + thread_nodes.append( + { + "databaseId": 31, + "author": {"login": "coderabbitai[bot]"}, + "body": "A new inline finding.", + "createdAt": "2026-09-23T00:02:16Z", + "updatedAt": "2026-09-23T00:02:16Z", + } + ) + elif mutation in {"positive_count", "incomplete_coverage", "mismatched_summary_head"}: + issue_comments = payload["data"]["repository"]["pullRequest"]["comments"]["nodes"] + summary = next(item for item in issue_comments if item["databaseId"] == 12) + if mutation == "positive_count": + summary["body"] += "\n**Actionable comments posted: 1**" + elif mutation == "incomplete_coverage": + summary["body"] += "\nFiles not reviewed: 3." + else: + summary["body"] = summary["body"].replace(HEAD, BASE) + + state = hosted.trigger_state(REPO, PR, payload, record, record_path) + + self.assertEqual(state.state, "ambiguous") + def test_active_acknowledgement_does_not_hide_clean_finished_result(self): trigger = comment(10, "owner", hosted.FULL_COMMAND, "2026-09-23T00:01:00Z") acknowledgement = comment(11, "coderabbitai", "Full review triggered", "2026-09-23T00:01:08Z") From 71631a7e62425f88a86381c71097879544e352b7 Mon Sep 17 00:00:00 2001 From: Ben Hook <5009589+benhook1013@users.noreply.github.com> Date: Sat, 3 Oct 2026 04:02:37 +1300 Subject: [PATCH 11/20] Correct initial-admission tracker legacy seed status --- .../game-session-runtime-and-tick-coordination.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) 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 e9c4707f6c..e2135b4b11 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 @@ -10,7 +10,7 @@ This tracker consolidates the live Game Session execution substrate by capabilit Retained bootstrap correction: V8 recognizes only the unchanged, provenance-backed historical demo/sandbox pair that was seeded with two public-production realms. It changes sandbox's public flag and advances only its catalog revision, retains runtime pointer and durable realm/namespace identity, and appends an immutable repair event in the same transaction. Unknown, operator-edited, incomplete, extra-public, or conflicting-history catalogs remain untouched and fail closed. This is not World-owner lifecycle or initial-bind proof. PostgreSQL execution remains a required separate check; the local environment has no Docker or PostgreSQL runtime. -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 existing configuration-driven pointer initializer and GS/WMS raw seed behavior remain legacy bootstrap inputs, not 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. +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: Durable initial-bind intent and pointer/audit commit/abort proof components, a method-specific Game Session owner-proof read connected to World’s hold reconciler, and an opt-in run-owned local Compose coordinator are wired. The coordinator validates a read-only fixture capability, resumes the descriptor-validated Game Session launch under its stable operation identity, persists initial-bind intent before requesting the World hold, and completes the owner transaction through authenticated proof. This does not implement the strict Account `JOIN` validation-through-commit gate, production activation, or generalized runtime-ID migration; default startup remains closed, and configured seed validation does not create startup authority rows without World-owned lifecycle proof. The recorded 85-path check passed 1,781 Game Session unit tests, generated Game Session jOOQ sources, compiled both integration-test source sets, and passed Flyway-version, Markdown link, and Markdown lint checks using `dev-tools/validation/run-locked-gradle.sh :game-session-service:generateJooq :game-session-service:test :game-session-service:compileIntegrationTestJava :world-management-service:compileIntegrationTestJava checkFlywayVersions linkCheck lintMarkdown --no-configuration-cache`. The 145 World Management unit tests are retained from prior validation and were not rerun at the pinned `6ffcbb663f84e0a77c5236f2029ca816923eb7b5` head; this command compiled its integration-test sources only. PostgreSQL and live Compose execution were not performed. The coordinator’s retry budget is per process; exhaustion requires an operator-mediated process restart under the same run claim, capability, and operation identity (or operator intervention), keeps World fenced, and does not establish live cross-service restart recovery or automatic generalized abort. A deterministic coordinator orchestration unit test covers budget exhaustion and fresh-coordinator replay under that same identity; it does not prove TLS capability validation, cross-service PostgreSQL races/restart, or live Compose execution. Ambiguous outcomes continue to fence World termination. See the [Game Session API status](../../architecture/microservices/game-session-service/api-contracts.md#initial-admission-bind) and canonical [World contract](../../architecture/microservices/world-management-service/api-contracts.md#initial-admission-bind-hold-contract). From deebe2c1938b998c227e9ba3ed2f0a8fa356b9e2 Mon Sep 17 00:00:00 2001 From: Ben Hook <5009589+benhook1013@users.noreply.github.com> Date: Sat, 3 Oct 2026 04:13:41 +1300 Subject: [PATCH 12/20] Select World initial-bind production constructor during Spring startup --- .../InitialAdmissionBindHoldServiceImpl.java | 2 ++ ...itialAdmissionBindHoldServiceImplTest.java | 36 +++++++++++++++++++ 2 files changed, 38 insertions(+) diff --git a/services/world-management-service/src/main/java/net/firedevops/firemud/worldmanagement/service/impl/InitialAdmissionBindHoldServiceImpl.java b/services/world-management-service/src/main/java/net/firedevops/firemud/worldmanagement/service/impl/InitialAdmissionBindHoldServiceImpl.java index 7f0b6689d1..b90eca438c 100644 --- a/services/world-management-service/src/main/java/net/firedevops/firemud/worldmanagement/service/impl/InitialAdmissionBindHoldServiceImpl.java +++ b/services/world-management-service/src/main/java/net/firedevops/firemud/worldmanagement/service/impl/InitialAdmissionBindHoldServiceImpl.java @@ -19,6 +19,7 @@ import net.firedevops.firemud.worldmanagement.repository.InitialAdmissionBindHoldRepository; import net.firedevops.firemud.worldmanagement.repository.WorldInstanceRepository; import net.firedevops.firemud.worldmanagement.service.InitialAdmissionBindHoldService; +import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Service; import org.springframework.transaction.annotation.Transactional; @@ -36,6 +37,7 @@ public class InitialAdmissionBindHoldServiceImpl implements InitialAdmissionBind private final WorldInstanceRepository worldInstanceRepository; private final Clock clock; + @Autowired public InitialAdmissionBindHoldServiceImpl( InitialAdmissionBindHoldRepository holdRepository, WorldInstanceRepository worldInstanceRepository) { diff --git a/services/world-management-service/src/test/java/unit/net/firedevops/firemud/worldmanagement/service/impl/InitialAdmissionBindHoldServiceImplTest.java b/services/world-management-service/src/test/java/unit/net/firedevops/firemud/worldmanagement/service/impl/InitialAdmissionBindHoldServiceImplTest.java index 06f68c79e8..f23515e255 100644 --- a/services/world-management-service/src/test/java/unit/net/firedevops/firemud/worldmanagement/service/impl/InitialAdmissionBindHoldServiceImplTest.java +++ b/services/world-management-service/src/test/java/unit/net/firedevops/firemud/worldmanagement/service/impl/InitialAdmissionBindHoldServiceImplTest.java @@ -2,6 +2,7 @@ import static org.junit.jupiter.api.Assertions.assertEquals; import static org.junit.jupiter.api.Assertions.assertNotEquals; +import static org.junit.jupiter.api.Assertions.assertNotNull; import static org.junit.jupiter.api.Assertions.assertThrows; import static org.junit.jupiter.api.Assertions.assertTrue; import static org.mockito.ArgumentMatchers.any; @@ -9,6 +10,7 @@ import static org.mockito.Mockito.verify; import static org.mockito.Mockito.when; +import java.time.Clock; import java.time.Instant; import java.util.Optional; import java.util.concurrent.atomic.AtomicReference; @@ -22,6 +24,7 @@ import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.Test; import org.mockito.Mockito; +import org.springframework.context.annotation.AnnotationConfigApplicationContext; class InitialAdmissionBindHoldServiceImplTest { private static final long TENANT_ID = 42L; @@ -49,6 +52,39 @@ void setUp() { .thenReturn(Optional.of(activeWorldInstance())); } + @Test + void springContextSelectsAutowiredProductionConstructor() { + try (AnnotationConfigApplicationContext context = new AnnotationConfigApplicationContext()) { + context.registerBean( + InitialAdmissionBindHoldRepository.class, + () -> Mockito.mock(InitialAdmissionBindHoldRepository.class)); + context.registerBean( + WorldInstanceRepository.class, () -> Mockito.mock(WorldInstanceRepository.class)); + context.registerBean(InitialAdmissionBindHoldServiceImpl.class); + + context.refresh(); + + assertNotNull(context.getBean(InitialAdmissionBindHoldServiceImpl.class)); + } + } + + @Test + void acquireUsesInjectedClockForDiagnosticExpiry() { + Instant now = Instant.parse("2026-09-01T00:00:00Z"); + service = + new InitialAdmissionBindHoldServiceImpl( + holdRepository, worldInstanceRepository, Clock.fixed(now, java.time.ZoneOffset.UTC)); + when(holdRepository.findByTenantIdAndRequestId(TENANT_ID, REQUEST_ID)) + .thenReturn(Optional.empty()); + when(holdRepository.hasNonterminalForRealm(TENANT_ID, REALM_UUID)).thenReturn(false); + when(holdRepository.insertIfNoUniqueConflict(any())) + .thenAnswer(invocation -> Optional.of(invocation.getArgument(0))); + + var hold = service.acquire(request()); + + assertEquals(now.plusSeconds(300), hold.diagnosticExpiresAt()); + } + @Test void acquireAllocatesOpaqueHoldAndExactRetryReusesItsIdentity() { AtomicReference persisted = new AtomicReference<>(); From 2ad31dabe8ca14326eb9b8b0c47b25e0b40e3765 Mon Sep 17 00:00:00 2001 From: Ben Hook <5009589+benhook1013@users.noreply.github.com> Date: Sat, 3 Oct 2026 04:16:10 +1300 Subject: [PATCH 13/20] feat(review): support exact additional rounds --- design/developer-workflows/pr-lifecycle.md | 2 +- dev-tools/pr_review/README.md | 2 + dev-tools/pr_review/cli.py | 7 + dev-tools/pr_review/controller.py | 47 +++- .../pr_review/sqlite_provider_imports.py | 2 + .../validation/test_pr_review_cli_runner.py | 23 ++ .../validation/test_pr_review_controller.py | 220 ++++++++++++++++++ .../test_pr_review_sqlite_provider_imports.py | 27 ++- 8 files changed, 313 insertions(+), 17 deletions(-) diff --git a/design/developer-workflows/pr-lifecycle.md b/design/developer-workflows/pr-lifecycle.md index 726f860a62..22b3009ac6 100644 --- a/design/developer-workflows/pr-lifecycle.md +++ b/design/developer-workflows/pr-lifecycle.md @@ -19,7 +19,7 @@ Use this guide for pull-request status, review handling, CI, Renovate, merging, - If that exact legacy transition is followed by a fresh review and a later coherent fix head, reauthorize only the same immutable fingerprints with `dev-tools/pr-review decide transition --reauthorize --pr --head --reason ""`. The controller requires a prior transition, verifies every carried record again, and requires every other observation to be normal completed attributable anchored evidence; newer evidence remains counting and subject to ordinary reconciliation and judgment. A changed head without this explicit reauthorization remains blocked, and the command never creates a checkpoint or consumes review quota. - A single previously audited Hosted fingerprint that is absent from the complete current history may be retired only with `--reauthorize --retire-missing-hosted-fingerprint `. This requires the exact prior fingerprint, coherent current topology, complete available Hosted trigger records and paginated GitHub review/comment history, terminal and uniquely attributable responses, no active or unresolved reservation, and no unresolved actionable findings; any missing or ambiguous proof remains held. The fingerprint stays in the transition audit and remains non-counting if it later reappears. This decision never reconstructs evidence or creates a checkpoint and does not grant review, taper, finding-count, or merge-readiness credit. - Record an explicit channel judgment with `dev-tools/pr-review decide judgment retain|reopen --pr --channel hosted|cli --head --checkpoint --reason ""`. Retain confirms the verified equivalent patch for request and queue safety; reopen explicitly requires fresh review without deleting historical completed taper and resets the taper streak at the bound checkpoint. For CLI, a reopen may bind the latest complete modern checkpoint to a proven descendant live head, but carries no new review credit until later completed results arrive. A narrow channel policy override uses `dev-tools/pr-review decide policy --pr --head --checkpoint --hosted-zero-useful --reason ""` or `--cli-zero-useful ` (exactly one channel); it sets that channel's zero-useful completion count for the exact checkpoint. -- Extend the existing allocation with `dev-tools/pr-review decide allocation grant --pr --channel hosted|cli --head [--checkpoint ] [--min-additional-completed ] [--max-additional-completed ] [--fresh-taper] --reason ""`. Both bounds count completed, attributable results for that PR and channel beginning at the decision; the optional checkpoint records the observed identity but does not move that count's start. With neither bound, the existing one-result promise remains (`min=1`, `max=1`). A minimum-only allocation has no maximum; a maximum-only allocation has no extra minimum (`min=0`). Without `--fresh-taper`, an allocation after completed taper affects queue eligibility and its additional-result count while preserving the existing historical taper display. Its zero-useful results continue the normal streak. An accepted allocated result resets the active streak at that result, while all earlier checkpoints remain visible with their original counts; after fixes, later zero-useful results can satisfy taper. `--fresh-taper` starts the active streak at the allocation decision immediately; earlier dry results remain visible historical evidence but cannot satisfy it. When both bounds are set, reject `min > max`; the minimum requires that many additional results even after fresh taper, while taper may stop earlier than the maximum once the minimum is met. Rate limits, connection failures, duplicates, partial or ambiguous responses, provisional captures, and other non-counting observations do not consume the count. Hosted and CLI allocations remain independent; request-time identity checks apply only when posting a new review. +- Extend the existing allocation with `dev-tools/pr-review decide allocation grant --pr --channel hosted|cli --head [--checkpoint ] [--min-additional-completed ] [--max-additional-completed ] [--exact-additional-completed ] [--fresh-taper] --reason ""`. Both bounds count completed, attributable results for that PR and channel beginning at the decision; the optional checkpoint records the observed identity but does not move that count's start. With neither bound, the existing one-result promise remains (`min=1`, `max=1`). A minimum-only allocation has no maximum; a maximum-only allocation has no extra minimum (`min=0`). `--exact-additional-completed N` is mutually exclusive with the separate bounds and `--fresh-taper`, and records `min=max=N`, so ordinary taper cannot stop discovery before all `N` results and the cap stops discovery immediately afterward. It preserves the existing taper rather than starting a fresh streak. Use `allocation renew --exact-additional-completed N` to replace an existing allocation or audited human stop explicitly. A verifiable request already admitted at the exact-allocation decision remains in flight and counts only when it completes attributably; ambiguous or unsupported active evidence is refused. Without `--fresh-taper`, an allocation after completed taper affects queue eligibility and its additional-result count while preserving the existing historical taper display. Its zero-useful results continue the normal streak. An accepted allocated result resets the active streak at that result, while all earlier checkpoints remain visible with their original counts; after fixes, later zero-useful results can satisfy taper. `--fresh-taper` starts the active streak at the allocation decision immediately; earlier dry results remain visible historical evidence but cannot satisfy it. When both bounds are set, reject `min > max`; the minimum requires that many additional results even after fresh taper, while taper may stop earlier than the maximum once the minimum is met. Rate limits, connection failures, duplicates, partial or ambiguous responses, provisional captures, and other non-counting observations do not consume the count. Hosted and CLI allocations remain independent; request-time identity checks apply only when posting a new review. - Normal taper can finish before a maximum once the minimum is met. After any additional result with accepted findings, no next request is allowed until those findings, current/outdated threads, actionable summary findings, and fix publication/validation obligations are clear, even if capacity remains. Once the maximum is used, no further request is allowed for that PR/channel; a maximum stop is not taper and does not waive accepted findings or fixes. `status` and `evidence` expose the minimum, maximum, completed count, baseline identity, in-flight results, taper state, and controlling reason. When the maximum is exhausted, the controller derives an audited human-cap stop and advances that channel through its normal selector without a separate `decide stop`, subject to the active-review safety described below. Pending obligations remain source-owned and visible as `cap exhausted; findings pending`; this stop is not taper, current-head review, CI/Smoke proof, or merge readiness. A bounded allocation can be replaced explicitly with `allocation renew` and new bounds; `allocation cancel` removes it. Ordinary fixes never reset its completed count. - When the Overseer deliberately allocates one further completed review before deciding whether to continue, record it before the review with `dev-tools/pr-review decide allocation grant --pr --channel hosted|cli --head --reason ""`. Completed-result counts belong to the PR and channel and survive later identity changes; rate limits, partial, duplicate, and unattributable results do not consume the allocation. Record a human decision to make no further requests with `dev-tools/pr-review decide stop --pr --channel hosted|cli --reason ""`. This audited PR/channel override bypasses the taper gate only for queue advancement; it is not taper completion or proof of review coverage, and it persists across head and parent changes. It requires no completed checkpoint, clean findings, idle provider, or coherent review topology. An already admitted CLI or Hosted run continues with its reservation, capture, attribution, and eventual findings intact; finishing that run does not clear the override. Stop recording and new-request admission share only the short state mutation boundary, while each provider keeps its execution exclusion. Optional `--head` and `--checkpoint` pins must match the observed identities; unavailable optional Git proof is recorded as absent, never fabricated. Existing ambiguity-retention and over-ceiling acknowledgment options record their specific evidence without granting review credit. Discovery can advance only when the same channel has no active provider run. Accepted fixes, pending captures and adjudication, attributable evidence, current and outdated threads, actionable summaries, required CI, runtime proof, ancestry, and merge safety remain independent obligations. A stop overrides taper only and does not manufacture a reviewed head or merge readiness. - For a channel that still needs review, targeting stops at the first held, unstable, unreconciled, over-ceiling, or judgment-blocked PR; it skips PRs whose channel has completed taper or an audited human stop. The narrow exception is a verified terminal, non-counting Hosted response: keep that PR incomplete and visible, but use the next coherent PR's Hosted window if one exists. Do not post another request on the ambiguous PR or grant it taper or merge credit; revisit its evidence or obtain an audited human stop before its merge handoff. Request-time identity and active-review checks still apply before any new request for an incomplete channel. A file-ceiling rejection requires a coherent topology decision; there is no normal incremental-review fallback. diff --git a/dev-tools/pr_review/README.md b/dev-tools/pr_review/README.md index e15fdb9227..3447df5d00 100644 --- a/dev-tools/pr_review/README.md +++ b/dev-tools/pr_review/README.md @@ -12,6 +12,8 @@ The output identifies the SQLite schema and writer build. The live shared cutove For a posted Hosted request, `dev-tools/pr-review wait hosted --pr --trigger-id ` watches only that saved trigger. `--poll-seconds` defaults to 30 and `--max-wait-minutes` to 90. It returns JSON and exit status 0 for an attributable completion, 3 for another terminal result, or 4 when the wait expires; it never posts a request, grants review credit, or retires the trigger. The caller must read the result and use `records sync-hosted --pr ` before adjudicating a completed review. A wait expiration leaves the underlying trigger unchanged. +To require exactly a chosen number of further completed attributable results on one channel, use `dev-tools/pr-review decide allocation grant --pr --channel hosted|cli --head --exact-additional-completed --reason ""`. Use `allocation renew` instead of `grant` to replace an existing allocation or human stop explicitly. The command records the existing minimum and maximum as the same positive number; it does not start a fresh taper streak. Earlier completed evidence remains historical, while a verifiable request already admitted at the decision remains in flight and consumes one result only if it later completes attributably. Failures, rate limits, and other non-counting results consume none. Discovery continues until all `N` results complete even if ordinary taper was already satisfied or becomes satisfied early, then closes at the exact cap while accepted findings and fixes remain mandatory obligations. + ### Manual Hosted adoption A human-posted Hosted CodeRabbit request can be incorporated without requesting another review: after the review completes, run `dev-tools/pr-review decide trigger-adopt-manual --pr --trigger-id --head `. This verifies the immutable public command, completed response, and current anchor before writing a private attribution record. A queued PR uses its reconciled stack parent; an off-queue PR uses its actual live base branch after matching the live base and head tips to their remote refs. Off-queue adoption leaves the configured review queue unchanged. The command does not post a GitHub comment, create a result checkpoint, or grant taper by itself; adjudicate findings and post the normal public Hosted checkpoint next. A moved head or ambiguous response is refused. diff --git a/dev-tools/pr_review/cli.py b/dev-tools/pr_review/cli.py index d2c828a5ed..e801cb7eac 100644 --- a/dev-tools/pr_review/cli.py +++ b/dev-tools/pr_review/cli.py @@ -408,6 +408,12 @@ def records_database(command: argparse.ArgumentParser) -> None: metavar="N", help="maximum additional completed attributable results after the decision", ) + allocation.add_argument( + "--exact-additional-completed", + type=_positive_int, + metavar="N", + help="require exactly N additional completed attributable results after the decision", + ) allocation.add_argument( "--fresh-taper", action="store_true", @@ -1662,6 +1668,7 @@ def record(current): checkpoint=args.checkpoint, min_additional_completed=args.min_additional_completed, max_additional_completed=args.max_additional_completed, + exact_additional_completed=args.exact_additional_completed, fresh_taper=args.fresh_taper, ), 0 if args.decide_command == "stop": diff --git a/dev-tools/pr_review/controller.py b/dev-tools/pr_review/controller.py index 1faacac900..1ddfd072de 100644 --- a/dev-tools/pr_review/controller.py +++ b/dev-tools/pr_review/controller.py @@ -5607,6 +5607,7 @@ def decide_allocation( checkpoint: str | None = None, min_additional_completed: int | None = None, max_additional_completed: int | None = None, + exact_additional_completed: int | None = None, fresh_taper: bool = False, ) -> dict[str, Any]: """Grant, replace, or cancel a one-result or bounded review allocation.""" @@ -5623,6 +5624,22 @@ def decide_allocation( raise ControllerError("fresh taper selection must be boolean") if checkpoint is not None and (not isinstance(checkpoint, str) or not checkpoint.strip()): raise ControllerError("allocation baseline checkpoint must be a non-empty immutable identity") + if exact_additional_completed is not None and ( + isinstance(exact_additional_completed, bool) + or not isinstance(exact_additional_completed, int) + or exact_additional_completed <= 0 + ): + raise ControllerError("exact additional completed reviews must be a positive integer") + if exact_additional_completed is not None and ( + min_additional_completed is not None or max_additional_completed is not None + ): + raise ControllerError("exact additional completed reviews cannot be combined with minimum or maximum") + if exact_additional_completed is not None and fresh_taper: + raise ControllerError("exact additional completed reviews preserve the existing taper") + exact_replacement = exact_additional_completed is not None + if exact_replacement: + min_additional_completed = exact_additional_completed + max_additional_completed = exact_additional_completed if min_additional_completed is not None and ( isinstance(min_additional_completed, bool) or not isinstance(min_additional_completed, int) @@ -5706,10 +5723,26 @@ def provable_posted_hosted_request(value: Any) -> bool: and self._hosted_anchor_matches(value, pr, current) ) + def exact_in_flight_request(value: Any) -> bool: + if not exact_replacement or _field(value, "channel") not in (None, selected.value): + return False + if selected == policy.Channel.HOSTED: + return self._hosted_active_response_overlaps_cli( + value, + pr, + item.head, + current, + require_response_identity=True, + ) + return self._active_cli_review_overlaps_hosted(value, pr, current) + + def permitted_in_flight_request(value: Any) -> bool: + return exact_in_flight_request(value) if exact_replacement else provable_posted_hosted_request(value) + stop_evidence_checked = False if ( bounded_replacement - and not any(provable_posted_hosted_request(value) for value in history) + and not any(permitted_in_flight_request(value) for value in history) and ( prior_taper_complete or any( @@ -5749,7 +5782,7 @@ def provable_posted_hosted_request(value: Any) -> bool: and target.pr == pr and target.status == policy.ReviewStatus.JUDGMENT_REQUIRED ): - if not fresh_taper: + if not fresh_taper and not exact_replacement: raise ControllerError( "bounded Hosted allocation after a judgment-required taper must explicitly reopen fresh taper" ) @@ -5769,12 +5802,12 @@ def provable_posted_hosted_request(value: Any) -> bool: bounded_replacement and target.pr == pr and target.status == policy.ReviewStatus.HELD - and any(provable_posted_hosted_request(value) for value in history) + and any(permitted_in_flight_request(value) for value in history) ): raise elif bounded_replacement: assert previous is not None - if previous.stop_basis is not None: + if previous.stop_basis is not None and not exact_replacement: raise ControllerError("a stopped allocation cannot be renewed") if self._head_repository_problem(item): raise ControllerError(f"PR #{pr} has an unsupported head repository") @@ -5798,10 +5831,12 @@ def provable_posted_hosted_request(value: Any) -> bool: _field(value, flag) is True for flag in ("held", "unstable", "rate_limited", "unreconciled", "parent_moved", "over_ceiling") ) and _field(value, "head", "reviewed_head") in (None, "", item.head) - if blocked and not provable_posted_hosted_request(value): + if blocked and not permitted_in_flight_request(value): raise ControllerError("current review evidence is blocked; allocation cannot be promised") baseline = tuple( - _field(value, "checkpoint", "checkpoint_id") for value in history if _field(value, "correction") is not True + _field(value, "checkpoint", "checkpoint_id") + for value in history + if _field(value, "correction") is not True and not exact_in_flight_request(value) ) if any(not isinstance(value, str) or not value for value in baseline): raise ControllerError("existing review evidence lacks a checkpoint identity") diff --git a/dev-tools/pr_review/sqlite_provider_imports.py b/dev-tools/pr_review/sqlite_provider_imports.py index b1c2e34a09..a9ecbed963 100644 --- a/dev-tools/pr_review/sqlite_provider_imports.py +++ b/dev-tools/pr_review/sqlite_provider_imports.py @@ -433,6 +433,8 @@ def _import_reply_only_hosted_checkpoint( checkpoint, state.response_id, state.duration_seconds, + repo, + pr_number, captured_head, record, hosted_payload, diff --git a/dev-tools/validation/test_pr_review_cli_runner.py b/dev-tools/validation/test_pr_review_cli_runner.py index 2a1c58e2c2..dd2390bf27 100644 --- a/dev-tools/validation/test_pr_review_cli_runner.py +++ b/dev-tools/validation/test_pr_review_cli_runner.py @@ -101,6 +101,29 @@ def test_minimum_and_maximum_are_optional_without_a_pinned_checkpoint(self): self.assertIsNone(maximum_only.min_additional_completed) self.assertEqual(maximum_only.max_additional_completed, 3) + def test_exact_additional_completed_accepts_only_a_positive_integer(self): + common = [ + "decide", + "allocation", + "grant", + "--pr", + "2827", + "--channel", + "cli", + "--head", + HEAD, + "--reason", + "three more completed CLI rounds", + "--exact-additional-completed", + ] + + args = _parser().parse_args([*common, "3"]) + + self.assertEqual(args.exact_additional_completed, 3) + for invalid in ("0", "-1", "not-an-integer"): + with self.subTest(invalid=invalid), self.assertRaises(SystemExit): + _parser().parse_args([*common, invalid]) + def test_legacy_cancel_shape_needs_no_cap_replacement(self): args = _parser().parse_args( [ diff --git a/dev-tools/validation/test_pr_review_controller.py b/dev-tools/validation/test_pr_review_controller.py index 414a305672..5f794ee432 100644 --- a/dev-tools/validation/test_pr_review_controller.py +++ b/dev-tools/validation/test_pr_review_controller.py @@ -3404,6 +3404,226 @@ def test_bounded_allocation_can_be_renewed_or_cancelled_explicitly(self): ) self.assertEqual(cancelled["allocations"], []) + def test_exact_allocation_maps_to_equal_bounds_and_replaces_a_stopped_allocation(self): + for channel in ("hosted", "cli"): + with self.subTest(channel=channel): + evidence = {(1, channel): [self.scope_timeline_evidence(channel=channel)]} + controller = self.make({1: pr(1, HEAD_1)}, evidence, heads={"feature-1": HEAD_1}, sqlite=True) + controller.set_stack([1]) + controller.decide_stop(pr=1, channel=channel, reason="human stopped ordinary discovery") + + renewed = controller.decide_allocation( + action="renew", + pr=1, + channel=channel, + head=HEAD_1, + exact_additional_completed=2, + reason="run exactly two more completed rounds", + ) + + self.assertEqual(renewed["allocation"]["min_additional_completed"], 2) + self.assertEqual(renewed["allocation"]["max_additional_completed"], 2) + self.assertIsNone(renewed["allocation"]["stop_basis"]) + self.assertFalse(renewed["allocation"].get("reopens_taper", False)) + + def test_exact_allocation_explicitly_replaces_an_exhausted_allocation(self): + evidence = {(1, "hosted"): [self.allocation_evidence(checkpoint="baseline")]} + controller = self.grant_bounded_allocation(checkpoint="baseline", cap=1, minimum=1, evidence=evidence) + evidence[(1, "hosted")].append(self.allocation_evidence(checkpoint="exhausted-result")) + self.assertEqual(controller.status()["prs"][0]["allocations"]["hosted"]["remaining"], 0) + + renewed = controller.decide_allocation( + action="renew", + pr=1, + channel="hosted", + head=HEAD_1, + exact_additional_completed=2, + reason="replace the exhausted tranche with exactly two more rounds", + ) + + self.assertEqual(renewed["progress"]["completed_count"], 0) + self.assertEqual(renewed["progress"]["remaining"], 2) + + def test_exact_allocation_retains_one_admitted_request_until_it_completes_or_fails(self): + for channel, terminal, same_checkpoint in ( + ("hosted", "completed", False), + ("cli", "completed", True), + ("cli", "failed", True), + ): + with self.subTest(channel=channel, terminal=terminal): + if channel == "hosted": + active = { + "pr": 1, + "head": HEAD_1, + "checkpoint": "trigger:45", + "trigger_id": 45, + "response_id": 46, + "state": "active", + "active_reservation": True, + "held": True, + "unstable": False, + "attributable": True, + "terminal": False, + "reason": HOSTED_ACTIVE_RESPONSE_REASON, + "anchor": { + "pr": 1, + "child_head": HEAD_1, + "parent_identity": "develop", + "parent_head": BASE, + "merge_base": BASE, + "patch_id": f"patch-{HEAD_1[:4]}", + }, + } + else: + active = { + "pr": 1, + "head": HEAD_1, + "child_head": HEAD_1, + "parent_identity": "develop", + "parent_head": BASE, + "merge_base": BASE, + "patch_id": f"patch-{HEAD_1[:4]}", + "checkpoint": "active-cli:run." + "a" * 32, + "active_review": True, + "held": True, + "current_lock_owner": True, + } + evidence = { + (1, channel): [ + self.scope_timeline_evidence(channel=channel), + active, + ] + } + controller = self.make({1: pr(1, HEAD_1)}, evidence, heads={"feature-1": HEAD_1}, sqlite=True) + controller.set_stack([1]) + controller.decide_stop(pr=1, channel=channel, reason="stop while the admitted request finishes") + + renewed = controller.decide_allocation( + action="renew", + pr=1, + channel=channel, + head=HEAD_1, + exact_additional_completed=2, + reason="retain the admitted request and complete exactly two rounds", + ) + self.assertEqual(renewed["progress"]["in_flight"], 1) + self.assertEqual(renewed["progress"]["used"], 0) + + if terminal == "completed": + replacement = self.allocation_evidence( + checkpoint=active["checkpoint"] if same_checkpoint else "completed-after-decision", + channel=channel, + ) + else: + replacement = self.allocation_evidence( + checkpoint=active["checkpoint"] if same_checkpoint else "failed-after-decision", + channel=channel, + completed=False, + attributable=False, + rate_limited=True, + ) + evidence[(1, channel)][1] = replacement + progress = controller.status()["prs"][0]["allocations"][channel] + + self.assertEqual(progress["used"], 1 if terminal == "completed" else 0) + self.assertEqual(progress["remaining"], 1 if terminal == "completed" else 2) + + def test_exact_allocation_rejects_unsupported_active_evidence_without_replacing_stop(self): + cases = { + "wrong-channel": {"channel": "hosted"}, + "wrong-pr": {"pr": 2}, + "moved-anchor": {"parent_head": HEAD_2}, + "ambiguous": {"unstable": True}, + } + for name, changed in cases.items(): + with self.subTest(name=name): + evidence = {(1, "cli"): [self.scope_timeline_evidence(channel="cli")]} + controller = self.make({1: pr(1, HEAD_1)}, evidence, heads={"feature-1": HEAD_1}, sqlite=True) + controller.set_stack([1]) + controller.decide_stop(pr=1, channel="cli", reason="retain the audited stop") + active = { + "pr": 1, + "head": HEAD_1, + "child_head": HEAD_1, + "parent_identity": "develop", + "parent_head": BASE, + "merge_base": BASE, + "patch_id": f"patch-{HEAD_1[:4]}", + "checkpoint": "active-cli:run." + "b" * 32, + "active_review": True, + "held": True, + "current_lock_owner": True, + **changed, + } + evidence[(1, "cli")].append(active) + stopped = controller.store.load() + + with self.assertRaises(ControllerError): + controller.decide_allocation( + action="renew", + pr=1, + channel="cli", + head=HEAD_1, + exact_additional_completed=2, + reason="unsupported active evidence must fail closed", + ) + + self.assertEqual(controller.store.load(), stopped) + + def test_exact_allocation_does_not_stop_at_existing_or_early_taper(self): + for channel, prior_count in (("hosted", 1), ("cli", 3)): + with self.subTest(channel=channel): + history = [ + self.allocation_evidence(checkpoint=f"prior-{index}", channel=channel) + for index in range(prior_count) + ] + history.append(self.scope_timeline_evidence(channel=channel)) + evidence = {(1, channel): history} + controller = self.make({1: pr(1, HEAD_1)}, evidence, heads={"feature-1": HEAD_1}, sqlite=True) + controller.set_stack([1]) + + controller.decide_allocation( + action="grant", + pr=1, + channel=channel, + head=HEAD_1, + exact_additional_completed=2, + reason="complete two rounds after ordinary taper", + ) + history.append(self.allocation_evidence(checkpoint="exact-first", channel=channel)) + first = controller.status()["prs"][0]["allocations"][channel] + self.assertEqual((first["status"], first["used"]), ("CAP_ACTIVE", 1)) + + history.append(self.allocation_evidence(checkpoint="exact-second", channel=channel)) + final = controller.status()["prs"][0]["allocations"][channel] + self.assertIn(final["status"], {"CAP_TAPERED", "CAP_AUDITED_STOP"}) + self.assertEqual((final["used"], final["remaining"]), (2, 0)) + + def test_exact_allocation_rejects_invalid_or_conflicting_values_without_mutation(self): + controller = self.make({1: pr(1, HEAD_1)}, heads={"feature-1": HEAD_1}, sqlite=True) + controller.set_stack([1]) + original = controller.store.load() + + for exact, extra, message in ( + (0, {}, "positive integer"), + (-1, {}, "positive integer"), + (True, {}, "positive integer"), + (2, {"min_additional_completed": 1}, "cannot be combined"), + (2, {"max_additional_completed": 3}, "cannot be combined"), + (2, {"fresh_taper": True}, "preserve the existing taper"), + ): + with self.subTest(exact=exact, extra=extra), self.assertRaisesRegex(ControllerError, message): + controller.decide_allocation( + action="grant", + pr=1, + channel="hosted", + head=HEAD_1, + exact_additional_completed=exact, + reason="invalid exact allocation", + **extra, + ) + self.assertEqual(controller.store.load(), original) + def test_bounded_dry_result_can_be_renewed_without_stop_authorization(self): evidence = {(1, "hosted"): [self.allocation_evidence(checkpoint="baseline", channel="hosted")]} controller = self.grant_bounded_allocation( diff --git a/dev-tools/validation/test_pr_review_sqlite_provider_imports.py b/dev-tools/validation/test_pr_review_sqlite_provider_imports.py index 4d5ae00892..01b3c3e287 100644 --- a/dev-tools/validation/test_pr_review_sqlite_provider_imports.py +++ b/dev-tools/validation/test_pr_review_sqlite_provider_imports.py @@ -806,17 +806,24 @@ def test_reply_only_zero_checkpoint_requires_exact_edited_trigger_reply(self) -> path.parent.mkdir(parents=True) path.write_text(json.dumps(record), encoding="utf-8") - imported = pr_review.sqlite_provider_imports.import_hosted_checkpoint( - self.records, - repo=REPO, - pr_number=PR, - checkpoint=checkpoint, - actor="reviewer", - common=self.common, - scope="broad", - hosted_payload=payload, - ) + proof_method = pr_review.runtime.LiveEvidence._hosted_zero_reply_proof + with patch.object( + pr_review.runtime.LiveEvidence, + "_hosted_zero_reply_proof", + wraps=proof_method, + ) as zero_reply_proof: + imported = pr_review.sqlite_provider_imports.import_hosted_checkpoint( + self.records, + repo=REPO, + pr_number=PR, + checkpoint=checkpoint, + actor="reviewer", + common=self.common, + scope="broad", + hosted_payload=payload, + ) + self.assertEqual(zero_reply_proof.call_args.args[3:5], (REPO, PR)) self.assertEqual(imported["provider_id"], "trigger:101") self.assertEqual(imported["counts"], {"found": 0, "accepted": 0, "routed": 0}) self.assertEqual(set(imported["archive_artifacts"]), {"hosted_comments", "hosted_review", "metadata"}) From 4c5e40e1a2a3ba36013114fbfbd6ca3ec20501d0 Mon Sep 17 00:00:00 2001 From: Ben Hook <5009589+benhook1013@users.noreply.github.com> Date: Sat, 3 Oct 2026 04:28:55 +1300 Subject: [PATCH 14/20] fix(review): retain active Hosted allocation evidence --- dev-tools/pr_review/runtime.py | 3 ++ .../validation/test_pr_review_controller.py | 32 +++++++++++-------- 2 files changed, 21 insertions(+), 14 deletions(-) diff --git a/dev-tools/pr_review/runtime.py b/dev-tools/pr_review/runtime.py index 731730b2bf..1f96df1299 100644 --- a/dev-tools/pr_review/runtime.py +++ b/dev-tools/pr_review/runtime.py @@ -1684,6 +1684,9 @@ def _current_hosted_history( observation["anchor"] = dict(anchor) if isinstance(anchor, Mapping) else None observation["trigger_id"] = state.trigger_comment_id observation["response_id"] = state.response_id + observation["state"] = state.state + observation["attributable"] = state.attributed + observation["terminal"] = state.terminal if state.state == "ambiguous" and not operational_only: terminal_observation = self._terminal_ambiguous_hosted_observation(pr, record, state, payload) if terminal_observation is not None: diff --git a/dev-tools/validation/test_pr_review_controller.py b/dev-tools/validation/test_pr_review_controller.py index 5f794ee432..ed84bc8011 100644 --- a/dev-tools/validation/test_pr_review_controller.py +++ b/dev-tools/validation/test_pr_review_controller.py @@ -3452,19 +3452,7 @@ def test_exact_allocation_retains_one_admitted_request_until_it_completes_or_fai ): with self.subTest(channel=channel, terminal=terminal): if channel == "hosted": - active = { - "pr": 1, - "head": HEAD_1, - "checkpoint": "trigger:45", - "trigger_id": 45, - "response_id": 46, - "state": "active", - "active_reservation": True, - "held": True, - "unstable": False, - "attributable": True, - "terminal": False, - "reason": HOSTED_ACTIVE_RESPONSE_REASON, + record = { "anchor": { "pr": 1, "child_head": HEAD_1, @@ -3472,8 +3460,24 @@ def test_exact_allocation_retains_one_admitted_request_until_it_completes_or_fai "parent_head": BASE, "merge_base": BASE, "patch_id": f"patch-{HEAD_1[:4]}", - }, + } } + state = SimpleNamespace( + state="active", + head_sha=HEAD_1, + trigger_comment_id=45, + response_id=46, + terminal=False, + attributed=True, + reason=HOSTED_ACTIVE_RESPONSE_REASON, + ) + live_evidence = LiveEvidence("owner/repo", LiveGitHub("owner/repo")) + with ( + patch.object(hosted, "current_trigger_record_paths", return_value=[Path("/trigger.json")]), + patch.object(hosted, "load_trigger_reservation", return_value=record), + patch.object(hosted, "trigger_state", return_value=state), + ): + active = live_evidence._current_hosted_history(1, HEAD_1, {}, set())[0] else: active = { "pr": 1, From d72bcdfa66e7e335ad13f42a311b883ffd3668c6 Mon Sep 17 00:00:00 2001 From: Ben Hook <5009589+benhook1013@users.noreply.github.com> Date: Sat, 3 Oct 2026 05:02:04 +1300 Subject: [PATCH 15/20] fix(world): repair initial admission smoke and CI setup --- .../game-session-runtime-and-tick-coordination.md | 2 +- .../implementation-tracking/world-runtime-and-movement.md | 2 +- .../firemud/worldmanagement/entity/WorldInstance.java | 2 +- .../InitialAdmissionBindHoldPostgresIntegrationTest.java | 2 ++ .../worldmanagement/RoomRepositoryPostgresIntegrationTest.java | 2 ++ .../WorldManagementServiceApplicationIntegrationTest.java | 2 ++ .../service/impl/WorldLifecycleCommandServiceImplTest.java | 1 + 7 files changed, 10 insertions(+), 3 deletions(-) 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 e2135b4b11..eaf5c7804a 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 @@ -45,7 +45,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 (see [Game Session API implementation status](../../architecture/microservices/game-session-service/api-contracts.md#implementation-status)); lease-owner forwarding for independently partitioned regions is not. Its initial-admission owner sub-boundary contributes to `AR-3.1`: durable catalog/intent and pointer/audit commit/abort components, typed owner-proof receiver/client, run-owned launch resume, and the opt-in fixture coordinator are wired; general `StartSession` retry integration is not claimed. | `proven` for the front-door and routing seams: [GameSessionWebSocketHandlerTest](../../../services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/websocket/GameSessionWebSocketHandlerTest.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); `audited` for the initial-admission sub-boundary: local owner/coordinator tests cover their unit seams, but cross-service PostgreSQL race/restart proof and live Compose execution are not established. | [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); [RunOwnedInitialAdmissionFixtureCoordinator.java](../../../services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/data/RunOwnedInitialAdmissionFixtureCoordinator.java); [RunOwnedInitialAdmissionFixtureCapability.java](../../../services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/data/RunOwnedInitialAdmissionFixtureCapability.java); [GameInstanceServiceImpl.java](../../../services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/service/impl/GameInstanceServiceImpl.java); [V9 initial-admission owner ledger](../../../services/game-session-service/src/main/resources/db/migration/V9__initial_admission_bind_owner_ledger.sql); [GetInitialAdmissionBindProof](../../../protos/game-session/v1/game_session_service.proto); [InitialAdmissionBindOwnerReadWorkloadGuard.java](../../../services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/service/impl/InitialAdmissionBindOwnerReadWorkloadGuard.java); [GrpcGameSessionInitialAdmissionBindProofClient.java](../../../services/world-management-service/src/main/java/net/firedevops/firemud/worldmanagement/client/GrpcGameSessionInitialAdmissionBindProofClient.java) | [GameSessionWebSocketHandlerTest](../../../services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/websocket/GameSessionWebSocketHandlerTest.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); [GameSessionGrpcServiceTest](../../../services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/service/impl/GameSessionGrpcServiceTest.java); [InitialAdmissionBindServiceTest.java](../../../services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/service/impl/InitialAdmissionBindServiceTest.java); [InitialAdmissionBindOwnerReadTest.java](../../../services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/service/impl/InitialAdmissionBindOwnerReadTest.java); [RunOwnedInitialAdmissionFixtureCapabilityTest.java](../../../services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/data/RunOwnedInitialAdmissionFixtureCapabilityTest.java); [RunOwnedInitialAdmissionFixtureCoordinatorTest.java](../../../services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/data/RunOwnedInitialAdmissionFixtureCoordinatorTest.java); [GameInstanceServiceImplTest.java](../../../services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/service/impl/GameInstanceServiceImplTest.java); [GrpcGameSessionInitialAdmissionBindProofClientTest.java](../../../services/world-management-service/src/test/java/unit/net/firedevops/firemud/worldmanagement/client/GrpcGameSessionInitialAdmissionBindProofClientTest.java); [InitialAdmissionBindPostgresIntegrationTest.java](../../../services/game-session-service/src/test/java/integration/net/firedevops/firemud/gamesession/service/InitialAdmissionBindPostgresIntegrationTest.java) | `AR-3.1` runtime lifecycle in [Game Authoring](./game-authoring-publishing-and-activation.md#capability-status); `GR-2.1` World hold and termination fence in the [World runtime tracker](./world-runtime-and-movement.md#capability-status); `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; an ambiguous result continues to fence World termination. The API contract requires front-end-to-lease-owner forwarding to be fenced, with retry/ambiguity handling. The current owner boundary is game-instance scoped and does not implement that forwarding or true region partitioning; no new design decision is recorded. | +| `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 (see [Game Session API implementation status](../../architecture/microservices/game-session-service/api-contracts.md#implementation-status)); lease-owner forwarding for independently partitioned regions is not. Its initial-admission owner sub-boundary contributes to `AR-3.1`: durable catalog/intent and pointer/audit commit/abort components, typed owner-proof receiver/client, run-owned launch resume, and the opt-in fixture coordinator are wired; general `StartSession` retry integration is not claimed. | `proven` for the front-door and routing seams: [GameSessionWebSocketHandlerTest](../../../services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/websocket/GameSessionWebSocketHandlerTest.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); `audited` for the initial-admission sub-boundary: local owner/coordinator tests cover their unit seams, but cross-service PostgreSQL race/restart proof and live Compose execution are not established. | [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); [RunOwnedInitialAdmissionFixtureCoordinator.java](../../../services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/data/RunOwnedInitialAdmissionFixtureCoordinator.java); [RunOwnedInitialAdmissionFixtureCapability.java](../../../services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/data/RunOwnedInitialAdmissionFixtureCapability.java); [GameInstanceServiceImpl.java](../../../services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/service/impl/GameInstanceServiceImpl.java); [V9 initial-admission owner ledger](../../../services/game-session-service/src/main/resources/db/migration/V9__initial_admission_bind_owner_ledger.sql); [GetInitialAdmissionBindProof](../../../protos/game-session/v1/game_session_service.proto); [InitialAdmissionBindOwnerReadWorkloadGuard.java](../../../services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/service/impl/InitialAdmissionBindOwnerReadWorkloadGuard.java); [GrpcGameSessionInitialAdmissionBindProofClient.java](../../../services/world-management-service/src/main/java/net/firedevops/firemud/worldmanagement/client/GrpcGameSessionInitialAdmissionBindProofClient.java) | [GameSessionWebSocketHandlerTest](../../../services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/websocket/GameSessionWebSocketHandlerTest.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); [GameSessionGrpcServiceTest](../../../services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/service/impl/GameSessionGrpcServiceTest.java); [InitialAdmissionBindServiceTest.java](../../../services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/service/impl/InitialAdmissionBindServiceTest.java); [InitialAdmissionBindOwnerReadTest.java](../../../services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/service/impl/InitialAdmissionBindOwnerReadTest.java); [RunOwnedInitialAdmissionFixtureCapabilityTest.java](../../../services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/data/RunOwnedInitialAdmissionFixtureCapabilityTest.java); [RunOwnedInitialAdmissionFixtureCoordinatorTest.java](../../../services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/data/RunOwnedInitialAdmissionFixtureCoordinatorTest.java); [GameInstanceServiceImplTest.java](../../../services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/service/impl/GameInstanceServiceImplTest.java); [GrpcGameSessionInitialAdmissionBindProofClientTest.java](../../../services/world-management-service/src/test/java/unit/net/firedevops/firemud/worldmanagement/client/GrpcGameSessionInitialAdmissionBindProofClientTest.java); [InitialAdmissionBindPostgresIntegrationTest.java](../../../services/game-session-service/src/test/java/integration/net/firedevops/firemud/gamesession/service/InitialAdmissionBindPostgresIntegrationTest.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; an ambiguous result continues to fence World termination. The API contract requires front-end-to-lease-owner forwarding to be fenced, with retry/ambiguity handling. The current owner boundary is game-instance scoped and does not implement that forwarding or true region partitioning; no new design decision is recorded. | | `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/world-runtime-and-movement.md b/design/project-management/implementation-tracking/world-runtime-and-movement.md index a43c4229a5..e6e42d9651 100644 --- a/design/project-management/implementation-tracking/world-runtime-and-movement.md +++ b/design/project-management/implementation-tracking/world-runtime-and-movement.md @@ -26,7 +26,7 @@ These links add decision provenance only; they do not upgrade world runtime, lif | Capability | Implementation | Verification | Design | Implementation anchors | Proof anchors | Secondary handoffs | Gap or decision | | --- | --- | --- | --- | --- | --- | --- | --- | -| `GR-2.1` World topology, rooms, regions, and runtime instances | `partial`: version-scoped topology, Draft mutation, and instance lifecycle exist, but generation still has hardcoded inputs, initial event scheduling is absent, and lifecycle prepare/activate retain blocking attestation calls. The World-owned initial-admission hold is a lifecycle sub-boundary under `GR-2.1` that contributes to the `AR-3.1` runtime lifecycle handoff: exact hold acquisition, serialized termination blocking, fail-closed reconciliation, authenticated Game Session owner readback, and the run-owned local Compose caller are wired; general `StartSession` retry integration is not claimed. Accepted publication and procedural-generation decisions now define World-owned topology, request-bounded replay, atomic visibility, explicit replacement, and sparse/full-grid boundaries; typed ingress, destructive plans, staging bounds, and large-grid proof remain incomplete. | `audited`: focused unit tests cover topology, lifecycle, hold acquisition, termination blocking, and reconciliation; PostgreSQL hold/termination race and restart proof and live Compose execution are not established for this boundary. | [World Management ownership](../../architecture/microservices/world-management-service/README.md); [World API contracts](../../architecture/microservices/world-management-service/api-contracts.md); [initial-admission bind hold contract](../../architecture/microservices/world-management-service/api-contracts.md#initial-admission-bind-hold-contract); [runtime and data](../../architecture/microservices/world-management-service/runtime-and-data.md); [world creation workflow](../../architecture/microservices/world-management-service/world-creation-workflow.md); [ADR 0093](../../architecture/decisions/adr-0093-game-design-coordinated-digest-attested-content-publication.md); [ADR 0098](../../architecture/decisions/adr-0098-request-bounded-generation-replay-and-explicit-regeneration.md); [ADR 0099](../../architecture/decisions/adr-0099-bounded-atomic-generation-with-staging-for-large-outputs.md); [ADR 0100](../../architecture/decisions/adr-0100-separate-generation-ingress-with-one-world-owned-engine.md); [ADR 0101](../../architecture/decisions/adr-0101-explicit-destructive-regeneration-with-previewed-scope.md); [ADR 0102](../../architecture/decisions/adr-0102-first-class-sparse-and-full-grid-world-topologies.md); [ADR 0123](../../architecture/decisions/adr-0123-database-authoritative-temporal-coordinated-world-lifecycle.md); [run-owned player-flow smoke boundary](../../architecture/system-architecture-testing.md#player-flow-smoke-and-reset-boundaries) | [WorldDesignMutationServiceImpl.java](../../../services/world-management-service/src/main/java/net/firedevops/firemud/worldmanagement/service/impl/WorldDesignMutationServiceImpl.java); [WorldInstanceActivationServiceImpl.java](../../../services/world-management-service/src/main/java/net/firedevops/firemud/worldmanagement/service/impl/WorldInstanceActivationServiceImpl.java); [WorldLifecycleCommandServiceImpl.java](../../../services/world-management-service/src/main/java/net/firedevops/firemud/worldmanagement/service/impl/WorldLifecycleCommandServiceImpl.java); [InitialAdmissionBindHoldServiceImpl.java](../../../services/world-management-service/src/main/java/net/firedevops/firemud/worldmanagement/service/impl/InitialAdmissionBindHoldServiceImpl.java); [InitialAdmissionBindHoldRepository.java](../../../services/world-management-service/src/main/java/net/firedevops/firemud/worldmanagement/repository/InitialAdmissionBindHoldRepository.java); [GrpcGameSessionInitialAdmissionBindProofClient.java](../../../services/world-management-service/src/main/java/net/firedevops/firemud/worldmanagement/client/GrpcGameSessionInitialAdmissionBindProofClient.java); [V18 version-scoped templates](../../../services/world-management-service/src/main/resources/db/migration/V18__version_scoped_world_templates.sql); [V19 mutation ledger](../../../services/world-management-service/src/main/resources/db/migration/V19__world_design_mutation_ledger.sql); [V23 initial-admission hold](../../../services/world-management-service/src/main/resources/db/migration/V23__initial_admission_bind_hold.sql) | [WorldDesignMutationServiceImplTest.java](../../../services/world-management-service/src/test/java/unit/net/firedevops/firemud/worldmanagement/service/impl/WorldDesignMutationServiceImplTest.java); [WorldDraftDesignDigestServiceImplTest.java](../../../services/world-management-service/src/test/java/unit/net/firedevops/firemud/worldmanagement/service/impl/WorldDraftDesignDigestServiceImplTest.java); [WorldLifecycleCommandServiceImplTest.java](../../../services/world-management-service/src/test/java/unit/net/firedevops/firemud/worldmanagement/service/impl/WorldLifecycleCommandServiceImplTest.java); [WorldManagementGrpcServiceTest.java](../../../services/world-management-service/src/test/java/unit/net/firedevops/firemud/worldmanagement/service/impl/WorldManagementGrpcServiceTest.java); [InitialAdmissionBindHoldServiceImplTest.java](../../../services/world-management-service/src/test/java/unit/net/firedevops/firemud/worldmanagement/service/impl/InitialAdmissionBindHoldServiceImplTest.java); [InitialAdmissionBindHoldRepositoryTest.java](../../../services/world-management-service/src/test/java/unit/net/firedevops/firemud/worldmanagement/repository/InitialAdmissionBindHoldRepositoryTest.java); [InitialAdmissionBindHoldPostgresIntegrationTest.java](../../../services/world-management-service/src/test/java/integration/net/firedevops/firemud/worldmanagement/InitialAdmissionBindHoldPostgresIntegrationTest.java) | [AR-3.1 lifecycle in Game Authoring](./game-authoring-publishing-and-activation.md#capability-status); [realm routing](./realm-routing-and-playable-state.md); [Game Session runtime](./game-session-runtime-and-tick-coordination.md) | The hold keeps ambiguous initial-admission outcomes fenced and does not complete the strict Account `JOIN` gate, production activation, or generalized runtime-ID migration. PostgreSQL race/restart proof and live Compose execution remain open. | +| `GR-2.1` World topology, rooms, regions, and runtime instances | `partial`: version-scoped topology, Draft mutation, and instance lifecycle exist, but generation still has hardcoded inputs, initial event scheduling is absent, and lifecycle prepare/activate retain blocking attestation calls. The World-owned initial-admission hold is a lifecycle sub-boundary under `GR-2.1` that contributes to the `AR-3.1` runtime lifecycle handoff: exact hold acquisition, serialized termination blocking, fail-closed reconciliation, authenticated Game Session owner readback, and the run-owned local Compose caller are wired; general `StartSession` retry integration is not claimed. Accepted publication and procedural-generation decisions now define World-owned topology, request-bounded replay, atomic visibility, explicit replacement, and sparse/full-grid boundaries; typed ingress, destructive plans, staging bounds, and large-grid proof remain incomplete. | `audited`: focused unit tests cover topology, lifecycle, hold acquisition, termination blocking, and reconciliation; PostgreSQL hold/termination race and restart proof and live Compose execution are not established for this boundary. | [World Management ownership](../../architecture/microservices/world-management-service/README.md); [World API contracts](../../architecture/microservices/world-management-service/api-contracts.md); [initial-admission bind hold contract](../../architecture/microservices/world-management-service/api-contracts.md#initial-admission-bind-hold-contract); [runtime and data](../../architecture/microservices/world-management-service/runtime-and-data.md); [world creation workflow](../../architecture/microservices/world-management-service/world-creation-workflow.md); [ADR 0093](../../architecture/decisions/adr-0093-game-design-coordinated-digest-attested-content-publication.md); [ADR 0098](../../architecture/decisions/adr-0098-request-bounded-generation-replay-and-explicit-regeneration.md); [ADR 0099](../../architecture/decisions/adr-0099-bounded-atomic-generation-with-staging-for-large-outputs.md); [ADR 0100](../../architecture/decisions/adr-0100-separate-generation-ingress-with-one-world-owned-engine.md); [ADR 0101](../../architecture/decisions/adr-0101-explicit-destructive-regeneration-with-previewed-scope.md); [ADR 0102](../../architecture/decisions/adr-0102-first-class-sparse-and-full-grid-world-topologies.md); [ADR 0123](../../architecture/decisions/adr-0123-database-authoritative-temporal-coordinated-world-lifecycle.md); [run-owned player-flow smoke boundary](../../architecture/system-architecture-testing.md#player-flow-smoke-and-reset-boundaries) | [WorldDesignMutationServiceImpl.java](../../../services/world-management-service/src/main/java/net/firedevops/firemud/worldmanagement/service/impl/WorldDesignMutationServiceImpl.java); [WorldInstanceActivationServiceImpl.java](../../../services/world-management-service/src/main/java/net/firedevops/firemud/worldmanagement/service/impl/WorldInstanceActivationServiceImpl.java); [WorldLifecycleCommandServiceImpl.java](../../../services/world-management-service/src/main/java/net/firedevops/firemud/worldmanagement/service/impl/WorldLifecycleCommandServiceImpl.java); [InitialAdmissionBindHoldServiceImpl.java](../../../services/world-management-service/src/main/java/net/firedevops/firemud/worldmanagement/service/impl/InitialAdmissionBindHoldServiceImpl.java); [InitialAdmissionBindHoldRepository.java](../../../services/world-management-service/src/main/java/net/firedevops/firemud/worldmanagement/repository/InitialAdmissionBindHoldRepository.java); [GrpcGameSessionInitialAdmissionBindProofClient.java](../../../services/world-management-service/src/main/java/net/firedevops/firemud/worldmanagement/client/GrpcGameSessionInitialAdmissionBindProofClient.java); [V18 version-scoped templates](../../../services/world-management-service/src/main/resources/db/migration/V18__version_scoped_world_templates.sql); [V19 mutation ledger](../../../services/world-management-service/src/main/resources/db/migration/V19__world_design_mutation_ledger.sql); [V23 initial-admission hold](../../../services/world-management-service/src/main/resources/db/migration/V23__initial_admission_bind_hold.sql) | [WorldDesignMutationServiceImplTest.java](../../../services/world-management-service/src/test/java/unit/net/firedevops/firemud/worldmanagement/service/impl/WorldDesignMutationServiceImplTest.java); [WorldDraftDesignDigestServiceImplTest.java](../../../services/world-management-service/src/test/java/unit/net/firedevops/firemud/worldmanagement/service/impl/WorldDraftDesignDigestServiceImplTest.java); [WorldLifecycleCommandServiceImplTest.java](../../../services/world-management-service/src/test/java/unit/net/firedevops/firemud/worldmanagement/service/impl/WorldLifecycleCommandServiceImplTest.java); [WorldManagementGrpcServiceTest.java](../../../services/world-management-service/src/test/java/unit/net/firedevops/firemud/worldmanagement/service/impl/WorldManagementGrpcServiceTest.java); [InitialAdmissionBindHoldServiceImplTest.java](../../../services/world-management-service/src/test/java/unit/net/firedevops/firemud/worldmanagement/service/impl/InitialAdmissionBindHoldServiceImplTest.java); [InitialAdmissionBindHoldRepositoryTest.java](../../../services/world-management-service/src/test/java/unit/net/firedevops/firemud/worldmanagement/repository/InitialAdmissionBindHoldRepositoryTest.java); [InitialAdmissionBindHoldPostgresIntegrationTest.java](../../../services/world-management-service/src/test/java/integration/net/firedevops/firemud/worldmanagement/InitialAdmissionBindHoldPostgresIntegrationTest.java) | [AR-3.1 lifecycle in Game Authoring](./game-authoring-publishing-and-activation.md); [realm routing](./realm-routing-and-playable-state.md); [Game Session runtime](./game-session-runtime-and-tick-coordination.md) | The hold keeps ambiguous initial-admission outcomes fenced and does not complete the strict Account `JOIN` gate, production activation, or generalized runtime-ID migration. PostgreSQL race/restart proof and live Compose execution remain open. | | `GR-2.2` Location, occupancy, movement, exits, and spatial reads | `partial` | `audited` | [World API contracts](../../architecture/microservices/world-management-service/api-contracts.md); [World runtime and data](../../architecture/microservices/world-management-service/runtime-and-data.md); [system architecture](../../architecture/system-architecture-overview.md); [spatial and ambient effects](../../architecture/system-architecture-spatial-and-ambient-effects-catalog.md); [ADR 0102](../../architecture/decisions/adr-0102-first-class-sparse-and-full-grid-world-topologies.md) | [WorldManagementGrpcService.java](../../../services/world-management-service/src/main/java/net/firedevops/firemud/worldmanagement/service/impl/WorldManagementGrpcService.java); [LookAggregationService.java](../../../services/game-logic-service/src/main/java/net/firedevops/firemud/gamelogic/service/LookAggregationService.java); [MoveAggregationService.java](../../../services/game-logic-service/src/main/java/net/firedevops/firemud/gamelogic/service/MoveAggregationService.java); [MoveCommandHandler.java](../../../services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/command/text/MoveCommandHandler.java); [room contract](../../../protos/world-management/v1/world_management_service.proto) | [WorldManagementGrpcServiceTest.java](../../../services/world-management-service/src/test/java/unit/net/firedevops/firemud/worldmanagement/service/impl/WorldManagementGrpcServiceTest.java); [LookAggregationServiceTest.java](../../../services/game-logic-service/src/test/java/net/firedevops/firemud/gamelogic/service/LookAggregationServiceTest.java); [MoveAggregationServiceTest.java](../../../services/game-logic-service/src/test/java/net/firedevops/firemud/gamelogic/service/MoveAggregationServiceTest.java); [MoveCommandHandlerTest.java](../../../services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/command/text/MoveCommandHandlerTest.java); [movement idempotency test](../../../services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/service/impl/RedisMovementEffectIdempotencyServiceTest.java) | [authoring](./game-authoring-publishing-and-activation.md); [gameplay](./gameplay-rules-entities-and-effects.md); [Game Session runtime](./game-session-runtime-and-tick-coordination.md); [player experience](./player-experience-commands-and-communication.md) | Partial: directional LOOK and movement primitives exist, but the WMS `ListRoomOccupants` handler and target-only `character_location`/`npc_location` location and occupancy persistence are absent. Live `room_instance` topology and the Game Session room binding are not the World-owned location authority, and the final LOOK identity is not yet the causal floor plus opaque World/Entity component versions; served-through proofs remain separate participant validation evidence. DROP/PICKUP also lack the target World `TargetingFactSnapshot` location/version validation in the Entity-local commit. [ADR 0054](../../architecture/decisions/adr-0054-split-spatial-authority-with-causal-read-composition.md) remains applied; implementation and proof gaps remain. Accepted full-grid topology decision now defines density-independent movement semantics and opaque scalable representation; large-grid identity, chunk/root finalization, base-plus-delta recovery, and movement-policy proof remain incomplete. | | `GR-2.3` Ambient, environmental, and scheduled world state | `partial` | `audited` | [World API contracts](../../architecture/microservices/world-management-service/api-contracts.md); [World runtime and data](../../architecture/microservices/world-management-service/runtime-and-data.md); [spatial and ambient effects](../../architecture/system-architecture-spatial-and-ambient-effects-catalog.md); [world creation workflow](../../architecture/microservices/world-management-service/world-creation-workflow.md) | [WorldEventServiceImpl.java](../../../services/world-management-service/src/main/java/net/firedevops/firemud/worldmanagement/service/impl/WorldEventServiceImpl.java); [WorldManagementGrpcService.java](../../../services/world-management-service/src/main/java/net/firedevops/firemud/worldmanagement/service/impl/WorldManagementGrpcService.java); [RoomSnapshotDto.java](../../../services/world-management-service/src/main/java/net/firedevops/firemud/worldmanagement/dto/RoomSnapshotDto.java); [V3 world events](../../../services/world-management-service/src/main/resources/db/migration/V3__world_events.sql); [V16 runtime event scope](../../../services/world-management-service/src/main/resources/db/migration/V16__runtime_world_event_scope.sql) | [WorldEventServiceImplTest.java](../../../services/world-management-service/src/test/java/unit/net/firedevops/firemud/worldmanagement/service/impl/WorldEventServiceImplTest.java); [RoomSnapshotDtoTest.java](../../../services/world-management-service/src/test/java/unit/net/firedevops/firemud/worldmanagement/dto/RoomSnapshotDtoTest.java); [WorldManagementGrpcServiceTest.java](../../../services/world-management-service/src/test/java/unit/net/firedevops/firemud/worldmanagement/service/impl/WorldManagementGrpcServiceTest.java) | [authoring](./game-authoring-publishing-and-activation.md); [automation](./automation-and-scheduler-runtime.md); [Game Session runtime](./game-session-runtime-and-tick-coordination.md); [gameplay](./gameplay-rules-entities-and-effects.md) | Partial: scheduled non-Weather event processing and ambient snapshot shape exist, but `ApplyRoomAmbientStatePatch` has no Java handler, durable effect-idempotency and general ambient patches are absent, and the creation workflow does not schedule initial events. Live `WorldEventService` rejects new `WEATHER_CHANGE` scheduling and leaves retained Weather rows unprocessed; the unresolved selector/fenced effect contract still blocks safe ambient mutation, so current code is not proof of the target World-owned fenced ambient-mutation contract. [ADR 0054](../../architecture/decisions/adr-0054-split-spatial-authority-with-causal-read-composition.md) remains the target owner; its World-side handler, durable replay guard, and focused proof remain unimplemented. | diff --git a/services/world-management-service/src/main/java/net/firedevops/firemud/worldmanagement/entity/WorldInstance.java b/services/world-management-service/src/main/java/net/firedevops/firemud/worldmanagement/entity/WorldInstance.java index 1fc649ee8e..afe59f7b0f 100644 --- a/services/world-management-service/src/main/java/net/firedevops/firemud/worldmanagement/entity/WorldInstance.java +++ b/services/world-management-service/src/main/java/net/firedevops/firemud/worldmanagement/entity/WorldInstance.java @@ -26,7 +26,7 @@ public class WorldInstance { private Instant terminatedAt; private Instant createdAt = Instant.now(); private Instant updatedAt = Instant.now(); - private Long rowVersion; + private Long rowVersion = 0L; void touchUpdatedAt() { updatedAt = Instant.now(); diff --git a/services/world-management-service/src/test/java/integration/net/firedevops/firemud/worldmanagement/InitialAdmissionBindHoldPostgresIntegrationTest.java b/services/world-management-service/src/test/java/integration/net/firedevops/firemud/worldmanagement/InitialAdmissionBindHoldPostgresIntegrationTest.java index 64ff40f373..e726827acf 100644 --- a/services/world-management-service/src/test/java/integration/net/firedevops/firemud/worldmanagement/InitialAdmissionBindHoldPostgresIntegrationTest.java +++ b/services/world-management-service/src/test/java/integration/net/firedevops/firemud/worldmanagement/InitialAdmissionBindHoldPostgresIntegrationTest.java @@ -19,6 +19,7 @@ import net.firedevops.firemud.worldmanagement.client.EntityManagementClient; 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.dto.InitialAdmissionBindHoldRequest; import net.firedevops.firemud.worldmanagement.jooq.tables.WorldInstance; import net.firedevops.firemud.worldmanagement.jooq.tables.records.WorldInstanceRecord; @@ -71,6 +72,7 @@ static void configure(DynamicPropertyRegistry registry) { @Autowired private PlatformTransactionManager transactionManager; @MockitoBean private GrpcServerLifecycle grpcServerLifecycle; + @MockitoBean private GrpcGameSessionInitialAdmissionBindProofClient bindProofClient; @MockitoBean private GameDesignClient gameDesignClient; @MockitoBean private GameSessionClient gameSessionClient; @MockitoBean private EntityManagementClient entityManagementClient; diff --git a/services/world-management-service/src/test/java/integration/net/firedevops/firemud/worldmanagement/RoomRepositoryPostgresIntegrationTest.java b/services/world-management-service/src/test/java/integration/net/firedevops/firemud/worldmanagement/RoomRepositoryPostgresIntegrationTest.java index 552e786667..2418d459fa 100644 --- a/services/world-management-service/src/test/java/integration/net/firedevops/firemud/worldmanagement/RoomRepositoryPostgresIntegrationTest.java +++ b/services/world-management-service/src/test/java/integration/net/firedevops/firemud/worldmanagement/RoomRepositoryPostgresIntegrationTest.java @@ -7,6 +7,7 @@ import net.firedevops.firemud.worldmanagement.client.EntityManagementClient; 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.entity.Region; import net.firedevops.firemud.worldmanagement.entity.Room; import net.firedevops.firemud.worldmanagement.entity.Zone; @@ -55,6 +56,7 @@ static void configure(DynamicPropertyRegistry registry) { @Autowired private DSLContext dsl; @MockitoBean private GrpcServerLifecycle grpcServerLifecycle; + @MockitoBean private GrpcGameSessionInitialAdmissionBindProofClient bindProofClient; @MockitoBean private EntityManagementClient entityManagementClient; @MockitoBean private GameDesignClient gameDesignClient; @MockitoBean private GameSessionClient gameSessionClient; diff --git a/services/world-management-service/src/test/java/integration/net/firedevops/firemud/worldmanagement/WorldManagementServiceApplicationIntegrationTest.java b/services/world-management-service/src/test/java/integration/net/firedevops/firemud/worldmanagement/WorldManagementServiceApplicationIntegrationTest.java index e7a08471f7..d7bade0c99 100644 --- a/services/world-management-service/src/test/java/integration/net/firedevops/firemud/worldmanagement/WorldManagementServiceApplicationIntegrationTest.java +++ b/services/world-management-service/src/test/java/integration/net/firedevops/firemud/worldmanagement/WorldManagementServiceApplicationIntegrationTest.java @@ -23,6 +23,7 @@ import net.firedevops.firemud.worldmanagement.client.EntityManagementClient; 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.entity.WorldEvent; import net.firedevops.firemud.worldmanagement.repository.WorldEventRepository; import org.jooq.DSLContext; @@ -74,6 +75,7 @@ static void configure(DynamicPropertyRegistry registry) { @Autowired private PlatformTransactionManager transactionManager; @MockitoBean private GrpcServerLifecycle grpcServerLifecycle; + @MockitoBean private GrpcGameSessionInitialAdmissionBindProofClient bindProofClient; @MockitoBean private GameDesignClient gameDesignClient; @MockitoBean private GameSessionClient gameSessionClient; @MockitoBean private EntityManagementClient entityManagementClient; diff --git a/services/world-management-service/src/test/java/unit/net/firedevops/firemud/worldmanagement/service/impl/WorldLifecycleCommandServiceImplTest.java b/services/world-management-service/src/test/java/unit/net/firedevops/firemud/worldmanagement/service/impl/WorldLifecycleCommandServiceImplTest.java index b360b2394c..af786ab78c 100644 --- a/services/world-management-service/src/test/java/unit/net/firedevops/firemud/worldmanagement/service/impl/WorldLifecycleCommandServiceImplTest.java +++ b/services/world-management-service/src/test/java/unit/net/firedevops/firemud/worldmanagement/service/impl/WorldLifecycleCommandServiceImplTest.java @@ -210,6 +210,7 @@ void prepareWorldInstanceMaterializesSeededRoomIdentityAndActivatesOwnerLifecycl assertEquals(42L, storedInstance.get().getTenantId()); assertEquals(101L, storedInstance.get().getGameInstanceId()); assertEquals(11L, storedInstance.get().getVersionId()); + assertEquals(0L, storedInstance.get().getRowVersion()); verify(regionInstanceRepository).save(any()); verify(zoneInstanceRepository).save(any()); ArgumentCaptor roomCaptor = ArgumentCaptor.forClass(RoomInstance.class); From 0716746657fb46ac6c8c3411ef21ac13552ceb3f Mon Sep 17 00:00:00 2001 From: Ben Hook <5009589+benhook1013@users.noreply.github.com> Date: Sat, 3 Oct 2026 05:18:21 +1300 Subject: [PATCH 16/20] fix(world): bind lifecycle hold SQL parameters correctly --- .../repository/WorldInstanceRepository.java | 12 ++++++++---- 1 file changed, 8 insertions(+), 4 deletions(-) diff --git a/services/world-management-service/src/main/java/net/firedevops/firemud/worldmanagement/repository/WorldInstanceRepository.java b/services/world-management-service/src/main/java/net/firedevops/firemud/worldmanagement/repository/WorldInstanceRepository.java index eff9e600e8..235ec3abe2 100644 --- a/services/world-management-service/src/main/java/net/firedevops/firemud/worldmanagement/repository/WorldInstanceRepository.java +++ b/services/world-management-service/src/main/java/net/firedevops/firemud/worldmanagement/repository/WorldInstanceRepository.java @@ -45,14 +45,18 @@ public Optional findByTenantIdAndGameInstanceIdForUpdate( } public boolean hasNonterminalInitialAdmissionBindHold(Long tenantId, Long gameInstanceId) { - return Boolean.TRUE.equals( - dsl.fetchValue( + Record result = + dsl.fetchOne( "SELECT EXISTS (SELECT 1 FROM initial_admission_bind_hold " + "WHERE tenant_id = ? AND game_instance_id = ? " + "AND status IN ('PENDING', 'RECONCILIATION_REQUIRED'))", - Boolean.class, tenantId, - gameInstanceId)); + gameInstanceId); + if (result == null) { + throw new IllegalStateException( + "INITIAL_ADMISSION_BIND_HOLD_LOOKUP_FAILED: lifecycle hold lookup returned no row"); + } + return Boolean.TRUE.equals(result.get(0, Boolean.class)); } public Optional findById(Long id) { From 580c7c766d60870740b8a8c49997e181f87605ea Mon Sep 17 00:00:00 2001 From: Ben Hook <5009589+benhook1013@users.noreply.github.com> Date: Sat, 3 Oct 2026 05:07:20 +1300 Subject: [PATCH 17/20] test(gameplay): bind TCP fixtures through durable pointer ownership --- .../MutableDefaultDemoCatalogTest.java | 28 +- .../support/TestGameplayWorldCatalogs.java | 55 +- .../test/stubs/WorldManagementStubServer.java | 148 ++++ .../GameplayCrossServiceStack.java | 634 +++++++++++++++++- 4 files changed, 783 insertions(+), 82 deletions(-) diff --git a/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/support/MutableDefaultDemoCatalogTest.java b/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/support/MutableDefaultDemoCatalogTest.java index d7dce9e9b2..39e395baa0 100644 --- a/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/support/MutableDefaultDemoCatalogTest.java +++ b/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/support/MutableDefaultDemoCatalogTest.java @@ -20,14 +20,15 @@ class MutableDefaultDemoCatalogTest { private static final long BASELINE_GAME_INSTANCE_ID = 73L; @Test - void defaultDemoIsAbsentUntilTheTestBaselineIsEnabled() { + void defaultDemoIsAbsentUntilPersistedPointerAuthorityContainsIt() { MutablePointerAuthority authority = new MutablePointerAuthority(); TestGameplayWorldCatalogs.MutableDefaultDemoCatalog fixture = fixture(authority); GameplayWorldCatalog catalog = fixture.catalog(); assertThat(catalog.resolveWorld("demo")).isEmpty(); - fixture.useDefaultDemo(TENANT_ID, BASELINE_GAME_INSTANCE_ID); + authority.setPointers( + List.of(pointer("demo", "production", TENANT_ID, BASELINE_GAME_INSTANCE_ID, 1L, 1L))); GameplayWorldCatalog.RealmView realm = catalog.resolveDefaultRealm(catalog.resolveWorld("demo").orElseThrow()).orElseThrow(); @@ -41,10 +42,9 @@ void defaultDemoIsAbsentUntilTheTestBaselineIsEnabled() { } @Test - void persistedMatchingPointerTakesPrecedenceOverTheBaselineFallback() { + void persistedPointerIsTheOnlySourceForTheDefaultDemoRoute() { MutablePointerAuthority authority = new MutablePointerAuthority(); TestGameplayWorldCatalogs.MutableDefaultDemoCatalog fixture = fixture(authority); - fixture.useDefaultDemo(TENANT_ID, BASELINE_GAME_INSTANCE_ID); authority.setPointers(List.of(pointer("demo", "production", TENANT_ID, 99L, 8L, 12L))); GameplayWorldCatalog.RealmView realm = @@ -59,10 +59,9 @@ void persistedMatchingPointerTakesPrecedenceOverTheBaselineFallback() { } @Test - void selectorForAnotherTenantAlsoOccupiesTheDefaultFallbackSelector() { + void selectorForAnotherTenantIsNotReplacedByASyntheticDefaultRoute() { MutablePointerAuthority authority = new MutablePointerAuthority(); TestGameplayWorldCatalogs.MutableDefaultDemoCatalog fixture = fixture(authority); - fixture.useDefaultDemo(TENANT_ID, BASELINE_GAME_INSTANCE_ID); authority.setPointers(List.of(pointer("demo", "production", TENANT_ID + 1L, 99L, 8L, 12L))); GameplayWorldCatalog catalog = fixture.catalog(); @@ -74,22 +73,17 @@ void selectorForAnotherTenantAlsoOccupiesTheDefaultFallbackSelector() { } @Test - void clearingTheFallbackRestoresMissingAuthority() { + void missingPersistedAuthorityRemainsMissing() { MutablePointerAuthority authority = new MutablePointerAuthority(); TestGameplayWorldCatalogs.MutableDefaultDemoCatalog fixture = fixture(authority); - fixture.useDefaultDemo(TENANT_ID, BASELINE_GAME_INSTANCE_ID); - assertThat(fixture.catalog().resolveWorld("demo")).isPresent(); - - fixture.clearDefaultDemo(); assertThat(fixture.catalog().resolveWorld("demo")).isEmpty(); } @Test - void incompletePersistedPointerIsNotReplacedByTheFallback() { + void incompletePersistedPointerFailsClosed() { MutablePointerAuthority authority = new MutablePointerAuthority(); TestGameplayWorldCatalogs.MutableDefaultDemoCatalog fixture = fixture(authority); - fixture.useDefaultDemo(TENANT_ID, BASELINE_GAME_INSTANCE_ID); authority.setPointers( List.of( new GameplayAdmissionPointerSnapshot( @@ -113,11 +107,13 @@ void incompletePersistedPointerIsNotReplacedByTheFallback() { } @Test - void ambiguousPersistedPublicAuthorityIsNotHiddenByTheFallback() { + void ambiguousPersistedPublicAuthorityFailsClosed() { MutablePointerAuthority authority = new MutablePointerAuthority(); TestGameplayWorldCatalogs.MutableDefaultDemoCatalog fixture = fixture(authority); - fixture.useDefaultDemo(TENANT_ID, BASELINE_GAME_INSTANCE_ID); - authority.setPointers(List.of(pointer("other", "production", TENANT_ID, 99L, 8L, 12L))); + authority.setPointers( + List.of( + pointer("demo", "production", TENANT_ID, 99L, 8L, 12L), + pointer("other", "production", TENANT_ID, 100L, 1L, 3L))); assertThatThrownBy(() -> fixture.catalog().resolveWorld("demo")) .isInstanceOf(IllegalArgumentException.class) diff --git a/services/game-session-service/src/testFixtures/java/net/firedevops/firemud/gamesession/support/TestGameplayWorldCatalogs.java b/services/game-session-service/src/testFixtures/java/net/firedevops/firemud/gamesession/support/TestGameplayWorldCatalogs.java index 39ff3de318..b8b5033eaf 100644 --- a/services/game-session-service/src/testFixtures/java/net/firedevops/firemud/gamesession/support/TestGameplayWorldCatalogs.java +++ b/services/game-session-service/src/testFixtures/java/net/firedevops/firemud/gamesession/support/TestGameplayWorldCatalogs.java @@ -10,7 +10,6 @@ import java.util.Objects; import java.util.Set; import java.util.UUID; -import java.util.concurrent.atomic.AtomicReference; import net.firedevops.firemud.common.gameplay.GameplayCatalogProperties; import net.firedevops.firemud.gamesession.command.text.GameplayWorldCatalog; import net.firedevops.firemud.gamesession.service.GameplayAdmissionPointerAuthorityService; @@ -24,14 +23,9 @@ public static GameplayWorldCatalog fromProperties(GameplayCatalogProperties prop return GameplayWorldCatalog.forWorldSupplier(() -> toWorldViews(properties.getWorlds())); } - /** - * Test-only catalog seam for cross-service transport fixtures that need a healthy demo route - * without claiming that a World-owned initial admission bind occurred. - */ + /** Test-only catalog projection backed by the same durable pointer authority as production. */ public static final class MutableDefaultDemoCatalog { private final GameplayAdmissionPointerAuthorityService pointerAuthority; - private final AtomicReference defaultDemo = - new AtomicReference<>(); public MutableDefaultDemoCatalog(GameplayAdmissionPointerAuthorityService pointerAuthority) { this.pointerAuthority = @@ -42,47 +36,8 @@ public GameplayWorldCatalog catalog() { return GameplayWorldCatalog.forWorldSupplier(this::worlds); } - public void useDefaultDemo(long tenantId, long gameInstanceId) { - if (tenantId <= 0 || gameInstanceId <= 0) { - throw new IllegalArgumentException( - "test demo tenant and game instance IDs must be positive"); - } - defaultDemo.set( - new GameplayAdmissionPointerSnapshot( - "demo", - "Demo World", - "production", - "Live Realm", - tenantId, - gameInstanceId, - 1L, - true, - true, - false, - "SHARED", - "ALLOW_NEW", - 1L, - stableId("realm", tenantId, "demo", "production"), - stableId("namespace", tenantId, "demo", "production"))); - } - - public void clearDefaultDemo() { - defaultDemo.set(null); - } - private List worlds() { - List pointers = - new ArrayList<>(pointerAuthority.listPointers()); - GameplayAdmissionPointerSnapshot fallback = defaultDemo.get(); - if (fallback != null - && pointers.stream() - .noneMatch( - pointer -> - pointer.worldSlug().equals(fallback.worldSlug()) - && pointer.realmSlug().equals(fallback.realmSlug()))) { - pointers.add(fallback); - } - return fromPointers(pointers); + return fromPointers(pointerAuthority.listPointers()); } } @@ -184,12 +139,6 @@ private static GameplayWorldCatalog.RealmView toRealmView( pointer.playableStateNamespaceId()); } - private static UUID stableId(String kind, long tenantId, String worldSlug, String realmSlug) { - return UUID.nameUUIDFromBytes( - ("firemud-test-catalog:" + kind + ":" + tenantId + ":" + worldSlug + ":" + realmSlug) - .getBytes(java.nio.charset.StandardCharsets.UTF_8)); - } - private static List toWorldViews( List worlds) { if (worlds == null) { diff --git a/services/game-session-service/src/testFixtures/java/net/firedevops/firemud/gamesession/test/stubs/WorldManagementStubServer.java b/services/game-session-service/src/testFixtures/java/net/firedevops/firemud/gamesession/test/stubs/WorldManagementStubServer.java index 019411e2d2..fa27a663de 100644 --- a/services/game-session-service/src/testFixtures/java/net/firedevops/firemud/gamesession/test/stubs/WorldManagementStubServer.java +++ b/services/game-session-service/src/testFixtures/java/net/firedevops/firemud/gamesession/test/stubs/WorldManagementStubServer.java @@ -6,23 +6,49 @@ import io.grpc.StatusRuntimeException; import io.grpc.stub.StreamObserver; import java.io.IOException; +import java.util.HashMap; +import java.util.Map; +import java.util.UUID; import java.util.concurrent.atomic.AtomicReference; +import java.util.regex.Pattern; +import net.firedevops.firemud.entitymanagement.v1.PlayableStateScope; import net.firedevops.firemud.gamesession.test.LookTestFixtures; +import net.firedevops.firemud.worldmanagement.v1.AcquireInitialAdmissionBindHoldRequest; +import net.firedevops.firemud.worldmanagement.v1.AcquireInitialAdmissionBindHoldResponse; import net.firedevops.firemud.worldmanagement.v1.GetRoomSnapshotRequest; import net.firedevops.firemud.worldmanagement.v1.GetRoomSnapshotResponse; +import net.firedevops.firemud.worldmanagement.v1.InitialAdmissionBindHold; +import net.firedevops.firemud.worldmanagement.v1.InitialAdmissionBindHoldStatus; import net.firedevops.firemud.worldmanagement.v1.RoomSnapshot; import net.firedevops.firemud.worldmanagement.v1.WorldManagementServiceGrpc; public final class WorldManagementStubServer implements AutoCloseable { + private static final Pattern SHA_256 = Pattern.compile("[0-9a-f]{64}"); + private final Server server; private final int port; private final AtomicReference nextFailure = new AtomicReference<>(); + private final Map admissionBindRequests = + new HashMap<>(); + private final Map admissionBindHolds = new HashMap<>(); public WorldManagementStubServer(int port) throws IOException { this.server = ServerBuilder.forPort(port) .addService( new WorldManagementServiceGrpc.WorldManagementServiceImplBase() { + @Override + public void acquireInitialAdmissionBindHold( + AcquireInitialAdmissionBindHoldRequest request, + StreamObserver responseObserver) { + try { + responseObserver.onNext(issueInitialAdmissionBindHold(request)); + responseObserver.onCompleted(); + } catch (StatusRuntimeException failure) { + responseObserver.onError(failure); + } + } + @Override public void getRoomSnapshot( GetRoomSnapshotRequest request, @@ -60,6 +86,128 @@ public void getRoomSnapshot( this.port = server.getPort(); } + /** Issues an exact, idempotent hold response for this test World owner stub. */ + private synchronized AcquireInitialAdmissionBindHoldResponse issueInitialAdmissionBindHold( + AcquireInitialAdmissionBindHoldRequest request) { + validateInitialAdmissionBindRequest(request); + String key = request.getTenantId() + ":" + request.getInitialAdmissionRequestId(); + AcquireInitialAdmissionBindHoldRequest existingRequest = admissionBindRequests.get(key); + if (existingRequest != null && !existingRequest.equals(request)) { + throw Status.ALREADY_EXISTS + .withDescription("initial admission request identity was reused with a different tuple") + .asRuntimeException(); + } + InitialAdmissionBindHold hold = admissionBindHolds.get(key); + if (hold == null) { + hold = + InitialAdmissionBindHold.newBuilder() + .setHoldId(UUID.randomUUID().toString()) + .setHoldFence(UUID.randomUUID().toString()) + .setTenantId(request.getTenantId()) + .setRealmUuid(request.getRealmUuid()) + .setPlayableStateNamespaceUuid(request.getPlayableStateNamespaceUuid()) + .setPlayableStateScope(request.getPlayableStateScope()) + .setGameInstanceId(request.getGameInstanceId()) + .setVersionId(request.getVersionId()) + .setActiveLifecycleEpoch(request.getExpectedActiveLifecycleEpoch()) + .setInitialAdmissionRequestId(request.getInitialAdmissionRequestId()) + .setRequestDigest(request.getRequestDigest()) + .setExpectedNoPriorPointer(request.getExpectedNoPriorPointer()) + .setExpectedCatalogRevision(request.getExpectedCatalogRevision()) + .setStatus(InitialAdmissionBindHoldStatus.INITIAL_ADMISSION_BIND_HOLD_STATUS_PENDING) + .build(); + admissionBindRequests.put(key, request); + admissionBindHolds.put(key, hold); + } + return AcquireInitialAdmissionBindHoldResponse.newBuilder().setHold(hold).build(); + } + + public synchronized void resetInitialAdmissionBindHold( + long tenantId, + String requestId, + String requestDigest, + String gameInstanceId, + String versionId, + long activeLifecycleEpoch, + String holdId, + String holdFence) { + String key = tenantId + ":" + requestId; + AcquireInitialAdmissionBindHoldRequest request = admissionBindRequests.get(key); + InitialAdmissionBindHold hold = admissionBindHolds.get(key); + if (request == null || hold == null) { + if (request == null && hold == null) { + return; + } + throw new IllegalStateException( + "test World stub has incomplete initial admission hold state"); + } + if (!Long.toString(tenantId).equals(request.getTenantId()) + || !requestId.equals(request.getInitialAdmissionRequestId()) + || !request.getTenantId().equals(hold.getTenantId()) + || !request.getRealmUuid().equals(hold.getRealmUuid()) + || !request.getPlayableStateNamespaceUuid().equals(hold.getPlayableStateNamespaceUuid()) + || request.getPlayableStateScope() != hold.getPlayableStateScope() + || !request.getGameInstanceId().equals(hold.getGameInstanceId()) + || !request.getVersionId().equals(hold.getVersionId()) + || request.getExpectedActiveLifecycleEpoch() != hold.getActiveLifecycleEpoch() + || !request.getInitialAdmissionRequestId().equals(hold.getInitialAdmissionRequestId()) + || !request.getRequestDigest().equals(hold.getRequestDigest()) + || request.getExpectedNoPriorPointer() != hold.getExpectedNoPriorPointer() + || request.getExpectedCatalogRevision() != hold.getExpectedCatalogRevision() + || hold.getStatus() + != InitialAdmissionBindHoldStatus.INITIAL_ADMISSION_BIND_HOLD_STATUS_PENDING + || (requestDigest != null && !requestDigest.equals(request.getRequestDigest())) + || (gameInstanceId != null && !gameInstanceId.equals(request.getGameInstanceId())) + || (versionId != null && !versionId.equals(request.getVersionId())) + || (activeLifecycleEpoch > 0L + && activeLifecycleEpoch != request.getExpectedActiveLifecycleEpoch()) + || (holdId != null && !holdId.equals(hold.getHoldId())) + || (holdFence != null && !holdFence.equals(hold.getHoldFence()))) { + throw new IllegalStateException("test World stub hold does not match the owned reset tuple"); + } + admissionBindRequests.remove(key); + admissionBindHolds.remove(key); + } + + private static void validateInitialAdmissionBindRequest( + AcquireInitialAdmissionBindHoldRequest request) { + if (request.getTenantId().isBlank() + || request.getGameInstanceId().isBlank() + || request.getVersionId().isBlank() + || request.getInitialAdmissionRequestId().isBlank() + || request.getInitialAdmissionRequestId().length() > 128 + || !SHA_256.matcher(request.getRequestDigest()).matches() + || !isCanonicalUuid(request.getRealmUuid()) + || !isCanonicalUuid(request.getPlayableStateNamespaceUuid()) + || request.getPlayableStateScope() != PlayableStateScope.PLAYABLE_STATE_SCOPE_SHARED + || !request.getExpectedNoPriorPointer() + || request.getExpectedCatalogRevision() <= 0L + || request.getExpectedActiveLifecycleEpoch() <= 0L + || !isPositiveLong(request.getTenantId()) + || !isPositiveLong(request.getGameInstanceId()) + || !isPositiveLong(request.getVersionId())) { + throw Status.INVALID_ARGUMENT + .withDescription("initial admission hold tuple is incomplete or unsupported") + .asRuntimeException(); + } + } + + private static boolean isPositiveLong(String value) { + try { + return Long.parseLong(value) > 0L && Long.toString(Long.parseLong(value)).equals(value); + } catch (NumberFormatException exception) { + return false; + } + } + + private static boolean isCanonicalUuid(String value) { + try { + return UUID.fromString(value).toString().equals(value); + } catch (IllegalArgumentException exception) { + return false; + } + } + public void triggerNotFound(String description) { nextFailure.set(Status.NOT_FOUND.withDescription(description).asRuntimeException()); } 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 e85974177e..0ff9fc897c 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 @@ -1,19 +1,36 @@ package net.firedevops.firemud.gamesession.testsupport; import edu.umd.cs.findbugs.annotations.SuppressFBWarnings; +import io.grpc.ManagedChannel; +import io.grpc.ManagedChannelBuilder; import java.io.IOException; +import java.nio.charset.StandardCharsets; +import java.security.MessageDigest; +import java.security.NoSuchAlgorithmException; import java.time.Instant; +import java.util.HexFormat; import java.util.LinkedHashMap; +import java.util.List; import java.util.Map; import java.util.Objects; +import java.util.UUID; +import java.util.concurrent.TimeUnit; import javax.sql.DataSource; import net.firedevops.firemud.cache.ScreenBufferService; +import net.firedevops.firemud.entitymanagement.v1.PlayableStateScope; import net.firedevops.firemud.gamesession.CrossServiceAppHarness; +import net.firedevops.firemud.gamesession.entity.InitialAdmissionBindCatalog; import net.firedevops.firemud.gamesession.entity.RuntimeRegionStatus; import net.firedevops.firemud.gamesession.repository.RuntimeRegionStatusRepository; +import net.firedevops.firemud.gamesession.service.GameplayAdmissionPointerAuthorityService; +import net.firedevops.firemud.gamesession.service.GameplayAdmissionPointerSnapshot; +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.InitialAdmissionBindOwnerService; +import net.firedevops.firemud.gamesession.service.InitialAdmissionBindRequest; import net.firedevops.firemud.gamesession.service.SessionContext; import net.firedevops.firemud.gamesession.service.SessionContextService; -import net.firedevops.firemud.gamesession.support.TestGameplayWorldCatalogs; import net.firedevops.firemud.gamesession.test.GameInstanceTestFixtures; import net.firedevops.firemud.gamesession.test.LookTestFixtures; import net.firedevops.firemud.gamesession.test.stubs.EntityManagementStubServer; @@ -22,8 +39,14 @@ import net.firedevops.firemud.gamesession.test.stubs.WorldManagementStubServer; import net.firedevops.firemud.socialgroups.v1.ListFriendPresenceResponse; import net.firedevops.firemud.test.AccountRuntimeStubServer; +import net.firedevops.firemud.worldmanagement.v1.AcquireInitialAdmissionBindHoldRequest; +import net.firedevops.firemud.worldmanagement.v1.AcquireInitialAdmissionBindHoldResponse; +import net.firedevops.firemud.worldmanagement.v1.InitialAdmissionBindHold; +import net.firedevops.firemud.worldmanagement.v1.WorldManagementServiceGrpc; import org.springframework.data.redis.core.StringRedisTemplate; import org.springframework.jdbc.core.JdbcTemplate; +import org.springframework.transaction.PlatformTransactionManager; +import org.springframework.transaction.support.TransactionTemplate; import org.testcontainers.containers.GenericContainer; import org.testcontainers.containers.PostgreSQLContainer; @@ -42,7 +65,7 @@ public final class GameplayCrossServiceStack implements AutoCloseable { private final ListFriendPresenceResponse baselineFriendPresenceResponse; private CrossServiceAppHarness.GameLogicHolder gameLogic; private final CrossServiceAppHarness.GameSessionHolder gameSession; - private final TestGameplayWorldCatalogs.MutableDefaultDemoCatalog defaultDemoCatalogFixture; + private final boolean useDefaultDemoCatalogFixture; private GameplayCrossServiceStack( AccountRuntimeStubServer accountStub, @@ -54,7 +77,7 @@ private GameplayCrossServiceStack( ListFriendPresenceResponse baselineFriendPresenceResponse, CrossServiceAppHarness.GameLogicHolder gameLogic, CrossServiceAppHarness.GameSessionHolder gameSession, - TestGameplayWorldCatalogs.MutableDefaultDemoCatalog defaultDemoCatalogFixture) { + boolean useDefaultDemoCatalogFixture) { this.accountStub = accountStub; this.gameDesignStub = gameDesignStub; this.worldStub = worldStub; @@ -64,7 +87,7 @@ private GameplayCrossServiceStack( this.baselineFriendPresenceResponse = baselineFriendPresenceResponse; this.gameLogic = gameLogic; this.gameSession = gameSession; - this.defaultDemoCatalogFixture = defaultDemoCatalogFixture; + this.useDefaultDemoCatalogFixture = useDefaultDemoCatalogFixture; } public static Builder builder() { @@ -184,6 +207,9 @@ public long freshGameplayBaseline( clearRedis(); JdbcTemplate jdbc = jdbc(); clearSyntheticAdmissionPointerState(jdbc); + if (useDefaultDemoCatalogFixture) { + clearDefaultDemoAdmissionBinding(jdbc, tenantId); + } jdbc.execute("TRUNCATE TABLE runtime_region_status RESTART IDENTITY"); jdbc.execute("TRUNCATE TABLE game_instances RESTART IDENTITY"); if (characterIds.length > 0) { @@ -193,19 +219,603 @@ public long freshGameplayBaseline( GameInstanceTestFixtures.insertRunningGameInstance( jdbc, tenantId, ownerAccountId, gameTemplateId); seedRuntimeOwnership(tenantId, gameInstanceId); - if (defaultDemoCatalogFixture != null) { - defaultDemoCatalogFixture.useDefaultDemo(tenantId, gameInstanceId); + if (useDefaultDemoCatalogFixture) { + bindDefaultDemoPointer(tenantId, gameInstanceId, ownerAccountId, gameTemplateId); } return gameInstanceId; } - /** Removes only the test catalog fallback; persisted pointer authority remains untouched. */ - public void clearDefaultDemoCatalogFixture() { - if (defaultDemoCatalogFixture != null) { - defaultDemoCatalogFixture.clearDefaultDemo(); + private void clearDefaultDemoAdmissionBinding(JdbcTemplate jdbc, long tenantId) { + String requestId = defaultDemoRequestId(tenantId); + TransactionTemplate transaction = + new TransactionTemplate(gameSession.bean(PlatformTransactionManager.class)); + DefaultDemoBindReset reset = + transaction.execute(status -> clearDefaultDemoAdmissionBinding(jdbc, tenantId, requestId)); + worldStub.resetInitialAdmissionBindHold( + tenantId, + requestId, + reset == null ? null : reset.requestDigest(), + reset == null ? null : Long.toString(reset.gameInstanceId()), + reset == null ? null : Long.toString(reset.versionId()), + reset == null ? 0L : reset.activeLifecycleEpoch(), + reset == null || reset.holdId() == null ? null : reset.holdId().toString(), + reset == null || reset.holdFence() == null ? null : reset.holdFence().toString()); + } + + private static DefaultDemoBindReset clearDefaultDemoAdmissionBinding( + JdbcTemplate jdbc, long tenantId, String requestId) { + List attempts = + jdbc.query( + """ + SELECT a.attempt_id, a.realm_id, a.playable_state_namespace_id, a.catalog_revision, + a.game_instance_id, a.version_id, a.active_lifecycle_epoch, a.request_digest, + a.playable_state_scope, a.expected_no_prior_pointer, + a.hold_id, a.hold_fence, a.status, a.pointer_id, a.audit_event_id, + c.realm_id AS catalog_realm_id, + c.playable_state_namespace_id AS catalog_namespace_id, + c.game_template_id AS catalog_game_template_id, + c.catalog_revision AS owner_catalog_revision, + c.world_slug AS catalog_world_slug, + c.world_display_name AS catalog_world_display_name, + c.realm_slug AS catalog_realm_slug, + c.realm_display_name AS catalog_realm_display_name, + c.visible AS catalog_visible, + c.public_production_realm AS catalog_public_production_realm, + c.requires_character_selection AS catalog_requires_character_selection, + c.state_scope AS catalog_state_scope, + c.character_creation_policy AS catalog_character_creation_policy + FROM gameplay_initial_admission_bind_attempt a + LEFT JOIN gameplay_initial_admission_bind_catalog c + ON c.tenant_id = a.tenant_id AND c.realm_id = a.realm_id + WHERE a.tenant_id = ? AND a.initial_admission_request_id = ? + """, + (row, rowNumber) -> + new DefaultDemoBindReset( + row.getObject("attempt_id", UUID.class), + row.getObject("realm_id", UUID.class), + row.getObject("playable_state_namespace_id", UUID.class), + row.getLong("catalog_revision"), + row.getLong("game_instance_id"), + row.getLong("version_id"), + row.getLong("active_lifecycle_epoch"), + row.getString("request_digest"), + row.getString("playable_state_scope"), + row.getBoolean("expected_no_prior_pointer"), + row.getObject("hold_id", UUID.class), + row.getObject("hold_fence", UUID.class), + row.getString("status"), + row.getObject("pointer_id", Long.class), + row.getObject("audit_event_id", Long.class), + row.getObject("catalog_realm_id", UUID.class), + row.getObject("catalog_namespace_id", UUID.class), + row.getLong("catalog_game_template_id"), + row.getObject("owner_catalog_revision", Long.class), + row.getString("catalog_world_slug"), + row.getString("catalog_world_display_name"), + row.getString("catalog_realm_slug"), + row.getString("catalog_realm_display_name"), + row.getBoolean("catalog_visible"), + row.getBoolean("catalog_public_production_realm"), + row.getBoolean("catalog_requires_character_selection"), + row.getString("catalog_state_scope"), + row.getString("catalog_character_creation_policy")), + tenantId, + requestId); + if (attempts.isEmpty()) { + if (countRows( + jdbc, + "SELECT count(*) FROM gameplay_admission_pointer " + + "WHERE tenant_id = ? AND world_slug = 'demo' AND realm_slug = 'production'", + tenantId) + != 0 + || countRows( + jdbc, + "SELECT count(*) FROM gameplay_admission_pointer_event " + + "WHERE tenant_id = ? AND world_slug = 'demo' AND realm_slug = 'production'", + tenantId) + != 0) { + throw new IllegalStateException( + "default demo authority exists without the fixture-owned initial bind attempt"); + } + return null; + } + if (attempts.size() != 1) { + throw new IllegalStateException("test default demo reset found duplicate owner attempts"); + } + DefaultDemoBindReset attempt = attempts.getFirst(); + requireOwnedDefaultDemoState(attempt); + + if (countRows( + jdbc, + "SELECT count(*) FROM gameplay_initial_admission_bind_attempt " + + "WHERE tenant_id = ? AND realm_id = ?", + tenantId, + attempt.realmId()) + != 1) { + throw new IllegalStateException( + "test default demo catalog has other initial bind attempts and cannot be reset"); + } + int pointerCount = + countRows( + jdbc, + "SELECT count(*) FROM gameplay_admission_pointer " + + "WHERE tenant_id = ? AND world_slug = 'demo' AND realm_slug = 'production'", + tenantId); + int auditCount = + countRows( + jdbc, + "SELECT count(*) FROM gameplay_admission_pointer_event " + + "WHERE tenant_id = ? AND world_slug = 'demo' AND realm_slug = 'production'", + tenantId); + if (pointerCount != (attempt.pointerId() == null ? 0 : 1) + || auditCount != (attempt.auditEventId() == null ? 0 : 1) + || !hasExactOwnedPointer(jdbc, tenantId, attempt) + || !hasExactOwnedAudit(jdbc, tenantId, requestId, attempt)) { + throw new IllegalStateException( + "test default demo reset found pointer or audit evidence outside its owner attempt"); + } + + if (jdbc.update( + "DELETE FROM gameplay_initial_admission_bind_attempt " + + "WHERE tenant_id = ? AND attempt_id = ? AND initial_admission_request_id = ? " + + "AND request_digest = ? AND realm_id = ? " + + "AND playable_state_namespace_id = ? AND playable_state_scope = 'SHARED' " + + "AND expected_no_prior_pointer AND catalog_revision = ? " + + "AND game_instance_id = ? AND version_id = ? AND active_lifecycle_epoch = ? " + + "AND hold_id IS NOT DISTINCT FROM ? AND hold_fence IS NOT DISTINCT FROM ? " + + "AND status = ? AND pointer_id IS NOT DISTINCT FROM ? " + + "AND audit_event_id IS NOT DISTINCT FROM ?", + tenantId, + attempt.attemptId(), + requestId, + attempt.requestDigest(), + attempt.realmId(), + attempt.playableStateNamespaceId(), + attempt.catalogRevision(), + attempt.gameInstanceId(), + attempt.versionId(), + attempt.activeLifecycleEpoch(), + attempt.holdId(), + attempt.holdFence(), + attempt.status(), + attempt.pointerId(), + attempt.auditEventId()) + != 1) { + throw new IllegalStateException("test default demo owner attempt changed during reset"); + } + if (attempt.auditEventId() != null + && jdbc.update( + "DELETE FROM gameplay_admission_pointer_event " + + "WHERE id = ? AND tenant_id = ? AND world_slug = 'demo' " + + "AND world_display_name = 'Demo World' AND realm_slug = 'production' " + + "AND realm_display_name = 'Live Realm' AND game_instance_id = ? " + + "AND pointer_version = 1 AND catalog_revision = ? " + + "AND realm_id = ? AND playable_state_namespace_id = ? " + + "AND visible AND public_production_realm " + + "AND NOT requires_character_selection AND state_scope = 'SHARED' " + + "AND character_creation_policy = 'ALLOW_NEW' " + + "AND control_plane_request_id = ? " + + "AND actor_principal = 'game-session-initial-admission-bind' " + + "AND reason = 'initial admission pointer bind'", + attempt.auditEventId(), + tenantId, + attempt.gameInstanceId(), + attempt.catalogRevision(), + attempt.realmId(), + attempt.playableStateNamespaceId(), + requestId) + != 1) { + throw new IllegalStateException("test default demo audit changed during reset"); + } + if (attempt.pointerId() != null + && jdbc.update( + "DELETE FROM gameplay_admission_pointer " + + "WHERE id = ? AND tenant_id = ? AND world_slug = 'demo' " + + "AND world_display_name = 'Demo World' AND realm_slug = 'production' " + + "AND realm_display_name = 'Live Realm' AND game_instance_id = ? " + + "AND pointer_version = 1 AND catalog_revision = ? " + + "AND realm_id = ? AND playable_state_namespace_id = ? " + + "AND visible AND public_production_realm " + + "AND NOT requires_character_selection AND state_scope = 'SHARED' " + + "AND character_creation_policy = 'ALLOW_NEW' " + + "AND last_updated_by = 'game-session-initial-admission-bind' " + + "AND last_update_reason = 'initial admission pointer bind'", + attempt.pointerId(), + tenantId, + attempt.gameInstanceId(), + attempt.catalogRevision(), + attempt.realmId(), + attempt.playableStateNamespaceId()) + != 1) { + throw new IllegalStateException("test default demo pointer changed during reset"); + } + if (jdbc.update( + "DELETE FROM gameplay_initial_admission_bind_catalog " + + "WHERE tenant_id = ? AND realm_id = ? AND world_slug = 'demo' " + + "AND game_template_id = ? AND world_display_name = 'Demo World' " + + "AND realm_slug = 'production' AND realm_display_name = 'Live Realm' " + + "AND catalog_revision = ? AND playable_state_namespace_id = ? " + + "AND visible AND public_production_realm " + + "AND NOT requires_character_selection AND state_scope = 'SHARED' " + + "AND character_creation_policy = 'ALLOW_NEW'", + tenantId, + attempt.realmId(), + attempt.catalogGameTemplateId(), + attempt.catalogRevision(), + attempt.playableStateNamespaceId()) + != 1) { + throw new IllegalStateException("test default demo owner catalog changed during reset"); + } + return attempt; + } + + private static void requireOwnedDefaultDemoState(DefaultDemoBindReset attempt) { + if (attempt.attemptId() == null + || attempt.realmId() == null + || attempt.playableStateNamespaceId() == null + || attempt.catalogRevision() <= 0L + || attempt.gameInstanceId() <= 0L + || attempt.versionId() <= 0L + || attempt.activeLifecycleEpoch() <= 0L + || (attempt.holdId() == null) != (attempt.holdFence() == null) + || attempt.catalogRealmId() == null + || !attempt.realmId().equals(attempt.catalogRealmId()) + || !attempt.playableStateNamespaceId().equals(attempt.catalogNamespaceId()) + || attempt.catalogGameTemplateId() <= 0L + || attempt.ownerCatalogRevision() == null + || attempt.catalogRevision() != attempt.ownerCatalogRevision() + || !"SHARED".equals(attempt.playableStateScope()) + || !attempt.expectedNoPriorPointer() + || !"demo".equals(attempt.catalogWorldSlug()) + || !"Demo World".equals(attempt.catalogWorldDisplayName()) + || !"production".equals(attempt.catalogRealmSlug()) + || !"Live Realm".equals(attempt.catalogRealmDisplayName()) + || !attempt.catalogVisible() + || !attempt.catalogPublicProductionRealm() + || attempt.catalogRequiresCharacterSelection() + || !"SHARED".equals(attempt.catalogStateScope()) + || !"ALLOW_NEW".equals(attempt.catalogCharacterCreationPolicy()) + || !("PENDING".equals(attempt.status()) + || "COMMITTED".equals(attempt.status()) + || "ABORTED".equals(attempt.status())) + || (attempt.pointerId() == null) != (attempt.auditEventId() == null) + || ("COMMITTED".equals(attempt.status()) != (attempt.pointerId() != null))) { + throw new IllegalStateException("test default demo reset found mismatched owner state"); + } + } + + private static boolean hasExactOwnedPointer( + JdbcTemplate jdbc, long tenantId, DefaultDemoBindReset attempt) { + if (attempt.pointerId() == null) { + return true; + } + return countRows( + jdbc, + "SELECT count(*) FROM gameplay_admission_pointer " + + "WHERE id = ? AND tenant_id = ? AND world_slug = 'demo' " + + "AND world_display_name = 'Demo World' AND realm_slug = 'production' " + + "AND realm_display_name = 'Live Realm' AND game_instance_id = ? " + + "AND pointer_version = 1 AND catalog_revision = ? " + + "AND realm_id = ? AND playable_state_namespace_id = ? " + + "AND visible AND public_production_realm AND NOT requires_character_selection " + + "AND state_scope = 'SHARED' AND character_creation_policy = 'ALLOW_NEW' " + + "AND last_updated_by = 'game-session-initial-admission-bind' " + + "AND last_update_reason = 'initial admission pointer bind'", + attempt.pointerId(), + tenantId, + attempt.gameInstanceId(), + attempt.catalogRevision(), + attempt.realmId(), + attempt.playableStateNamespaceId()) + == 1; + } + + private static boolean hasExactOwnedAudit( + JdbcTemplate jdbc, long tenantId, String requestId, DefaultDemoBindReset attempt) { + if (attempt.auditEventId() == null) { + return true; } + return countRows( + jdbc, + "SELECT count(*) FROM gameplay_admission_pointer_event " + + "WHERE id = ? AND tenant_id = ? AND world_slug = 'demo' " + + "AND realm_slug = 'production' AND game_instance_id = ? " + + "AND pointer_version = 1 AND catalog_revision = ? " + + "AND realm_id = ? AND playable_state_namespace_id = ? " + + "AND control_plane_request_id = ? " + + "AND actor_principal = 'game-session-initial-admission-bind' " + + "AND reason = 'initial admission pointer bind' " + + "AND visible AND public_production_realm AND NOT requires_character_selection " + + "AND state_scope = 'SHARED' AND character_creation_policy = 'ALLOW_NEW'", + attempt.auditEventId(), + tenantId, + attempt.gameInstanceId(), + attempt.catalogRevision(), + attempt.realmId(), + attempt.playableStateNamespaceId(), + requestId) + == 1; } + private static int countRows(JdbcTemplate jdbc, String sql, Object... parameters) { + Integer count = jdbc.queryForObject(sql, Integer.class, parameters); + return count == null ? 0 : count; + } + + private static String defaultDemoRequestId(long tenantId) { + return "cross-service-default-demo-" + tenantId; + } + + private void bindDefaultDemoPointer( + long tenantId, long gameInstanceId, long ownerAccountId, long gameTemplateId) { + InitialAdmissionBindOwnerService owner = + gameSession.bean(InitialAdmissionBindOwnerService.class); + GameplayAdmissionPointerAuthorityService pointerAuthority = + gameSession.bean(GameplayAdmissionPointerAuthorityService.class); + InitialAdmissionBindCatalogDescriptor descriptor = + new InitialAdmissionBindCatalogDescriptor( + tenantId, gameTemplateId, "demo", "Demo World", "production", "Live Realm", false); + InitialAdmissionBindCatalog catalog = owner.registerPublicSharedFixtureCatalog(descriptor); + long versionId = + Objects.requireNonNull( + jdbc() + .queryForObject( + "SELECT version_id FROM game_instances WHERE tenant_id = ? AND id = ?", + Long.class, + tenantId, + gameInstanceId), + "test target versionId must exist"); + long activeLifecycleEpoch = 1L; + String requestId = "cross-service-default-demo-" + tenantId; + String requestDigest = + defaultDemoRequestDigest( + requestId, + tenantId, + gameTemplateId, + ownerAccountId, + catalog, + gameInstanceId, + versionId, + activeLifecycleEpoch); + InitialAdmissionBindRequest request = + new InitialAdmissionBindRequest( + tenantId, + descriptor.worldSlug(), + descriptor.realmSlug(), + requestId, + requestDigest, + gameInstanceId, + versionId, + activeLifecycleEpoch); + owner.beginIntent(request); + + AcquireInitialAdmissionBindHoldRequest holdRequest = + AcquireInitialAdmissionBindHoldRequest.newBuilder() + .setTenantId(Long.toString(tenantId)) + .setGameInstanceId(Long.toString(gameInstanceId)) + .setVersionId(Long.toString(versionId)) + .setExpectedActiveLifecycleEpoch(activeLifecycleEpoch) + .setInitialAdmissionRequestId(requestId) + .setRequestDigest(requestDigest) + .setRealmUuid(catalog.realmId().toString()) + .setPlayableStateNamespaceUuid(catalog.playableStateNamespaceId().toString()) + .setPlayableStateScope(PlayableStateScope.PLAYABLE_STATE_SCOPE_SHARED) + .setExpectedNoPriorPointer(true) + .setExpectedCatalogRevision(catalog.catalogRevision()) + .build(); + AcquireInitialAdmissionBindHoldResponse holdResponse = + acquireInitialAdmissionBindHold(holdRequest); + if (!holdResponse.hasHold()) { + throw new IllegalStateException( + "test World stub did not return the requested initial admission hold"); + } + InitialAdmissionBindHold hold = holdResponse.getHold(); + InitialAdmissionBindHoldBinding binding = + requireDefaultDemoHold( + hold, request, catalog, tenantId, gameInstanceId, versionId, activeLifecycleEpoch); + owner.attachHold(binding); + InitialAdmissionBindOwnerProof proof = owner.commit(binding); + requireDefaultDemoProof(proof, binding); + verifyDefaultDemoPointer(pointerAuthority, catalog, request, gameInstanceId); + } + + private AcquireInitialAdmissionBindHoldResponse acquireInitialAdmissionBindHold( + AcquireInitialAdmissionBindHoldRequest request) { + ManagedChannel channel = + ManagedChannelBuilder.forTarget(worldStub.endpoint()).usePlaintext().build(); + try { + return WorldManagementServiceGrpc.newBlockingStub(channel) + .withDeadlineAfter(3L, TimeUnit.SECONDS) + .acquireInitialAdmissionBindHold(request); + } finally { + channel.shutdownNow(); + } + } + + private static InitialAdmissionBindHoldBinding requireDefaultDemoHold( + InitialAdmissionBindHold hold, + InitialAdmissionBindRequest request, + InitialAdmissionBindCatalog catalog, + long tenantId, + long gameInstanceId, + long versionId, + long activeLifecycleEpoch) { + if (!isCanonicalUuid(hold.getHoldId()) + || !isCanonicalUuid(hold.getHoldFence()) + || !Long.toString(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()) { + throw new IllegalStateException( + "test World stub returned a mismatched initial admission hold"); + } + return new InitialAdmissionBindHoldBinding( + hold.getHoldId(), + hold.getHoldFence(), + tenantId, + hold.getRealmUuid(), + hold.getPlayableStateNamespaceUuid(), + "SHARED", + gameInstanceId, + versionId, + activeLifecycleEpoch, + request.initialAdmissionRequestId(), + request.requestDigest(), + true, + catalog.catalogRevision()); + } + + private static void requireDefaultDemoProof( + InitialAdmissionBindOwnerProof proof, InitialAdmissionBindHoldBinding binding) { + if (proof == null + || proof.outcome() != InitialAdmissionBindOwnerProof.Outcome.COMMITTED + || !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() + || !binding.initialAdmissionRequestId().equals(proof.initialAdmissionRequestId()) + || !binding.requestDigest().equals(proof.requestDigest()) + || proof.expectedNoPriorPointer() != binding.expectedNoPriorPointer() + || proof.expectedCatalogRevision() != binding.expectedCatalogRevision() + || !binding.requestDigest().equals(proof.pointerAuditRequestDigest()) + || proof.pointerVersion() != 1L + || !isPositiveLong(proof.pointerAuditId())) { + throw new IllegalStateException("test owner did not prove the exact committed initial bind"); + } + } + + private static void verifyDefaultDemoPointer( + GameplayAdmissionPointerAuthorityService pointerAuthority, + InitialAdmissionBindCatalog catalog, + InitialAdmissionBindRequest request, + long gameInstanceId) { + GameplayAdmissionPointerSnapshot pointer = + pointerAuthority + .findPointer(request.tenantId(), request.worldSlug(), request.realmSlug()) + .orElseThrow( + () -> new IllegalStateException("test initial bind did not persist its pointer")); + if (pointer.gameInstanceId() != gameInstanceId + || pointer.pointerVersion() != 1L + || pointer.catalogRevision() != catalog.catalogRevision() + || !catalog.realmId().equals(pointer.realmId()) + || !catalog.playableStateNamespaceId().equals(pointer.playableStateNamespaceId()) + || !pointer.visible() + || !pointer.publicProductionRealm() + || !"SHARED".equals(pointer.stateScope())) { + throw new IllegalStateException("test default demo pointer does not match its owner catalog"); + } + } + + private static String defaultDemoRequestDigest( + String operationId, + long tenantId, + long gameTemplateId, + long ownerAccountId, + InitialAdmissionBindCatalog catalog, + long gameInstanceId, + long versionId, + long activeLifecycleEpoch) { + StringBuilder canonical = new StringBuilder(); + appendDigestField(canonical, "domain", "firemud.run-owned-initial-admission-bind.v1"); + appendDigestField(canonical, "operationId", operationId); + appendDigestField(canonical, "tenantId", Long.toString(tenantId)); + appendDigestField(canonical, "gameTemplateId", Long.toString(gameTemplateId)); + appendDigestField(canonical, "ownerAccountId", Long.toString(ownerAccountId)); + appendDigestField(canonical, "worldSlug", "demo"); + appendDigestField(canonical, "worldDisplayName", "Demo World"); + appendDigestField(canonical, "realmSlug", "production"); + appendDigestField(canonical, "realmDisplayName", "Live Realm"); + appendDigestField(canonical, "requiresCharacterSelection", "false"); + appendDigestField(canonical, "realmId", catalog.realmId().toString()); + appendDigestField( + canonical, "playableStateNamespaceId", catalog.playableStateNamespaceId().toString()); + appendDigestField(canonical, "playableStateScope", "SHARED"); + 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) { + canonical + .append(name.getBytes(StandardCharsets.UTF_8).length) + .append(':') + .append(name) + .append(value.getBytes(StandardCharsets.UTF_8).length) + .append(':') + .append(value); + } + + private static boolean isCanonicalUuid(String value) { + try { + return UUID.fromString(value).toString().equals(value); + } catch (IllegalArgumentException exception) { + return false; + } + } + + private static boolean isPositiveLong(String value) { + try { + return Long.parseLong(value) > 0L; + } catch (NumberFormatException exception) { + return false; + } + } + + private record DefaultDemoBindReset( + UUID attemptId, + UUID realmId, + UUID playableStateNamespaceId, + long catalogRevision, + long gameInstanceId, + long versionId, + long activeLifecycleEpoch, + String requestDigest, + String playableStateScope, + boolean expectedNoPriorPointer, + UUID holdId, + UUID holdFence, + String status, + Long pointerId, + Long auditEventId, + UUID catalogRealmId, + UUID catalogNamespaceId, + long catalogGameTemplateId, + Long ownerCatalogRevision, + String catalogWorldSlug, + String catalogWorldDisplayName, + String catalogRealmSlug, + String catalogRealmDisplayName, + boolean catalogVisible, + boolean catalogPublicProductionRealm, + boolean catalogRequiresCharacterSelection, + String catalogStateScope, + String catalogCharacterCreationPolicy) {} + private void clearSyntheticAdmissionPointerState(JdbcTemplate jdbc) { // Audit rows are removed first so this remains safe if a future schema adds an FK to the // current pointer row. The world prefix is reserved for this fixture; keep canonical demo and @@ -510,9 +1120,7 @@ public GameplayCrossServiceStack start() throws IOException { initialFriendPresenceResponse, gameLogic, gameSession, - useDefaultDemoCatalogFixture - ? gameSession.bean(TestGameplayWorldCatalogs.MutableDefaultDemoCatalog.class) - : null); + useDefaultDemoCatalogFixture); } private void requireConfigured() { From d80c32aa37ecc84b708527a4a2485ea464a05632 Mon Sep 17 00:00:00 2001 From: Ben Hook <5009589+benhook1013@users.noreply.github.com> Date: Sat, 3 Oct 2026 08:58:16 +1300 Subject: [PATCH 18/20] refactor(review): preserve controller corrections in a separate stacked boundary --- design/developer-workflows/pr-lifecycle.md | 2 +- dev-tools/pr_review/README.md | 2 - dev-tools/pr_review/cli.py | 7 - dev-tools/pr_review/controller.py | 47 +--- dev-tools/pr_review/hosted.py | 260 +----------------- dev-tools/pr_review/runtime.py | 16 +- .../pr_review/sqlite_provider_imports.py | 2 - .../validation/test_pr_review_cli_runner.py | 23 -- .../validation/test_pr_review_controller.py | 224 --------------- .../test_pr_review_evidence_hosted.py | 199 -------------- .../test_pr_review_sqlite_provider_imports.py | 27 +- 11 files changed, 20 insertions(+), 789 deletions(-) diff --git a/design/developer-workflows/pr-lifecycle.md b/design/developer-workflows/pr-lifecycle.md index 22b3009ac6..726f860a62 100644 --- a/design/developer-workflows/pr-lifecycle.md +++ b/design/developer-workflows/pr-lifecycle.md @@ -19,7 +19,7 @@ Use this guide for pull-request status, review handling, CI, Renovate, merging, - If that exact legacy transition is followed by a fresh review and a later coherent fix head, reauthorize only the same immutable fingerprints with `dev-tools/pr-review decide transition --reauthorize --pr --head --reason ""`. The controller requires a prior transition, verifies every carried record again, and requires every other observation to be normal completed attributable anchored evidence; newer evidence remains counting and subject to ordinary reconciliation and judgment. A changed head without this explicit reauthorization remains blocked, and the command never creates a checkpoint or consumes review quota. - A single previously audited Hosted fingerprint that is absent from the complete current history may be retired only with `--reauthorize --retire-missing-hosted-fingerprint `. This requires the exact prior fingerprint, coherent current topology, complete available Hosted trigger records and paginated GitHub review/comment history, terminal and uniquely attributable responses, no active or unresolved reservation, and no unresolved actionable findings; any missing or ambiguous proof remains held. The fingerprint stays in the transition audit and remains non-counting if it later reappears. This decision never reconstructs evidence or creates a checkpoint and does not grant review, taper, finding-count, or merge-readiness credit. - Record an explicit channel judgment with `dev-tools/pr-review decide judgment retain|reopen --pr --channel hosted|cli --head --checkpoint --reason ""`. Retain confirms the verified equivalent patch for request and queue safety; reopen explicitly requires fresh review without deleting historical completed taper and resets the taper streak at the bound checkpoint. For CLI, a reopen may bind the latest complete modern checkpoint to a proven descendant live head, but carries no new review credit until later completed results arrive. A narrow channel policy override uses `dev-tools/pr-review decide policy --pr --head --checkpoint --hosted-zero-useful --reason ""` or `--cli-zero-useful ` (exactly one channel); it sets that channel's zero-useful completion count for the exact checkpoint. -- Extend the existing allocation with `dev-tools/pr-review decide allocation grant --pr --channel hosted|cli --head [--checkpoint ] [--min-additional-completed ] [--max-additional-completed ] [--exact-additional-completed ] [--fresh-taper] --reason ""`. Both bounds count completed, attributable results for that PR and channel beginning at the decision; the optional checkpoint records the observed identity but does not move that count's start. With neither bound, the existing one-result promise remains (`min=1`, `max=1`). A minimum-only allocation has no maximum; a maximum-only allocation has no extra minimum (`min=0`). `--exact-additional-completed N` is mutually exclusive with the separate bounds and `--fresh-taper`, and records `min=max=N`, so ordinary taper cannot stop discovery before all `N` results and the cap stops discovery immediately afterward. It preserves the existing taper rather than starting a fresh streak. Use `allocation renew --exact-additional-completed N` to replace an existing allocation or audited human stop explicitly. A verifiable request already admitted at the exact-allocation decision remains in flight and counts only when it completes attributably; ambiguous or unsupported active evidence is refused. Without `--fresh-taper`, an allocation after completed taper affects queue eligibility and its additional-result count while preserving the existing historical taper display. Its zero-useful results continue the normal streak. An accepted allocated result resets the active streak at that result, while all earlier checkpoints remain visible with their original counts; after fixes, later zero-useful results can satisfy taper. `--fresh-taper` starts the active streak at the allocation decision immediately; earlier dry results remain visible historical evidence but cannot satisfy it. When both bounds are set, reject `min > max`; the minimum requires that many additional results even after fresh taper, while taper may stop earlier than the maximum once the minimum is met. Rate limits, connection failures, duplicates, partial or ambiguous responses, provisional captures, and other non-counting observations do not consume the count. Hosted and CLI allocations remain independent; request-time identity checks apply only when posting a new review. +- Extend the existing allocation with `dev-tools/pr-review decide allocation grant --pr --channel hosted|cli --head [--checkpoint ] [--min-additional-completed ] [--max-additional-completed ] [--fresh-taper] --reason ""`. Both bounds count completed, attributable results for that PR and channel beginning at the decision; the optional checkpoint records the observed identity but does not move that count's start. With neither bound, the existing one-result promise remains (`min=1`, `max=1`). A minimum-only allocation has no maximum; a maximum-only allocation has no extra minimum (`min=0`). Without `--fresh-taper`, an allocation after completed taper affects queue eligibility and its additional-result count while preserving the existing historical taper display. Its zero-useful results continue the normal streak. An accepted allocated result resets the active streak at that result, while all earlier checkpoints remain visible with their original counts; after fixes, later zero-useful results can satisfy taper. `--fresh-taper` starts the active streak at the allocation decision immediately; earlier dry results remain visible historical evidence but cannot satisfy it. When both bounds are set, reject `min > max`; the minimum requires that many additional results even after fresh taper, while taper may stop earlier than the maximum once the minimum is met. Rate limits, connection failures, duplicates, partial or ambiguous responses, provisional captures, and other non-counting observations do not consume the count. Hosted and CLI allocations remain independent; request-time identity checks apply only when posting a new review. - Normal taper can finish before a maximum once the minimum is met. After any additional result with accepted findings, no next request is allowed until those findings, current/outdated threads, actionable summary findings, and fix publication/validation obligations are clear, even if capacity remains. Once the maximum is used, no further request is allowed for that PR/channel; a maximum stop is not taper and does not waive accepted findings or fixes. `status` and `evidence` expose the minimum, maximum, completed count, baseline identity, in-flight results, taper state, and controlling reason. When the maximum is exhausted, the controller derives an audited human-cap stop and advances that channel through its normal selector without a separate `decide stop`, subject to the active-review safety described below. Pending obligations remain source-owned and visible as `cap exhausted; findings pending`; this stop is not taper, current-head review, CI/Smoke proof, or merge readiness. A bounded allocation can be replaced explicitly with `allocation renew` and new bounds; `allocation cancel` removes it. Ordinary fixes never reset its completed count. - When the Overseer deliberately allocates one further completed review before deciding whether to continue, record it before the review with `dev-tools/pr-review decide allocation grant --pr --channel hosted|cli --head --reason ""`. Completed-result counts belong to the PR and channel and survive later identity changes; rate limits, partial, duplicate, and unattributable results do not consume the allocation. Record a human decision to make no further requests with `dev-tools/pr-review decide stop --pr --channel hosted|cli --reason ""`. This audited PR/channel override bypasses the taper gate only for queue advancement; it is not taper completion or proof of review coverage, and it persists across head and parent changes. It requires no completed checkpoint, clean findings, idle provider, or coherent review topology. An already admitted CLI or Hosted run continues with its reservation, capture, attribution, and eventual findings intact; finishing that run does not clear the override. Stop recording and new-request admission share only the short state mutation boundary, while each provider keeps its execution exclusion. Optional `--head` and `--checkpoint` pins must match the observed identities; unavailable optional Git proof is recorded as absent, never fabricated. Existing ambiguity-retention and over-ceiling acknowledgment options record their specific evidence without granting review credit. Discovery can advance only when the same channel has no active provider run. Accepted fixes, pending captures and adjudication, attributable evidence, current and outdated threads, actionable summaries, required CI, runtime proof, ancestry, and merge safety remain independent obligations. A stop overrides taper only and does not manufacture a reviewed head or merge readiness. - For a channel that still needs review, targeting stops at the first held, unstable, unreconciled, over-ceiling, or judgment-blocked PR; it skips PRs whose channel has completed taper or an audited human stop. The narrow exception is a verified terminal, non-counting Hosted response: keep that PR incomplete and visible, but use the next coherent PR's Hosted window if one exists. Do not post another request on the ambiguous PR or grant it taper or merge credit; revisit its evidence or obtain an audited human stop before its merge handoff. Request-time identity and active-review checks still apply before any new request for an incomplete channel. A file-ceiling rejection requires a coherent topology decision; there is no normal incremental-review fallback. diff --git a/dev-tools/pr_review/README.md b/dev-tools/pr_review/README.md index 3447df5d00..e15fdb9227 100644 --- a/dev-tools/pr_review/README.md +++ b/dev-tools/pr_review/README.md @@ -12,8 +12,6 @@ The output identifies the SQLite schema and writer build. The live shared cutove For a posted Hosted request, `dev-tools/pr-review wait hosted --pr --trigger-id ` watches only that saved trigger. `--poll-seconds` defaults to 30 and `--max-wait-minutes` to 90. It returns JSON and exit status 0 for an attributable completion, 3 for another terminal result, or 4 when the wait expires; it never posts a request, grants review credit, or retires the trigger. The caller must read the result and use `records sync-hosted --pr ` before adjudicating a completed review. A wait expiration leaves the underlying trigger unchanged. -To require exactly a chosen number of further completed attributable results on one channel, use `dev-tools/pr-review decide allocation grant --pr --channel hosted|cli --head --exact-additional-completed --reason ""`. Use `allocation renew` instead of `grant` to replace an existing allocation or human stop explicitly. The command records the existing minimum and maximum as the same positive number; it does not start a fresh taper streak. Earlier completed evidence remains historical, while a verifiable request already admitted at the decision remains in flight and consumes one result only if it later completes attributably. Failures, rate limits, and other non-counting results consume none. Discovery continues until all `N` results complete even if ordinary taper was already satisfied or becomes satisfied early, then closes at the exact cap while accepted findings and fixes remain mandatory obligations. - ### Manual Hosted adoption A human-posted Hosted CodeRabbit request can be incorporated without requesting another review: after the review completes, run `dev-tools/pr-review decide trigger-adopt-manual --pr --trigger-id --head `. This verifies the immutable public command, completed response, and current anchor before writing a private attribution record. A queued PR uses its reconciled stack parent; an off-queue PR uses its actual live base branch after matching the live base and head tips to their remote refs. Off-queue adoption leaves the configured review queue unchanged. The command does not post a GitHub comment, create a result checkpoint, or grant taper by itself; adjudicate findings and post the normal public Hosted checkpoint next. A moved head or ambiguous response is refused. diff --git a/dev-tools/pr_review/cli.py b/dev-tools/pr_review/cli.py index e801cb7eac..d2c828a5ed 100644 --- a/dev-tools/pr_review/cli.py +++ b/dev-tools/pr_review/cli.py @@ -408,12 +408,6 @@ def records_database(command: argparse.ArgumentParser) -> None: metavar="N", help="maximum additional completed attributable results after the decision", ) - allocation.add_argument( - "--exact-additional-completed", - type=_positive_int, - metavar="N", - help="require exactly N additional completed attributable results after the decision", - ) allocation.add_argument( "--fresh-taper", action="store_true", @@ -1668,7 +1662,6 @@ def record(current): checkpoint=args.checkpoint, min_additional_completed=args.min_additional_completed, max_additional_completed=args.max_additional_completed, - exact_additional_completed=args.exact_additional_completed, fresh_taper=args.fresh_taper, ), 0 if args.decide_command == "stop": diff --git a/dev-tools/pr_review/controller.py b/dev-tools/pr_review/controller.py index 1ddfd072de..1faacac900 100644 --- a/dev-tools/pr_review/controller.py +++ b/dev-tools/pr_review/controller.py @@ -5607,7 +5607,6 @@ def decide_allocation( checkpoint: str | None = None, min_additional_completed: int | None = None, max_additional_completed: int | None = None, - exact_additional_completed: int | None = None, fresh_taper: bool = False, ) -> dict[str, Any]: """Grant, replace, or cancel a one-result or bounded review allocation.""" @@ -5624,22 +5623,6 @@ def decide_allocation( raise ControllerError("fresh taper selection must be boolean") if checkpoint is not None and (not isinstance(checkpoint, str) or not checkpoint.strip()): raise ControllerError("allocation baseline checkpoint must be a non-empty immutable identity") - if exact_additional_completed is not None and ( - isinstance(exact_additional_completed, bool) - or not isinstance(exact_additional_completed, int) - or exact_additional_completed <= 0 - ): - raise ControllerError("exact additional completed reviews must be a positive integer") - if exact_additional_completed is not None and ( - min_additional_completed is not None or max_additional_completed is not None - ): - raise ControllerError("exact additional completed reviews cannot be combined with minimum or maximum") - if exact_additional_completed is not None and fresh_taper: - raise ControllerError("exact additional completed reviews preserve the existing taper") - exact_replacement = exact_additional_completed is not None - if exact_replacement: - min_additional_completed = exact_additional_completed - max_additional_completed = exact_additional_completed if min_additional_completed is not None and ( isinstance(min_additional_completed, bool) or not isinstance(min_additional_completed, int) @@ -5723,26 +5706,10 @@ def provable_posted_hosted_request(value: Any) -> bool: and self._hosted_anchor_matches(value, pr, current) ) - def exact_in_flight_request(value: Any) -> bool: - if not exact_replacement or _field(value, "channel") not in (None, selected.value): - return False - if selected == policy.Channel.HOSTED: - return self._hosted_active_response_overlaps_cli( - value, - pr, - item.head, - current, - require_response_identity=True, - ) - return self._active_cli_review_overlaps_hosted(value, pr, current) - - def permitted_in_flight_request(value: Any) -> bool: - return exact_in_flight_request(value) if exact_replacement else provable_posted_hosted_request(value) - stop_evidence_checked = False if ( bounded_replacement - and not any(permitted_in_flight_request(value) for value in history) + and not any(provable_posted_hosted_request(value) for value in history) and ( prior_taper_complete or any( @@ -5782,7 +5749,7 @@ def permitted_in_flight_request(value: Any) -> bool: and target.pr == pr and target.status == policy.ReviewStatus.JUDGMENT_REQUIRED ): - if not fresh_taper and not exact_replacement: + if not fresh_taper: raise ControllerError( "bounded Hosted allocation after a judgment-required taper must explicitly reopen fresh taper" ) @@ -5802,12 +5769,12 @@ def permitted_in_flight_request(value: Any) -> bool: bounded_replacement and target.pr == pr and target.status == policy.ReviewStatus.HELD - and any(permitted_in_flight_request(value) for value in history) + and any(provable_posted_hosted_request(value) for value in history) ): raise elif bounded_replacement: assert previous is not None - if previous.stop_basis is not None and not exact_replacement: + if previous.stop_basis is not None: raise ControllerError("a stopped allocation cannot be renewed") if self._head_repository_problem(item): raise ControllerError(f"PR #{pr} has an unsupported head repository") @@ -5831,12 +5798,10 @@ def permitted_in_flight_request(value: Any) -> bool: _field(value, flag) is True for flag in ("held", "unstable", "rate_limited", "unreconciled", "parent_moved", "over_ceiling") ) and _field(value, "head", "reviewed_head") in (None, "", item.head) - if blocked and not permitted_in_flight_request(value): + if blocked and not provable_posted_hosted_request(value): raise ControllerError("current review evidence is blocked; allocation cannot be promised") baseline = tuple( - _field(value, "checkpoint", "checkpoint_id") - for value in history - if _field(value, "correction") is not True and not exact_in_flight_request(value) + _field(value, "checkpoint", "checkpoint_id") for value in history if _field(value, "correction") is not True ) if any(not isinstance(value, str) or not value for value in baseline): raise ControllerError("existing review evidence lacks a checkpoint identity") diff --git a/dev-tools/pr_review/hosted.py b/dev-tools/pr_review/hosted.py index 1ec845af8c..7dddb638ed 100644 --- a/dev-tools/pr_review/hosted.py +++ b/dev-tools/pr_review/hosted.py @@ -10,7 +10,7 @@ import re import stat import tempfile -from collections.abc import Callable, Mapping +from collections.abc import Callable from dataclasses import dataclass from datetime import datetime, timedelta, timezone from pathlib import Path @@ -1532,236 +1532,6 @@ def _is_finished_action_response(body: str, *, allow_action_wrapper: bool) -> bo ) -_ADDRESSED_COMMIT_ANNOTATION = re.compile( - r"(?:\r?\n){2}✅ Addressed in commits ([0-9a-f]{7,40}) to ([0-9a-f]{7,40})\Z", - re.IGNORECASE, -) - - -def _archived_completed_thread_bodies( - repo: str, - pr_number: int, - head: str, - record: Mapping[str, Any] | None, - current_record_path: str | Path | None, -) -> dict[int, tuple[str, str]]: - """Read immutable prior Hosted thread bodies for exact trigger attribution.""" - - if not isinstance(record, Mapping): - return {} - current_attempt_id = record.get("sqlite_attempt_id") - trigger = record.get("trigger") - trigger_id = trigger.get("id") if isinstance(trigger, Mapping) else None - trigger_at = parse_timestamp(trigger.get("created_at")) if isinstance(trigger, Mapping) else None - if ( - not isinstance(current_attempt_id, str) - or not current_attempt_id - or type(trigger_id) is not int - or trigger_id <= 0 - or trigger_at is None - or not isinstance(record.get("head_sha"), str) - or record["head_sha"].casefold() != head.casefold() - ): - return {} - - selected_record = Path(current_record_path) if current_record_path is not None else default_trigger_record_path( - repo, pr_number - ) - if selected_record.is_symlink(): - return {} - common = _trigger_record_common_for_path(selected_record, repo, pr_number) - if common is None: - return {} - selected_state = state_path(common) - if selected_state.is_symlink() or not selected_state.is_dir(): - return {} - database = sqlite_state_path(selected_state) - try: - database_stat = database.stat(follow_symlinks=False) - except FileNotFoundError: - return {} - if database.is_symlink() or not stat.S_ISREG(database_stat.st_mode): - return {} - - try: - records = SqliteReviewRecords(database) - current_attempt = records.attempt(current_attempt_id) - attempt_history = records.attempt_history(pr_number) - current_history = [item for item in attempt_history if item.get("attempt_id") == current_attempt_id] - current_head = current_attempt.get("candidate_sha") - if ( - current_attempt.get("source_pr") != pr_number - or current_attempt.get("channel") != "hosted" - or not isinstance(current_head, str) - or current_head.casefold() != head.casefold() - or len(current_history) != 1 - or current_history[0].get("trigger_id") != str(trigger_id) - ): - return {} - - candidates: dict[int, list[tuple[str, str]]] = {} - for attempt in attempt_history: - candidate_head = attempt.get("candidate_sha") - started_at = parse_timestamp(attempt.get("started_at")) - finished_at = parse_timestamp(attempt.get("finished_at")) - if ( - attempt.get("channel") != "hosted" - or attempt.get("state") != "completed" - or not isinstance(candidate_head, str) - or not EXACT_SHA.fullmatch(candidate_head) - or started_at is None - or finished_at is None - or finished_at >= trigger_at - ): - continue - attempt_id = attempt.get("attempt_id") - provider_review_id = attempt.get("provider_review_id") - archived_trigger_id = attempt.get("trigger_id") - if ( - not isinstance(attempt_id, str) - or not attempt_id - or not isinstance(provider_review_id, str) - or not provider_review_id.isdecimal() - or not isinstance(archived_trigger_id, str) - or not archived_trigger_id.isdecimal() - ): - continue - artifacts = records.attempt_artifacts(attempt_id) - try: - metadata = json.loads(artifacts.get("metadata", "")) - archived = json.loads(artifacts.get("hosted_comments", "")) - reviews = json.loads(artifacts.get("hosted_review", "")) - except (TypeError, ValueError, json.JSONDecodeError): - continue - observed_at = parse_timestamp(metadata.get("observed_at")) if isinstance(metadata, dict) else None - metadata_repository = metadata.get("repository") if isinstance(metadata, dict) else None - metadata_head = metadata.get("head_sha") if isinstance(metadata, dict) else None - if ( - not isinstance(metadata, dict) - or metadata.get("state") != "completed" - or metadata.get("terminal") is not True - or metadata.get("attributable") is not True - or not isinstance(metadata_repository, str) - or metadata_repository.casefold() != repo.casefold() - or metadata.get("pull_request") != pr_number - or not isinstance(metadata_head, str) - or metadata_head.casefold() != candidate_head.casefold() - or type(metadata.get("trigger_id")) is not int - or str(metadata["trigger_id"]) != archived_trigger_id - or type(metadata.get("response_id")) is not int - or str(metadata["response_id"]) != provider_review_id - or observed_at is None - or observed_at != finished_at - or not isinstance(archived, dict) - or not isinstance(archived.get("comments"), list) - or not isinstance(archived.get("review_threads"), list) - or not isinstance(reviews, list) - ): - continue - - matching_reviews = [ - item - for item in reviews - if isinstance(item, dict) - and immutable_database_id(item) == metadata["response_id"] - and is_coderabbit_login((item.get("author") or {}).get("login")) - and item.get("state") != "DISMISSED" - and isinstance((item.get("commit") or {}).get("oid"), str) - and (item.get("commit") or {}).get("oid").casefold() == candidate_head.casefold() - ] - matching_triggers = [ - item - for item in archived["comments"] - if isinstance(item, dict) and immutable_database_id(item) == int(archived_trigger_id) - ] - if ( - len(matching_reviews) != 1 - or len(matching_triggers) != 1 - or is_coderabbit_login((matching_triggers[0].get("author") or {}).get("login")) - or normalize_command(matching_triggers[0].get("body") or "") != FULL_COMMAND - ): - continue - archived_trigger_at = parse_timestamp(matching_triggers[0].get("createdAt")) - review_submitted_at = parse_timestamp(matching_reviews[0].get("submittedAt")) - if ( - archived_trigger_at is None - or archived_trigger_at > finished_at - or review_submitted_at is None - or review_submitted_at < archived_trigger_at - or review_submitted_at > finished_at - ): - continue - - for thread in archived["review_threads"]: - comments = thread.get("comments") if isinstance(thread, dict) else None - nodes = comments.get("nodes") if isinstance(comments, dict) else None - if not isinstance(nodes, list): - continue - for item in nodes: - if not isinstance(item, dict) or not is_coderabbit_login((item.get("author") or {}).get("login")): - continue - comment_id = immutable_database_id(item) - created_at = item.get("createdAt") - created = parse_timestamp(created_at) - body = item.get("body") - if ( - comment_id is None - or not isinstance(created_at, str) - or created is None - or created < archived_trigger_at - or created > finished_at - or not isinstance(body, str) - ): - continue - candidates.setdefault(comment_id, []).append((created_at, body)) - - result: dict[int, tuple[str, str]] = {} - for comment_id, baselines in candidates.items(): - if len(baselines) == 1: - result[comment_id] = baselines[0] - except Exception: # noqa: BLE001 - unavailable or incompatible archive must remain fail closed - return {} - return result - - -def _addressed_thread_update_matches_archive( - item: dict[str, Any], - head: str, - after: datetime, - before: datetime | None, - archived_bodies: Mapping[int, tuple[str, str]], -) -> bool: - """Accept only the exact known addressed footer appended to an archived finding.""" - - comment_id = immutable_database_id(item) - if comment_id is None: - return False - archived = archived_bodies.get(comment_id) - body = item.get("body") - created_at = item.get("createdAt") - updated = parse_timestamp(item.get("updatedAt")) - created = parse_timestamp(created_at) - if ( - archived is None - or not isinstance(body, str) - or not isinstance(created_at, str) - or created_at != archived[0] - or not isinstance(archived[1], str) - or created is None - or created >= after - or updated is None - or updated <= after - or (before is not None and updated >= before) - ): - return False - annotation = _ADDRESSED_COMMIT_ANNOTATION.search(body) - return ( - annotation is not None - and annotation.group(2).casefold() == head[: len(annotation.group(2))].casefold() - and body[: annotation.start()] == archived[1] - ) - - def _summary_has_explicit_incompleteness(body: str) -> bool: text = _unquoted(body) not_reviewed_counts = [int(match.group(1)) for match in FILE_NOT_REVIEWED_COUNT.finditer(text)] @@ -2045,10 +1815,6 @@ def finished_reply_without_findings( after: datetime, response_id: int | None, before: datetime | None = None, - record: Mapping[str, Any] | None = None, - current_record_path: str | Path | None = None, - repo: str | None = None, - pr_number: int | None = None, ) -> bool: """Accept CodeRabbit's terminal full-review reply when its complete window is empty. @@ -2127,7 +1893,6 @@ def in_window(value: Any) -> bool | None: submitted_in_window = in_window(item.get("submittedAt")) if submitted_in_window is None or submitted_in_window: return False - archived_bodies: dict[int, tuple[str, str]] | None = None for thread in connections["reviewThreads"]: comments = thread.get("comments") nodes = comments.get("nodes") if isinstance(comments, dict) else None @@ -2138,24 +1903,7 @@ def in_window(value: Any) -> bool | None: continue created_in_window = in_window(item.get("createdAt")) updated_in_window = in_window(item.get("updatedAt")) - if created_in_window is None or updated_in_window is None: - return False - if created_in_window or updated_in_window: - if not created_in_window and updated_in_window: - if archived_bodies is None: - archived_bodies = ( - _archived_completed_thread_bodies( - repo, - pr_number, - head, - record, - current_record_path, - ) - if isinstance(repo, str) and type(pr_number) is int and pr_number > 0 - else {} - ) - if _addressed_thread_update_matches_archive(item, head, after, before, archived_bodies): - continue + if created_in_window is None or updated_in_window is None or created_in_window or updated_in_window: return False return True @@ -2335,10 +2083,6 @@ def trigger_state( trigger_dt, immutable_database_id(item), next_dt, - record, - current_record_path, - repo, - pr_number, ): state = ( "ambiguous_retired_predecessor" diff --git a/dev-tools/pr_review/runtime.py b/dev-tools/pr_review/runtime.py index 1f96df1299..74d3cc0c2f 100644 --- a/dev-tools/pr_review/runtime.py +++ b/dev-tools/pr_review/runtime.py @@ -1111,8 +1111,6 @@ def _hosted_zero_reply_proof( checkpoint: evidence.Checkpoint, response_id: int | None, response_duration_seconds: int | None, - repo: str, - pr_number: int, captured_head: str, record: dict[str, Any], payload: dict[str, Any], @@ -1184,14 +1182,7 @@ def _hosted_zero_reply_proof( next_trigger, ) finished_only = hosted.finished_reply_without_findings( - payload, - captured_head, - trigger_at, - response_id, - next_trigger, - record, - repo=repo, - pr_number=pr_number, + payload, captured_head, trigger_at, response_id, next_trigger ) if legacy_summary is None and provider_summary is None and not finished_only: return None @@ -1238,8 +1229,6 @@ def _hosted_trigger_for_checkpoint( checkpoint, state.response_id, state.duration_seconds, - self.repo, - pr, captured_head, record, payload, @@ -1684,9 +1673,6 @@ def _current_hosted_history( observation["anchor"] = dict(anchor) if isinstance(anchor, Mapping) else None observation["trigger_id"] = state.trigger_comment_id observation["response_id"] = state.response_id - observation["state"] = state.state - observation["attributable"] = state.attributed - observation["terminal"] = state.terminal if state.state == "ambiguous" and not operational_only: terminal_observation = self._terminal_ambiguous_hosted_observation(pr, record, state, payload) if terminal_observation is not None: diff --git a/dev-tools/pr_review/sqlite_provider_imports.py b/dev-tools/pr_review/sqlite_provider_imports.py index a9ecbed963..b1c2e34a09 100644 --- a/dev-tools/pr_review/sqlite_provider_imports.py +++ b/dev-tools/pr_review/sqlite_provider_imports.py @@ -433,8 +433,6 @@ def _import_reply_only_hosted_checkpoint( checkpoint, state.response_id, state.duration_seconds, - repo, - pr_number, captured_head, record, hosted_payload, diff --git a/dev-tools/validation/test_pr_review_cli_runner.py b/dev-tools/validation/test_pr_review_cli_runner.py index dd2390bf27..2a1c58e2c2 100644 --- a/dev-tools/validation/test_pr_review_cli_runner.py +++ b/dev-tools/validation/test_pr_review_cli_runner.py @@ -101,29 +101,6 @@ def test_minimum_and_maximum_are_optional_without_a_pinned_checkpoint(self): self.assertIsNone(maximum_only.min_additional_completed) self.assertEqual(maximum_only.max_additional_completed, 3) - def test_exact_additional_completed_accepts_only_a_positive_integer(self): - common = [ - "decide", - "allocation", - "grant", - "--pr", - "2827", - "--channel", - "cli", - "--head", - HEAD, - "--reason", - "three more completed CLI rounds", - "--exact-additional-completed", - ] - - args = _parser().parse_args([*common, "3"]) - - self.assertEqual(args.exact_additional_completed, 3) - for invalid in ("0", "-1", "not-an-integer"): - with self.subTest(invalid=invalid), self.assertRaises(SystemExit): - _parser().parse_args([*common, invalid]) - def test_legacy_cancel_shape_needs_no_cap_replacement(self): args = _parser().parse_args( [ diff --git a/dev-tools/validation/test_pr_review_controller.py b/dev-tools/validation/test_pr_review_controller.py index ed84bc8011..414a305672 100644 --- a/dev-tools/validation/test_pr_review_controller.py +++ b/dev-tools/validation/test_pr_review_controller.py @@ -3404,230 +3404,6 @@ def test_bounded_allocation_can_be_renewed_or_cancelled_explicitly(self): ) self.assertEqual(cancelled["allocations"], []) - def test_exact_allocation_maps_to_equal_bounds_and_replaces_a_stopped_allocation(self): - for channel in ("hosted", "cli"): - with self.subTest(channel=channel): - evidence = {(1, channel): [self.scope_timeline_evidence(channel=channel)]} - controller = self.make({1: pr(1, HEAD_1)}, evidence, heads={"feature-1": HEAD_1}, sqlite=True) - controller.set_stack([1]) - controller.decide_stop(pr=1, channel=channel, reason="human stopped ordinary discovery") - - renewed = controller.decide_allocation( - action="renew", - pr=1, - channel=channel, - head=HEAD_1, - exact_additional_completed=2, - reason="run exactly two more completed rounds", - ) - - self.assertEqual(renewed["allocation"]["min_additional_completed"], 2) - self.assertEqual(renewed["allocation"]["max_additional_completed"], 2) - self.assertIsNone(renewed["allocation"]["stop_basis"]) - self.assertFalse(renewed["allocation"].get("reopens_taper", False)) - - def test_exact_allocation_explicitly_replaces_an_exhausted_allocation(self): - evidence = {(1, "hosted"): [self.allocation_evidence(checkpoint="baseline")]} - controller = self.grant_bounded_allocation(checkpoint="baseline", cap=1, minimum=1, evidence=evidence) - evidence[(1, "hosted")].append(self.allocation_evidence(checkpoint="exhausted-result")) - self.assertEqual(controller.status()["prs"][0]["allocations"]["hosted"]["remaining"], 0) - - renewed = controller.decide_allocation( - action="renew", - pr=1, - channel="hosted", - head=HEAD_1, - exact_additional_completed=2, - reason="replace the exhausted tranche with exactly two more rounds", - ) - - self.assertEqual(renewed["progress"]["completed_count"], 0) - self.assertEqual(renewed["progress"]["remaining"], 2) - - def test_exact_allocation_retains_one_admitted_request_until_it_completes_or_fails(self): - for channel, terminal, same_checkpoint in ( - ("hosted", "completed", False), - ("cli", "completed", True), - ("cli", "failed", True), - ): - with self.subTest(channel=channel, terminal=terminal): - if channel == "hosted": - record = { - "anchor": { - "pr": 1, - "child_head": HEAD_1, - "parent_identity": "develop", - "parent_head": BASE, - "merge_base": BASE, - "patch_id": f"patch-{HEAD_1[:4]}", - } - } - state = SimpleNamespace( - state="active", - head_sha=HEAD_1, - trigger_comment_id=45, - response_id=46, - terminal=False, - attributed=True, - reason=HOSTED_ACTIVE_RESPONSE_REASON, - ) - live_evidence = LiveEvidence("owner/repo", LiveGitHub("owner/repo")) - with ( - patch.object(hosted, "current_trigger_record_paths", return_value=[Path("/trigger.json")]), - patch.object(hosted, "load_trigger_reservation", return_value=record), - patch.object(hosted, "trigger_state", return_value=state), - ): - active = live_evidence._current_hosted_history(1, HEAD_1, {}, set())[0] - else: - active = { - "pr": 1, - "head": HEAD_1, - "child_head": HEAD_1, - "parent_identity": "develop", - "parent_head": BASE, - "merge_base": BASE, - "patch_id": f"patch-{HEAD_1[:4]}", - "checkpoint": "active-cli:run." + "a" * 32, - "active_review": True, - "held": True, - "current_lock_owner": True, - } - evidence = { - (1, channel): [ - self.scope_timeline_evidence(channel=channel), - active, - ] - } - controller = self.make({1: pr(1, HEAD_1)}, evidence, heads={"feature-1": HEAD_1}, sqlite=True) - controller.set_stack([1]) - controller.decide_stop(pr=1, channel=channel, reason="stop while the admitted request finishes") - - renewed = controller.decide_allocation( - action="renew", - pr=1, - channel=channel, - head=HEAD_1, - exact_additional_completed=2, - reason="retain the admitted request and complete exactly two rounds", - ) - self.assertEqual(renewed["progress"]["in_flight"], 1) - self.assertEqual(renewed["progress"]["used"], 0) - - if terminal == "completed": - replacement = self.allocation_evidence( - checkpoint=active["checkpoint"] if same_checkpoint else "completed-after-decision", - channel=channel, - ) - else: - replacement = self.allocation_evidence( - checkpoint=active["checkpoint"] if same_checkpoint else "failed-after-decision", - channel=channel, - completed=False, - attributable=False, - rate_limited=True, - ) - evidence[(1, channel)][1] = replacement - progress = controller.status()["prs"][0]["allocations"][channel] - - self.assertEqual(progress["used"], 1 if terminal == "completed" else 0) - self.assertEqual(progress["remaining"], 1 if terminal == "completed" else 2) - - def test_exact_allocation_rejects_unsupported_active_evidence_without_replacing_stop(self): - cases = { - "wrong-channel": {"channel": "hosted"}, - "wrong-pr": {"pr": 2}, - "moved-anchor": {"parent_head": HEAD_2}, - "ambiguous": {"unstable": True}, - } - for name, changed in cases.items(): - with self.subTest(name=name): - evidence = {(1, "cli"): [self.scope_timeline_evidence(channel="cli")]} - controller = self.make({1: pr(1, HEAD_1)}, evidence, heads={"feature-1": HEAD_1}, sqlite=True) - controller.set_stack([1]) - controller.decide_stop(pr=1, channel="cli", reason="retain the audited stop") - active = { - "pr": 1, - "head": HEAD_1, - "child_head": HEAD_1, - "parent_identity": "develop", - "parent_head": BASE, - "merge_base": BASE, - "patch_id": f"patch-{HEAD_1[:4]}", - "checkpoint": "active-cli:run." + "b" * 32, - "active_review": True, - "held": True, - "current_lock_owner": True, - **changed, - } - evidence[(1, "cli")].append(active) - stopped = controller.store.load() - - with self.assertRaises(ControllerError): - controller.decide_allocation( - action="renew", - pr=1, - channel="cli", - head=HEAD_1, - exact_additional_completed=2, - reason="unsupported active evidence must fail closed", - ) - - self.assertEqual(controller.store.load(), stopped) - - def test_exact_allocation_does_not_stop_at_existing_or_early_taper(self): - for channel, prior_count in (("hosted", 1), ("cli", 3)): - with self.subTest(channel=channel): - history = [ - self.allocation_evidence(checkpoint=f"prior-{index}", channel=channel) - for index in range(prior_count) - ] - history.append(self.scope_timeline_evidence(channel=channel)) - evidence = {(1, channel): history} - controller = self.make({1: pr(1, HEAD_1)}, evidence, heads={"feature-1": HEAD_1}, sqlite=True) - controller.set_stack([1]) - - controller.decide_allocation( - action="grant", - pr=1, - channel=channel, - head=HEAD_1, - exact_additional_completed=2, - reason="complete two rounds after ordinary taper", - ) - history.append(self.allocation_evidence(checkpoint="exact-first", channel=channel)) - first = controller.status()["prs"][0]["allocations"][channel] - self.assertEqual((first["status"], first["used"]), ("CAP_ACTIVE", 1)) - - history.append(self.allocation_evidence(checkpoint="exact-second", channel=channel)) - final = controller.status()["prs"][0]["allocations"][channel] - self.assertIn(final["status"], {"CAP_TAPERED", "CAP_AUDITED_STOP"}) - self.assertEqual((final["used"], final["remaining"]), (2, 0)) - - def test_exact_allocation_rejects_invalid_or_conflicting_values_without_mutation(self): - controller = self.make({1: pr(1, HEAD_1)}, heads={"feature-1": HEAD_1}, sqlite=True) - controller.set_stack([1]) - original = controller.store.load() - - for exact, extra, message in ( - (0, {}, "positive integer"), - (-1, {}, "positive integer"), - (True, {}, "positive integer"), - (2, {"min_additional_completed": 1}, "cannot be combined"), - (2, {"max_additional_completed": 3}, "cannot be combined"), - (2, {"fresh_taper": True}, "preserve the existing taper"), - ): - with self.subTest(exact=exact, extra=extra), self.assertRaisesRegex(ControllerError, message): - controller.decide_allocation( - action="grant", - pr=1, - channel="hosted", - head=HEAD_1, - exact_additional_completed=exact, - reason="invalid exact allocation", - **extra, - ) - self.assertEqual(controller.store.load(), original) - def test_bounded_dry_result_can_be_renewed_without_stop_authorization(self): evidence = {(1, "hosted"): [self.allocation_evidence(checkpoint="baseline", channel="hosted")]} controller = self.grant_bounded_allocation( diff --git a/dev-tools/validation/test_pr_review_evidence_hosted.py b/dev-tools/validation/test_pr_review_evidence_hosted.py index 7b7c91d573..36f5099858 100644 --- a/dev-tools/validation/test_pr_review_evidence_hosted.py +++ b/dev-tools/validation/test_pr_review_evidence_hosted.py @@ -80,145 +80,6 @@ def trigger_record(head: str = HEAD): } -def archived_addressed_reply_fixture(common: Path, *, include_baseline: bool = True): - trigger_at = "2026-09-23T00:02:00Z" - old_trigger_at = "2026-09-23T00:00:50Z" - old_started_at = "2026-09-23T00:00:40Z" - old_finished_at = "2026-09-23T00:01:15Z" - old_body = "An archived CodeRabbit finding.\n\n" - addressed_body = f"{old_body}\n\n✅ Addressed in commits {'c' * 7} to {HEAD[:7]}" - inline = { - "databaseId": 30, - "author": {"login": "coderabbitai[bot]"}, - "body": addressed_body, - "createdAt": "2026-09-23T00:01:10Z", - "updatedAt": "2026-09-23T00:02:15Z", - } - old_review = { - "databaseId": 20, - "author": {"login": "coderabbitai[bot]"}, - "body": "\nReviewing the archived candidate.", - "state": "COMMENTED", - "submittedAt": old_finished_at, - "commit": {"oid": BASE}, - } - old_comments = { - "comments": [ - comment(9, "owner", hosted.FULL_COMMAND, old_trigger_at), - ], - "review_threads": ( - [ - { - "comments": { - "nodes": [ - { - **inline, - "body": old_body, - "createdAt": inline["createdAt"], - "updatedAt": old_finished_at, - } - ] - } - } - ] - if include_baseline - else [] - ), - } - old_metadata = { - "state": "completed", - "terminal": True, - "attributable": True, - "repository": REPO, - "pull_request": PR, - "head_sha": BASE, - "trigger_id": 9, - "response_id": 20, - "observed_at": old_finished_at, - } - - state_dir = common / "firemud" / "pr-review-stack.json" - state_dir.mkdir(parents=True) - database = common / "firemud" / "pr-review-stack.sqlite3" - SqliteStateStore(database).update(lambda state: state) - records = SqliteReviewRecords(database) - records.bootstrap() - records.start_attempt( - attempt_id="old-hosted-attempt", - source_pr=PR, - channel="hosted", - candidate_sha=BASE, - started_at=old_started_at, - ) - records.finish_attempt( - "old-hosted-attempt", - state="completed", - finished_at=old_finished_at, - trigger_id="9", - provider_review_id="20", - artifacts={ - "hosted_review": json.dumps([old_review]), - "hosted_comments": json.dumps(old_comments), - "metadata": json.dumps(old_metadata), - }, - ) - records.start_attempt( - attempt_id="current-hosted-attempt", - source_pr=PR, - channel="hosted", - candidate_sha=HEAD, - started_at="2026-09-23T00:01:50Z", - ) - records.finish_attempt( - "current-hosted-attempt", - state="ambiguous", - finished_at="2026-09-23T00:02:08Z", - trigger_id="10", - provider_review_id="11", - artifacts={ - "hosted_review": "[]", - "hosted_comments": json.dumps({"comments": []}), - "metadata": json.dumps({"state": "ambiguous"}), - }, - ) - - trigger = comment(10, "owner", hosted.FULL_COMMAND, trigger_at) - summary = comment( - 12, - "coderabbitai[bot]", - "No actionable comments were generated in the recent review.\n" - f"Reviewing files that changed from the base of the PR and between {BASE} and {HEAD}.", - "2026-09-23T00:01:40Z", - ) - summary["updatedAt"] = "2026-09-23T00:02:30Z" - response = comment( - 11, - "coderabbitai[bot]", - "\n" - f"\n" - "
\n✅ Action performed\n" - "Full review finished.\n
", - "2026-09-23T00:02:08Z", - ) - response["updatedAt"] = "2026-09-23T00:02:20Z" - payload = review_payload( - [trigger, summary, response], - threads=[{"comments": {"nodes": [inline]}}], - ) - record = trigger_record() - record["sqlite_attempt_id"] = "current-hosted-attempt" - record["trigger"].update( - { - "id": 10, - "created_at": trigger_at, - "url": trigger["url"], - } - ) - record_path = hosted.default_trigger_record_path(REPO, PR, common) - record_path.parent.mkdir(parents=True, exist_ok=True) - return payload, record, record_path - - class GithubAndEvidenceTests(unittest.TestCase): def test_cli_result_exposes_human_duration_without_changing_seconds_or_marker(self): result = ReviewResult( @@ -1888,66 +1749,6 @@ def test_finished_reply_with_empty_complete_history_is_clean_completion(self): with self.assertRaisesRegex(ValueError, "invalid full-review identity"): hosted.trigger_state(REPO, PR, review_payload([trigger, finished]), bool_record) - def test_finished_reply_accepts_only_exact_archived_addressed_thread_updates(self): - with tempfile.TemporaryDirectory() as directory: - payload, record, record_path = archived_addressed_reply_fixture(Path(directory)) - - state = hosted.trigger_state(REPO, PR, payload, record, record_path) - - self.assertEqual(state.state, "completed") - self.assertTrue(state.attributed) - self.assertEqual(state.response_id, 11) - - def test_finished_reply_keeps_unproven_or_changed_thread_output_ambiguous(self): - cases = ( - ("unknown baseline", False, None), - ("modified archived body", True, "modified_body"), - ("addressed range ends on another head", True, "mismatched_range"), - ("new inline comment", True, "new_comment"), - ("positive finding count", True, "positive_count"), - ("incomplete coverage", True, "incomplete_coverage"), - ("mismatched summary head", True, "mismatched_summary_head"), - ) - for label, include_baseline, mutation in cases: - with self.subTest(case=label), tempfile.TemporaryDirectory() as directory: - payload, record, record_path = archived_addressed_reply_fixture( - Path(directory), include_baseline=include_baseline - ) - thread_nodes = payload["data"]["repository"]["pullRequest"]["reviewThreads"]["nodes"][0][ - "comments" - ]["nodes"] - if mutation == "modified_body": - thread_nodes[0]["body"] = thread_nodes[0]["body"].replace( - "An archived CodeRabbit finding.", "A changed CodeRabbit finding." - ) - elif mutation == "mismatched_range": - thread_nodes[0]["body"] = thread_nodes[0]["body"].replace( - f"to {HEAD[:7]}", f"to {BASE[:7]}" - ) - elif mutation == "new_comment": - thread_nodes.append( - { - "databaseId": 31, - "author": {"login": "coderabbitai[bot]"}, - "body": "A new inline finding.", - "createdAt": "2026-09-23T00:02:16Z", - "updatedAt": "2026-09-23T00:02:16Z", - } - ) - elif mutation in {"positive_count", "incomplete_coverage", "mismatched_summary_head"}: - issue_comments = payload["data"]["repository"]["pullRequest"]["comments"]["nodes"] - summary = next(item for item in issue_comments if item["databaseId"] == 12) - if mutation == "positive_count": - summary["body"] += "\n**Actionable comments posted: 1**" - elif mutation == "incomplete_coverage": - summary["body"] += "\nFiles not reviewed: 3." - else: - summary["body"] = summary["body"].replace(HEAD, BASE) - - state = hosted.trigger_state(REPO, PR, payload, record, record_path) - - self.assertEqual(state.state, "ambiguous") - def test_active_acknowledgement_does_not_hide_clean_finished_result(self): trigger = comment(10, "owner", hosted.FULL_COMMAND, "2026-09-23T00:01:00Z") acknowledgement = comment(11, "coderabbitai", "Full review triggered", "2026-09-23T00:01:08Z") diff --git a/dev-tools/validation/test_pr_review_sqlite_provider_imports.py b/dev-tools/validation/test_pr_review_sqlite_provider_imports.py index 01b3c3e287..4d5ae00892 100644 --- a/dev-tools/validation/test_pr_review_sqlite_provider_imports.py +++ b/dev-tools/validation/test_pr_review_sqlite_provider_imports.py @@ -806,24 +806,17 @@ def test_reply_only_zero_checkpoint_requires_exact_edited_trigger_reply(self) -> path.parent.mkdir(parents=True) path.write_text(json.dumps(record), encoding="utf-8") - proof_method = pr_review.runtime.LiveEvidence._hosted_zero_reply_proof - with patch.object( - pr_review.runtime.LiveEvidence, - "_hosted_zero_reply_proof", - wraps=proof_method, - ) as zero_reply_proof: - imported = pr_review.sqlite_provider_imports.import_hosted_checkpoint( - self.records, - repo=REPO, - pr_number=PR, - checkpoint=checkpoint, - actor="reviewer", - common=self.common, - scope="broad", - hosted_payload=payload, - ) + imported = pr_review.sqlite_provider_imports.import_hosted_checkpoint( + self.records, + repo=REPO, + pr_number=PR, + checkpoint=checkpoint, + actor="reviewer", + common=self.common, + scope="broad", + hosted_payload=payload, + ) - self.assertEqual(zero_reply_proof.call_args.args[3:5], (REPO, PR)) self.assertEqual(imported["provider_id"], "trigger:101") self.assertEqual(imported["counts"], {"found": 0, "accepted": 0, "routed": 0}) self.assertEqual(set(imported["archive_artifacts"]), {"hosted_comments", "hosted_review", "metadata"}) From 8eacc5e737e82d314bc64dd1359df9f5d9dec7f2 Mon Sep 17 00:00:00 2001 From: Ben Hook <5009589+benhook1013@users.noreply.github.com> Date: Sat, 3 Oct 2026 09:50:28 +1300 Subject: [PATCH 19/20] Fix typed initial-admission ledger status assertion --- .../InitialAdmissionBindPostgresIntegrationTest.java | 8 ++++---- 1 file changed, 4 insertions(+), 4 deletions(-) diff --git a/services/game-session-service/src/test/java/integration/net/firedevops/firemud/gamesession/service/InitialAdmissionBindPostgresIntegrationTest.java b/services/game-session-service/src/test/java/integration/net/firedevops/firemud/gamesession/service/InitialAdmissionBindPostgresIntegrationTest.java index 00cacfbd04..449e35f050 100644 --- a/services/game-session-service/src/test/java/integration/net/firedevops/firemud/gamesession/service/InitialAdmissionBindPostgresIntegrationTest.java +++ b/services/game-session-service/src/test/java/integration/net/firedevops/firemud/gamesession/service/InitialAdmissionBindPostgresIntegrationTest.java @@ -98,10 +98,10 @@ void initialAdmissionLedgerCommitsPointerAuditAndAttemptTogetherAndReadbackFails assertThat(dsl.fetchCount(DSL.table("gameplay_admission_pointer"))).isZero(); assertThat(dsl.fetchCount(DSL.table("gameplay_admission_pointer_event"))).isZero(); assertThat( - dsl.fetchValue( - "SELECT status FROM gameplay_initial_admission_bind_attempt WHERE attempt_id = ?", - String.class, - attempt.attemptId())) + dsl.fetchOne( + "SELECT status FROM gameplay_initial_admission_bind_attempt WHERE attempt_id = ?", + attempt.attemptId()) + .get("status", String.class)) .isEqualTo("PENDING"); dsl.execute("DROP TRIGGER reject_initial_admission_audit ON gameplay_admission_pointer_event"); dsl.execute("DROP FUNCTION reject_initial_admission_audit()"); From 5b8ab3550bef08a22310cd957e943cc8f4f97963 Mon Sep 17 00:00:00 2001 From: Ben Hook <5009589+benhook1013@users.noreply.github.com> Date: Sat, 3 Oct 2026 11:29:31 +1300 Subject: [PATCH 20/20] test: require retained initial admission row before status read --- .../InitialAdmissionBindPostgresIntegrationTest.java | 8 +++++--- 1 file changed, 5 insertions(+), 3 deletions(-) diff --git a/services/game-session-service/src/test/java/integration/net/firedevops/firemud/gamesession/service/InitialAdmissionBindPostgresIntegrationTest.java b/services/game-session-service/src/test/java/integration/net/firedevops/firemud/gamesession/service/InitialAdmissionBindPostgresIntegrationTest.java index 449e35f050..cc43052120 100644 --- a/services/game-session-service/src/test/java/integration/net/firedevops/firemud/gamesession/service/InitialAdmissionBindPostgresIntegrationTest.java +++ b/services/game-session-service/src/test/java/integration/net/firedevops/firemud/gamesession/service/InitialAdmissionBindPostgresIntegrationTest.java @@ -98,9 +98,11 @@ void initialAdmissionLedgerCommitsPointerAuditAndAttemptTogetherAndReadbackFails assertThat(dsl.fetchCount(DSL.table("gameplay_admission_pointer"))).isZero(); assertThat(dsl.fetchCount(DSL.table("gameplay_admission_pointer_event"))).isZero(); assertThat( - dsl.fetchOne( - "SELECT status FROM gameplay_initial_admission_bind_attempt WHERE attempt_id = ?", - attempt.attemptId()) + Objects.requireNonNull( + dsl.fetchOne( + "SELECT status FROM gameplay_initial_admission_bind_attempt WHERE attempt_id = ?", + attempt.attemptId()), + "expected retained initial-admission bind attempt after audit rollback") .get("status", String.class)) .isEqualTo("PENDING"); dsl.execute("DROP TRIGGER reject_initial_admission_audit ON gameplay_admission_pointer_event");