diff --git a/design/architecture/microservices/game-session-service/api-contracts.md b/design/architecture/microservices/game-session-service/api-contracts.md index 0362138e33..849c2c366a 100644 --- a/design/architecture/microservices/game-session-service/api-contracts.md +++ b/design/architecture/microservices/game-session-service/api-contracts.md @@ -10,7 +10,7 @@ Target state makes Game Session the authoritative owner of region/tick coordinat `EnqueueAutomationCommandIfAbsent` and `ScheduleRemoteFollowup` currently fail closed at their authenticated internal receiving boundary with `FAILED_PRECONDITION` / `automation_admission_receiver_fence_unavailable`, before command, coordinator, follow-up, or queue mutation. The retained lower-level admission implementation does not prove the cross-service Automation admission-epoch fence required by [ADR 0106](../../decisions/adr-0106-epoch-fenced-script-rollback-without-routine-gameplay-pause.md). A separate receiver-fence successor must durably serialize installation against receiving admission, preserve exact retry outcomes, and prove that a handoff whose intent committed before an Automation pause cannot create live work under the displaced admission epoch afterward. This gate preserves ordinary gameplay APIs and does not claim the successor implemented. -Realm-catalog identity status: Game Session pointer rows persist a separately advancing positive `catalogRevision` and stable UUID `realmId`/`playableStateNamespaceId`; new audit rows retain those values, and player-facing discovery and runtime pointer projections fail closed when identity is incomplete or a tenant catalog is ambiguous. The control-plane `SetAdmissionPointer` and `ExecutePreparedVersionCutover` paths currently fail closed pending catalog-revision and durable-identity preconditions. The existing configuration-driven startup pointer initializer and GS/WMS raw seed behavior remain legacy bootstrap inputs; they do not establish World-owner lifecycle proof or an owner-validated initial bind. The [Game Session runtime tracker](../../../project-management/implementation-tracking/game-session-runtime-and-tick-coordination.md) records execution evidence and remaining proof gaps. +Realm-catalog identity status: Game Session pointer and audit rows persist a separately advancing positive `catalogRevision` and stable UUID `realmId`/`playableStateNamespaceId`; player-facing catalog and runtime pointer projections fail closed when identity is incomplete or a tenant catalog is ambiguous. The control-plane `SetAdmissionPointer` and `ExecutePreparedVersionCutover` paths remain closed pending catalog-revision and durable-identity preconditions. The configuration-driven pointer initializer validates seed shape but does not write authority rows while World-owned lifecycle proof is unavailable; raw seed inputs do not establish that proof or an owner-validated initial bind. Current implementation and proof gaps are tracked in the [Game Session runtime tracker](../../../project-management/implementation-tracking/game-session-runtime-and-tick-coordination.md). This document mixes live and target-state control-plane surfaces. Current live behavior is narrower: @@ -48,6 +48,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 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 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..340b01d865 100644 --- a/design/architecture/microservices/world-management-service/api-contracts.md +++ b/design/architecture/microservices/world-management-service/api-contracts.md @@ -257,6 +257,24 @@ 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. + +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/design/architecture/microservices/world-management-service/runtime-and-data.md b/design/architecture/microservices/world-management-service/runtime-and-data.md index f58bce5725..16a5c81f04 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 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 - `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-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/architecture/system-architecture-multi-tenancy.md b/design/architecture/system-architecture-multi-tenancy.md index 12ea1b030d..edddbdf005 100644 --- a/design/architecture/system-architecture-multi-tenancy.md +++ b/design/architecture/system-architecture-multi-tenancy.md @@ -14,7 +14,7 @@ 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 persists a separate positive `catalogRevision` and stable `realmId`/`playableStateNamespaceId` on admission-pointer and audit records, and repository updates compare both pointer version and catalog revision. Player-facing catalog discovery and runtime pointer projections fail closed for ambiguous tenant catalogs or incomplete identity. The control-plane `SetAdmissionPointer` and `ExecutePreparedVersionCutover` paths currently fail closed pending catalog-revision and durable-identity preconditions. The existing configuration-driven startup pointer initializer and preserved GS/WMS raw seed paths remain legacy bootstrap behavior and do not establish World-owner lifecycle proof; an owner-validated initial bind remains unimplemented; 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. --- @@ -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 c5abc08ee7..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 @@ -10,7 +10,9 @@ 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). 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). @@ -34,7 +36,7 @@ Current command/effect and Automation handoff paths use narrower identities and ## Packet 4 Status and Proof Gaps -- `GR-1.1` / `GR-1.4`: [ADR 0122](../../architecture/decisions/adr-0122-stable-playable-state-namespaces-for-runtime-replacement.md) adds the runtime local consequence that admission and reconnects must use the active playable-state namespace and `playableStateScope`/instance fence. Existing handoff, drain, and route-swap gaps remain. Game Session admission-pointer rows now persist `catalogRevision`, `realmId`, and `playableStateNamespaceId`, but this does not prove replacement-state migration or cleanup. Concretely, the `game_instances` schema/entity/repository and `PreparedVersionUpgrade` persistence still have no `playableStateNamespaceId` or `playableStateScope`, and prepared cutover records version/remap and target-pointer facts only; current cutover therefore does not carry the stable namespace/scope binding required by the target. +- `GR-1.1` / `GR-1.4`: [ADR 0122](../../architecture/decisions/adr-0122-stable-playable-state-namespaces-for-runtime-replacement.md) adds the runtime local consequence that admission and reconnects must use the active playable-state namespace and `playableStateScope`/instance fence. Existing pointer, handoff, drain, and route-swap gaps remain; current Game Session evidence does not prove replacement-state migration or cleanup. Concretely, the `game_instances` schema/entity/repository and `PreparedVersionUpgrade` persistence have no `playableStateNamespaceId` or `playableStateScope`, and prepared cutover records version/remap and target-pointer facts only; this remains a partial implementation gap rather than evidence that current cutover carries stable namespace/scope identity. - `AR-3.1`: Current Game Session lifecycle uses staged local state and separate runtime mutation/finalization transactions; focused failure-path proof exists, but stable lifecycle-operation identity, durable lifecycle readback/reconciliation, owner-acknowledgement aggregation, and `TERMINATED` cleanup completion remain unimplemented or unproved. [ADR 0123](../../architecture/decisions/adr-0123-database-authoritative-temporal-coordinated-world-lifecycle.md) remains the canonical owner for the database-authoritative lifecycle and Temporal-coordination contract; this tracker records only Game Session implementation consequences. These links add decision provenance only; they do not upgrade any Game Session implementation or verification state. @@ -43,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 | `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. | +| `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. | @@ -83,7 +85,7 @@ The live queue and ownership boundary is still `(tenantId, gameInstanceId)`. The After ingress validation, rate and queue-target resolution, Game Session writes one `gameplay_command` row before Redis staging and assigns a stable `commandId`. The row includes tenant/game/session/actor identity, sanitized command text, admitted routing and runtime scope, timestamps and failure information, comparable `enqueueSeq`, automation/script/plugin provenance where applicable, the local Automation pin tuple where applicable, and the latest origin/queue source tuple. Credential-bearing input is sanitized before persistence, so passwords and OTPs do not become durable command history. -Current pointer-CAS status/proof: routed Automation and remote gameplay-command insertion uses one PostgreSQL `INSERT ... SELECT` guarded by exactly one total current pointer row for the tenant/game-instance target, with that sole row matching the normalized world/realm selectors, pointer version, and required nonblank playable-state scope. Missing, mismatched, or ambiguous authority fails retryably before the insert. Existing pointer updates use expected-version CAS, and pointer creation serializes on the runtime target and fails closed when another route already owns it. Focused unit and compile proof has passed for this path, but live PostgreSQL/Testcontainers concurrency proof is unavailable locally and remains required before claiming full proof. This gameplay-command ingress check does not consume `catalogRevision` or durable realm/namespace identity, even though those values are now persisted on pointer rows. +Current pointer-CAS status/proof: routed Automation and remote gameplay-command insertion uses one PostgreSQL `INSERT ... SELECT` guarded by exactly one total current pointer row for the tenant/game-instance target, with that sole row matching the normalized world/realm selectors, pointer version, and required nonblank playable-state scope. Missing, mismatched, or ambiguous authority fails retryably before the insert. Existing pointer updates use expected-version CAS, and pointer creation serializes on the runtime target and fails closed when another route already owns it. Focused unit and compile proof has passed for this path, but live PostgreSQL/Testcontainers concurrency proof is unavailable locally and remains required before claiming full proof. This current pointer-CAS note does not establish target stable-namespace or `realmId` completeness. The current command lifecycle is explicit: `ACCEPTED` means durable identity exists but staging has not succeeded; `STAGED` means Redis staging succeeded; `DRAINED` means a durable tick batch consumed the staged command; `RETRY_QUEUED` means an abandoned attempt was returned for another attempt; and `FAILED` means staging failed before gameplay application. For live startup-loss recovery, target `LOST_BEFORE_STAGING` is the terminal recovery state only for explicitly volatile/no-batch accepted work that never reached staging. Live startup recovery re-enqueues old `ACCEPTED` rows under the same command identity and leaves the row `ACCEPTED` when materialization is uncertain or fails, so durable accepted work remains retryable rather than being terminalized without evidence. Batch drain and abandonment update command rows, so status is not ingress-only. @@ -182,6 +184,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 a8ccf449ab..e6e42d9651 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 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 - `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. @@ -24,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` | `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 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. | @@ -115,6 +117,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/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..cf11b756c0 100644 --- a/dev-tools/certs/ensure-dev-certs.sh +++ b/dev-tools/certs/ensure-dev-certs.sh @@ -6,11 +6,61 @@ CERT_DIR="${1:-$SCRIPT_DIR}" GENERATOR="$SCRIPT_DIR/generate-dev-certs.sh" COMPOSE_MTLS_STAGE_ROOT="" COMPOSE_MTLS_STAGE_DIR="" +COMPOSE_MTLS_LEAF_STAGE_DIR="" cleanup_compose_mtls_stage() { if [[ -n "$COMPOSE_MTLS_STAGE_DIR" && "$COMPOSE_MTLS_STAGE_DIR" == "$COMPOSE_MTLS_STAGE_ROOT"/.workloads.* && -d "$COMPOSE_MTLS_STAGE_DIR" && ! -L "$COMPOSE_MTLS_STAGE_DIR" ]]; then rm -rf -- "$COMPOSE_MTLS_STAGE_DIR" fi + if [[ -n "$COMPOSE_MTLS_LEAF_STAGE_DIR" && "$COMPOSE_MTLS_LEAF_STAGE_DIR" == "$COMPOSE_MTLS_STAGE_ROOT"/.world-management-service-leaf.* && -d "$COMPOSE_MTLS_LEAF_STAGE_DIR" && ! -L "$COMPOSE_MTLS_LEAF_STAGE_DIR" ]]; then + rm -rf -- "$COMPOSE_MTLS_LEAF_STAGE_DIR" + fi +} + +compose_certificate_matches_private_key() { + local certificate="$1" private_key="$2" certificate_public_key private_key_public_key + certificate_public_key="$(openssl x509 -in "$certificate" -pubkey -noout | openssl pkey -pubin -outform DER | sha256sum | awk '{print $1}')" + private_key_public_key="$(openssl pkey -in "$private_key" -pubout -outform DER | sha256sum | awk '{print $1}')" + [[ "$certificate_public_key" == "$private_key_public_key" ]] +} + +migrate_legacy_world_management_leaf() { + local requested_root="$1" authority_dir="$2" service_dir="$3" + local staged_certificate staged_private_key san_output + + # The only upgradeable shape is the original generic authority/client pair, + # copied byte-for-byte into the WMS fixture and still using the same CA. + if ! cmp -s "$service_dir/client.crt" "$authority_dir/client.crt" \ + || ! cmp -s "$service_dir/client.key" "$authority_dir/client.key" \ + || ! cmp -s "$service_dir/ca.crt" "$authority_dir/ca.crt" \ + || ! compose_certificate_matches_private_key "$service_dir/client.crt" "$service_dir/client.key"; then + return 1 + fi + + COMPOSE_MTLS_STAGE_ROOT="$requested_root" + COMPOSE_MTLS_LEAF_STAGE_DIR="$(mktemp -d "$requested_root/.world-management-service-leaf.XXXXXX")" || return 1 + chmod 700 "$COMPOSE_MTLS_LEAF_STAGE_DIR" || return 1 + staged_certificate="$COMPOSE_MTLS_LEAF_STAGE_DIR/client.crt" + staged_private_key="$COMPOSE_MTLS_LEAF_STAGE_DIR/client.key" + "$GENERATOR" --workload \ + "$authority_dir/ca.crt" "$authority_dir/ca.key" \ + "$staged_certificate" "$staged_private_key" dev world-management-service || return 1 + chmod 444 "$staged_certificate" "$staged_private_key" || return 1 + + openssl verify -CAfile "$authority_dir/ca.crt" "$staged_certificate" >/dev/null || return 1 + san_output="$(openssl x509 -in "$staged_certificate" -noout -ext subjectAltName)" || return 1 + if [[ "$san_output" != *"URI:spiffe://firemud/ns/dev/sa/world-management-service"* ]] \ + || ! compose_certificate_matches_private_key "$staged_certificate" "$staged_private_key"; then + echo "Generated Compose mTLS WMS leaf failed identity or key validation." >&2 + return 1 + fi + + # Both validated files are staged on the fixture filesystem; each rename + # atomically replaces only the corresponding WMS leaf file. + mv -fT -- "$staged_certificate" "$service_dir/client.crt" || return 1 + mv -fT -- "$staged_private_key" "$service_dir/client.key" || return 1 + openssl verify -CAfile "$service_dir/ca.crt" "$service_dir/client.crt" >/dev/null || return 1 + compose_certificate_matches_private_key "$service_dir/client.crt" "$service_dir/client.key" || return 1 } ensure_compose_mtls_certs() { @@ -94,7 +144,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" @@ -140,6 +190,10 @@ ensure_compose_mtls_certs() { return 1 fi openssl verify -CAfile "$service_dir/ca.crt" "$service_dir/client.crt" >/dev/null + if ! compose_certificate_matches_private_key "$service_dir/client.crt" "$service_dir/client.key"; then + echo "Compose mTLS workload certificate and private key do not match: $service" >&2 + return 1 + fi done local found_service_count=0 entry for entry in "$workloads_dir"/*; do @@ -154,12 +208,16 @@ 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 - echo "Compose mTLS workload has the wrong SPIFFE identity: $service" >&2 - return 1 + if [[ "$service" != world-management-service ]] \ + || ! migrate_legacy_world_management_leaf \ + "$requested_root" "$authority_dir" "$workloads_dir/$service"; then + echo "Compose mTLS workload has the wrong SPIFFE identity: $service" >&2 + return 1 + fi fi done fi 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 e622a208cc..ec83082f6c 100644 --- a/dev-tools/tests/compose-grpc-mtls-contract.sh +++ b/dev-tools/tests/compose-grpc-mtls-contract.sh @@ -13,16 +13,16 @@ project_name="firemud-smoke-$run_id" project_key="$(printf '%s' "$project_name" | sha256sum | awk '{print $1}')" fixture_root="$ownership_dir/$project_key.grpc-mtls" -FIREMUD_SMOKE_TEST_MODE=1 \ -FIREMUD_SMOKE_OWNERSHIP_DIR="$ownership_dir" \ -FIREMUD_SMOKE_RUN_ID="$run_id" \ -COMPOSE_PROJECT_NAME="$project_name" \ - bash "$ROOT_DIR/dev-tools/certs/ensure-dev-certs.sh" --compose-mtls "$fixture_root" -FIREMUD_SMOKE_TEST_MODE=1 \ -FIREMUD_SMOKE_OWNERSHIP_DIR="$ownership_dir" \ -FIREMUD_SMOKE_RUN_ID="$run_id" \ -COMPOSE_PROJECT_NAME="$project_name" \ - bash "$ROOT_DIR/dev-tools/certs/ensure-dev-certs.sh" --compose-mtls "$fixture_root" +ensure_compose_mtls_fixture() { + FIREMUD_SMOKE_TEST_MODE=1 \ + FIREMUD_SMOKE_OWNERSHIP_DIR="$ownership_dir" \ + FIREMUD_SMOKE_RUN_ID="$run_id" \ + COMPOSE_PROJECT_NAME="$project_name" \ + bash "$ROOT_DIR/dev-tools/certs/ensure-dev-certs.sh" --compose-mtls "$fixture_root" +} + +ensure_compose_mtls_fixture +ensure_compose_mtls_fixture services=( account-service gateway automation-scripting-service entity-management-service @@ -64,6 +64,109 @@ public_key_digest() { fi | openssl pkey -pubin -outform DER 2>/dev/null | openssl dgst -sha256 | awk '{print $NF}' } +file_digest() { + sha256sum "$1" | awk '{print $1}' +} + +# Recreate the retained fixture's exact legacy shape: only the WMS leaf is the +# generic authority/client pair. The owner claim and all other fixture material +# remain in place while ensure-dev-certs performs the narrow migration. +declare -A authority_digests=() +for file in ca.crt ca.key client.crt client.key; do + authority_digests["$file"]="$(file_digest "$fixture_root/authority/$file")" +done +declare -A workload_ca_digests=() other_leaf_digests=() +for service in "${services[@]}"; do + service_dir="$workloads_dir/$service" + workload_ca_digests["$service"]="$(file_digest "$service_dir/ca.crt")" + if [[ "$service" != world-management-service ]]; then + other_leaf_digests["$service.crt"]="$(file_digest "$service_dir/client.crt")" + other_leaf_digests["$service.key"]="$(file_digest "$service_dir/client.key")" + fi +done +wms_dir="$workloads_dir/world-management-service" +chmod 644 "$wms_dir/client.crt" "$wms_dir/client.key" +cp -- "$fixture_root/authority/client.crt" "$wms_dir/client.crt" +cp -- "$fixture_root/authority/client.key" "$wms_dir/client.key" +chmod 444 "$wms_dir/client.crt" "$wms_dir/client.key" +legacy_wms_fingerprint="$(openssl x509 -in "$wms_dir/client.crt" -noout -fingerprint -sha256)" + +ensure_compose_mtls_fixture +canonical_wms_san="$(openssl x509 -in "$wms_dir/client.crt" -noout -ext subjectAltName)" +[[ "$canonical_wms_san" == *"URI:spiffe://firemud/ns/dev/sa/world-management-service"* ]] +[[ "$(openssl x509 -in "$wms_dir/client.crt" -noout -fingerprint -sha256)" != "$legacy_wms_fingerprint" ]] +[[ "$(public_key_digest "$wms_dir/client.crt" certificate)" == "$(public_key_digest "$wms_dir/client.key" key)" ]] +for file in ca.crt ca.key client.crt client.key; do + [[ "$(file_digest "$fixture_root/authority/$file")" == "${authority_digests[$file]}" ]] +done +for service in "${services[@]}"; do + service_dir="$workloads_dir/$service" + [[ "$(file_digest "$service_dir/ca.crt")" == "${workload_ca_digests[$service]}" ]] + if [[ "$service" != world-management-service ]]; then + [[ "$(file_digest "$service_dir/client.crt")" == "${other_leaf_digests[$service.crt]}" ]] + [[ "$(file_digest "$service_dir/client.key")" == "${other_leaf_digests[$service.key]}" ]] + fi +done +migrated_wms_certificate_digest="$(file_digest "$wms_dir/client.crt")" +migrated_wms_key_digest="$(file_digest "$wms_dir/client.key")" +ensure_compose_mtls_fixture +[[ "$(file_digest "$wms_dir/client.crt")" == "$migrated_wms_certificate_digest" ]] +[[ "$(file_digest "$wms_dir/client.key")" == "$migrated_wms_key_digest" ]] + +canonical_wms_dir="$TEST_ROOT/canonical-wms" +mkdir -m 700 -- "$canonical_wms_dir" +cp -- "$wms_dir/client.crt" "$canonical_wms_dir/client.crt" +cp -- "$wms_dir/client.key" "$canonical_wms_dir/client.key" + +# A canonical-SAN certificate paired with the legacy generic key is neither a +# valid retry nor the recognized legacy copy, so validation must fail without +# repairing either file. +chmod 644 "$wms_dir/client.key" +cp -- "$fixture_root/authority/client.key" "$wms_dir/client.key" +chmod 444 "$wms_dir/client.key" +stale_key_wms_certificate_digest="$(file_digest "$wms_dir/client.crt")" +stale_key_wms_key_digest="$(file_digest "$wms_dir/client.key")" +if ensure_compose_mtls_fixture >"$TEST_ROOT/stale-key-output" 2>&1; then + echo "Compose mTLS certificate validation accepted a mismatched canonical WMS key." >&2 + exit 1 +fi +rg -Fq 'Compose mTLS workload certificate and private key do not match: world-management-service' "$TEST_ROOT/stale-key-output" +[[ "$(file_digest "$wms_dir/client.crt")" == "$stale_key_wms_certificate_digest" ]] +[[ "$(file_digest "$wms_dir/client.key")" == "$stale_key_wms_key_digest" ]] +chmod 644 "$wms_dir/client.crt" "$wms_dir/client.key" +cp -- "$canonical_wms_dir/client.crt" "$wms_dir/client.crt" +cp -- "$canonical_wms_dir/client.key" "$wms_dir/client.key" +chmod 444 "$wms_dir/client.crt" "$wms_dir/client.key" +[[ "$(file_digest "$wms_dir/client.crt")" == "$migrated_wms_certificate_digest" ]] +[[ "$(file_digest "$wms_dir/client.key")" == "$migrated_wms_key_digest" ]] + +unknown_wms_dir="$TEST_ROOT/unknown-wms" +mkdir -m 700 -- "$unknown_wms_dir" +"$ROOT_DIR/dev-tools/certs/generate-dev-certs.sh" --workload \ + "$fixture_root/authority/ca.crt" "$fixture_root/authority/ca.key" \ + "$unknown_wms_dir/client.crt" "$unknown_wms_dir/client.key" test world-management-service +chmod 444 "$unknown_wms_dir/client.crt" "$unknown_wms_dir/client.key" +openssl verify -CAfile "$fixture_root/authority/ca.crt" "$unknown_wms_dir/client.crt" >/dev/null +chmod 644 "$wms_dir/client.crt" "$wms_dir/client.key" +cp -- "$unknown_wms_dir/client.crt" "$wms_dir/client.crt" +cp -- "$unknown_wms_dir/client.key" "$wms_dir/client.key" +chmod 444 "$wms_dir/client.crt" "$wms_dir/client.key" +unknown_wms_certificate_digest="$(file_digest "$wms_dir/client.crt")" +unknown_wms_key_digest="$(file_digest "$wms_dir/client.key")" +if ensure_compose_mtls_fixture >"$TEST_ROOT/unknown-identity-output" 2>&1; then + echo "Compose mTLS certificate validation accepted an unknown WMS identity." >&2 + exit 1 +fi +rg -Fq 'Compose mTLS workload has the wrong SPIFFE identity: world-management-service' "$TEST_ROOT/unknown-identity-output" +[[ "$(file_digest "$wms_dir/client.crt")" == "$unknown_wms_certificate_digest" ]] +[[ "$(file_digest "$wms_dir/client.key")" == "$unknown_wms_key_digest" ]] +chmod 644 "$wms_dir/client.crt" "$wms_dir/client.key" +cp -- "$canonical_wms_dir/client.crt" "$wms_dir/client.crt" +cp -- "$canonical_wms_dir/client.key" "$wms_dir/client.key" +chmod 444 "$wms_dir/client.crt" "$wms_dir/client.key" +[[ "$(file_digest "$wms_dir/client.crt")" == "$migrated_wms_certificate_digest" ]] +[[ "$(file_digest "$wms_dir/client.key")" == "$migrated_wms_key_digest" ]] + for service in "${services[@]}"; do echo "Checking Compose mTLS leaf: $service" service_dir="$workloads_dir/$service" @@ -79,21 +182,119 @@ 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" +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" +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 @@ -133,18 +334,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 = { @@ -168,6 +372,22 @@ 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 +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 8e964e51a9..ab79427c42 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 @@ -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: @@ -77,5 +88,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/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/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/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/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/data/GameplayAdmissionPointerBootstrapInitializer.java b/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/data/GameplayAdmissionPointerBootstrapInitializer.java index 5879092158..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 @@ -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,73 +28,94 @@ 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) { + 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; } - for (GameplayAdmissionPointerBootstrapProperties.PointerSeed pointer : - bootstrapProperties.getPointers()) { - if (pointer == null - || pointer.getWorldSlug() == null - || pointer.getWorldSlug().isBlank() - || pointer.getRealmSlug() == null - || pointer.getRealmSlug().isBlank()) { - continue; + 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) { + throw new IllegalArgumentException("Gameplay admission pointer bootstrap seeds are required"); + } + + 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, - 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/data/RunOwnedInitialAdmissionFixtureCapability.java b/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/data/RunOwnedInitialAdmissionFixtureCapability.java new file mode 100644 index 0000000000..beaade5843 --- /dev/null +++ b/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/data/RunOwnedInitialAdmissionFixtureCapability.java @@ -0,0 +1,442 @@ +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.GeneralSecurityException; +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 (GeneralSecurityException 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(); + } + } + + 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) { + if (value == null) { + return false; + } + try { + return UUID.fromString(value).toString().equals(value); + } catch (IllegalArgumentException 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..807932a8cd --- /dev/null +++ b/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/data/RunOwnedInitialAdmissionFixtureCoordinator.java @@ -0,0 +1,524 @@ +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) { + SafeDiagnostic diagnostic = safeDiagnostic(exception); + if (attempt >= MAX_ATTEMPTS) { + finished.set(true); + logger.error( + "Run-owned initial-admission fixture did not reach a verified terminal result after" + + " the bounded retry budget; World hold state remains owner-controlled." + + " exceptionType={} errorCode={} message={}", + diagnostic.exceptionType(), + diagnostic.errorCode(), + diagnostic.message()); + } else { + logger.warn( + "Run-owned initial-admission fixture attempt {}/{} remains unresolved; the same" + + " stable operation identity will be retried. exceptionType={} errorCode={}" + + " message={}", + attempt, + MAX_ATTEMPTS, + diagnostic.exceptionType(), + diagnostic.errorCode(), + diagnostic.message()); + } + } finally { + inProgress.set(false); + } + } + + BootstrapResult coordinate(RunOwnedInitialAdmissionFixtureCapability capability) { + 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) { + if (value == null) { + return false; + } + try { + return UUID.fromString(value).toString().equals(value); + } catch (IllegalArgumentException exception) { + return false; + } + } + + private static boolean isCanonicalPositiveLong(String value) { + if (value == null) { + return false; + } + try { + long parsed = Long.parseLong(value); + return parsed > 0L && Long.toString(parsed).equals(value); + } catch (NumberFormatException exception) { + return false; + } + } + + private static RuntimeException unresolved() { + return new IllegalStateException("Run-owned initial-admission fixture remains unresolved"); + } + + private static SafeDiagnostic safeDiagnostic(RuntimeException exception) { + if (exception instanceof IllegalArgumentException) { + return new SafeDiagnostic( + exception.getClass().getSimpleName(), + "FIXTURE_INPUT_REJECTED", + "Fixture input or owner response was rejected."); + } + if (exception instanceof IllegalStateException) { + return new SafeDiagnostic( + exception.getClass().getSimpleName(), + "FIXTURE_STATE_UNRESOLVED", + "Fixture state remains unresolved."); + } + return new SafeDiagnostic( + exception.getClass().getSimpleName(), + "FIXTURE_ATTEMPT_FAILED", + "Fixture dependency attempt failed."); + } + + private record SafeDiagnostic(String exceptionType, String errorCode, String message) {} + + enum BootstrapResult { + COMMITTED, + ABORTED + } +} diff --git a/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/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/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/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/InitialAdmissionBindAttemptRepository.java b/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/repository/InitialAdmissionBindAttemptRepository.java new file mode 100644 index 0000000000..d416468e94 --- /dev/null +++ b/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/repository/InitialAdmissionBindAttemptRepository.java @@ -0,0 +1,299 @@ +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()) + .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 was not pending with an unattached 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().longValue()).orElseThrow(); + } + + public 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/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/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/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/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/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/V10__run_owned_initial_launch_identity.sql b/services/game-session-service/src/main/resources/db/migration/V10__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/V10__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/main/resources/db/migration/V9__initial_admission_bind_owner_ledger.sql b/services/game-session-service/src/main/resources/db/migration/V9__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/V9__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/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..cc43052120 --- /dev/null +++ b/services/game-session-service/src/test/java/integration/net/firedevops/firemud/gamesession/service/InitialAdmissionBindPostgresIntegrationTest.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.Objects; +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 initialAdmissionLedgerCommitsPointerAuditAndAttemptTogetherAndReadbackFailsClosed() { + 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( + 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"); + 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( + 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 = + 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()); + 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/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..d6766d3d57 --- /dev/null +++ b/services/game-session-service/src/test/java/integration/net/firedevops/firemud/gamesession/service/RunOwnedInitialLaunchPostgresIntegrationTest.java @@ -0,0 +1,208 @@ +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.sql.SQLException; +import java.util.Objects; +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( + 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( + 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); + + assertThatThrownBy(() -> insertDuplicateIdentity(dsl, firstId + 1L)) + .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( + 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); + } + } + + 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 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"); + 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/CrossServiceAppHarnessTest.java b/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/CrossServiceAppHarnessTest.java new file mode 100644 index 0000000000..818c6986fb --- /dev/null +++ b/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/CrossServiceAppHarnessTest.java @@ -0,0 +1,91 @@ +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.getBeanNamesForType(GameInstanceServiceImpl.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/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/data/GameplayAdmissionPointerBootstrapInitializerTest.java b/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/data/GameplayAdmissionPointerBootstrapInitializerTest.java index 732b5c72a5..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 @@ -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,183 @@ 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 { + void runTreatsEmptyBootstrapPointerSeedsAsExplicitOptOutWithoutMutation() 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))); + properties.setPointers(List.of()); initializer.run(new DefaultApplicationArguments(new String[] {})); - ArgumentCaptor mutationCaptor = - ArgumentCaptor.forClass(GameplayAdmissionPointerMutation.class); - verify(authorityService).upsertPointer(mutationCaptor.capture()); - assertEquals("demo", mutationCaptor.getValue().worldSlug()); + verify(pointerRepository).count(); + verifyNoMoreInteractions(pointerRepository); + } + + @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"); + } + + @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 +216,7 @@ private static GameplayAdmissionPointerBootstrapProperties.PointerSeed pointerSe String realmDisplayName, long tenantId, long gameInstanceId, + boolean publicProductionRealm, boolean requiresCharacterSelection) { GameplayAdmissionPointerBootstrapProperties.PointerSeed pointerSeed = new GameplayAdmissionPointerBootstrapProperties.PointerSeed(); @@ -128,11 +227,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/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..ae05ad6384 --- /dev/null +++ b/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/data/RunOwnedInitialAdmissionFixtureCapabilityTest.java @@ -0,0 +1,183 @@ +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.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; + +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(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\"")); + 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.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 = + 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 """ + {%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, + 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..83a07c8aae --- /dev/null +++ b/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/data/RunOwnedInitialAdmissionFixtureCoordinatorTest.java @@ -0,0 +1,699 @@ +package net.firedevops.firemud.gamesession.data; + +import static org.assertj.core.api.Assertions.assertThat; +import static org.assertj.core.api.Assertions.assertThatThrownBy; +import static org.mockito.ArgumentMatchers.any; +import static org.mockito.ArgumentMatchers.anyLong; +import static org.mockito.ArgumentMatchers.anyString; +import static org.mockito.ArgumentMatchers.eq; +import static org.mockito.Mockito.doAnswer; +import static org.mockito.Mockito.doThrow; +import static org.mockito.Mockito.inOrder; +import static org.mockito.Mockito.mockStatic; +import static org.mockito.Mockito.never; +import static org.mockito.Mockito.same; +import static org.mockito.Mockito.times; +import static org.mockito.Mockito.verify; +import static org.mockito.Mockito.verifyNoInteractions; +import static org.mockito.Mockito.when; + +import java.nio.file.Path; +import java.time.Instant; +import java.util.UUID; +import java.util.concurrent.atomic.AtomicInteger; +import java.util.concurrent.atomic.AtomicReference; +import net.firedevops.firemud.common.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; +import net.firedevops.firemud.gamesession.service.GameInstanceService; +import net.firedevops.firemud.gamesession.service.InitialAdmissionBindCatalogDescriptor; +import net.firedevops.firemud.gamesession.service.InitialAdmissionBindHoldBinding; +import net.firedevops.firemud.gamesession.service.InitialAdmissionBindOwnerProof; +import net.firedevops.firemud.gamesession.service.InitialAdmissionBindOwnerProof.Outcome; +import net.firedevops.firemud.gamesession.service.InitialAdmissionBindOwnerService; +import net.firedevops.firemud.gamesession.service.InitialAdmissionBindRequest; +import net.firedevops.firemud.gamesession.service.RunOwnedInitialLaunchResult; +import net.firedevops.firemud.worldmanagement.v1.AcquireInitialAdmissionBindHoldResponse; +import net.firedevops.firemud.worldmanagement.v1.InitialAdmissionBindHold; +import net.firedevops.firemud.worldmanagement.v1.InitialAdmissionBindHoldStatus; +import org.junit.jupiter.api.Test; +import org.junit.jupiter.api.extension.ExtendWith; +import org.mockito.ArgumentCaptor; +import org.mockito.InOrder; +import org.mockito.MockedStatic; +import org.springframework.boot.test.system.CapturedOutput; +import org.springframework.boot.test.system.OutputCaptureExtension; + +@ExtendWith(OutputCaptureExtension.class) +class RunOwnedInitialAdmissionFixtureCoordinatorTest { + private static final String RUN_ID = "compose-smoke-2939"; + private static final String PROJECT_NAME = "firemud-smoke-compose-smoke-2939"; + private static final String CAPABILITY_PATH = "fixture/capability.json"; + private static final String 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 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 = + 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); + } + + @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 = + 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 = + 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, + CAPABILITY_PATH, + RUN_ID, + PROJECT_NAME, + grpc, + gameInstanceService, + ownerService, + worldClient); + return new Fixture( + 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( + 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, + CommonGrpcClientProperties grpcProperties, + GameInstanceService gameInstanceService, + InitialAdmissionBindOwnerService ownerService, + WorldManagementClient worldClient, + AtomicReference request) {} +} diff --git a/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/data/TestDataSeederTest.java b/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/data/TestDataSeederTest.java index 0ec9ea647c..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 @@ -5,10 +5,8 @@ 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; import net.firedevops.firemud.gamesession.repository.GameManifestRepository; import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.Test; @@ -21,28 +19,23 @@ class TestDataSeederTest { @Mock GameManifestRepository gameManifestRepository; @Mock FeatureFlagRepository featureFlagRepository; - @Mock GameInstanceRepository gameInstanceRepository; private TestDataSeeder seeder; @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)); } } 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/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/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/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/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..39e395baa0 --- /dev/null +++ b/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/support/MutableDefaultDemoCatalogTest.java @@ -0,0 +1,204 @@ +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 defaultDemoIsAbsentUntilPersistedPointerAuthorityContainsIt() { + MutablePointerAuthority authority = new MutablePointerAuthority(); + TestGameplayWorldCatalogs.MutableDefaultDemoCatalog fixture = fixture(authority); + GameplayWorldCatalog catalog = fixture.catalog(); + + assertThat(catalog.resolveWorld("demo")).isEmpty(); + + 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(); + 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 persistedPointerIsTheOnlySourceForTheDefaultDemoRoute() { + MutablePointerAuthority authority = new MutablePointerAuthority(); + TestGameplayWorldCatalogs.MutableDefaultDemoCatalog fixture = fixture(authority); + 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 selectorForAnotherTenantIsNotReplacedByASyntheticDefaultRoute() { + MutablePointerAuthority authority = new MutablePointerAuthority(); + TestGameplayWorldCatalogs.MutableDefaultDemoCatalog fixture = fixture(authority); + 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 missingPersistedAuthorityRemainsMissing() { + MutablePointerAuthority authority = new MutablePointerAuthority(); + TestGameplayWorldCatalogs.MutableDefaultDemoCatalog fixture = fixture(authority); + + assertThat(fixture.catalog().resolveWorld("demo")).isEmpty(); + } + + @Test + void incompletePersistedPointerFailsClosed() { + MutablePointerAuthority authority = new MutablePointerAuthority(); + TestGameplayWorldCatalogs.MutableDefaultDemoCatalog fixture = fixture(authority); + 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 ambiguousPersistedPublicAuthorityFailsClosed() { + MutablePointerAuthority authority = new MutablePointerAuthority(); + TestGameplayWorldCatalogs.MutableDefaultDemoCatalog fixture = fixture(authority); + 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) + .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 List listPointersByTenant(long tenantId) { + return pointers.stream().filter(pointer -> pointer.tenantId() == tenantId).toList(); + } + + @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 050c62a4e0..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 @@ -21,9 +21,19 @@ 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.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; import org.springframework.boot.web.server.context.WebServerApplicationContext; @@ -317,9 +327,61 @@ public void clear(long tenantId, long gameInstanceId, long characterId) { }; } - @Bean(name = "gameInstanceServiceImpl") + @Bean + @ConditionalOnProperty( + 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") @Primary - GameInstanceService gameInstanceService() { + @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( @@ -350,10 +412,34 @@ 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) { + throw new IllegalStateException( + "run-owned launch requires a database-enabled test context"); + } }; } } + /** 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..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 @@ -1,10 +1,19 @@ 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 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 +23,122 @@ public static GameplayWorldCatalog fromProperties(GameplayCatalogProperties prop return GameplayWorldCatalog.forWorldSupplier(() -> toWorldViews(properties.getWorlds())); } + /** Test-only catalog projection backed by the same durable pointer authority as production. */ + public static final class MutableDefaultDemoCatalog { + private final GameplayAdmissionPointerAuthorityService pointerAuthority; + + public MutableDefaultDemoCatalog(GameplayAdmissionPointerAuthorityService pointerAuthority) { + this.pointerAuthority = + Objects.requireNonNull(pointerAuthority, "pointerAuthority must not be null"); + } + + public GameplayWorldCatalog catalog() { + return GameplayWorldCatalog.forWorldSupplier(this::worlds); + } + + private List worlds() { + return fromPointers(pointerAuthority.listPointers()); + } + } + + 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 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 309203b51e..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,16 +1,34 @@ 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.test.GameInstanceTestFixtures; @@ -21,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; @@ -41,6 +65,7 @@ public final class GameplayCrossServiceStack implements AutoCloseable { private final ListFriendPresenceResponse baselineFriendPresenceResponse; private CrossServiceAppHarness.GameLogicHolder gameLogic; private final CrossServiceAppHarness.GameSessionHolder gameSession; + private final boolean useDefaultDemoCatalogFixture; private GameplayCrossServiceStack( AccountRuntimeStubServer accountStub, @@ -51,7 +76,8 @@ private GameplayCrossServiceStack( net.firedevops.firemud.entitymanagement.v1.ListRoomEntitiesResponse baselineRoomEntities, ListFriendPresenceResponse baselineFriendPresenceResponse, CrossServiceAppHarness.GameLogicHolder gameLogic, - CrossServiceAppHarness.GameSessionHolder gameSession) { + CrossServiceAppHarness.GameSessionHolder gameSession, + boolean useDefaultDemoCatalogFixture) { this.accountStub = accountStub; this.gameDesignStub = gameDesignStub; this.worldStub = worldStub; @@ -61,6 +87,7 @@ private GameplayCrossServiceStack( this.baselineFriendPresenceResponse = baselineFriendPresenceResponse; this.gameLogic = gameLogic; this.gameSession = gameSession; + this.useDefaultDemoCatalogFixture = useDefaultDemoCatalogFixture; } public static Builder builder() { @@ -69,15 +96,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( @@ -177,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) { @@ -186,9 +219,603 @@ public long freshGameplayBaseline( GameInstanceTestFixtures.insertRunningGameInstance( jdbc, tenantId, ownerAccountId, gameTemplateId); seedRuntimeOwnership(tenantId, gameInstanceId); + if (useDefaultDemoCatalogFixture) { + bindDefaultDemoPointer(tenantId, gameInstanceId, ownerAccountId, gameTemplateId); + } return gameInstanceId; } + 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 @@ -352,6 +979,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 +1067,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 +1108,7 @@ public GameplayCrossServiceStack start() throws IOException { } props.putAll(gameSessionProps); }, - gameSessionConfigs); + selectedGameSessionConfigs); return new GameplayCrossServiceStack( accountStub, @@ -483,7 +1119,8 @@ public GameplayCrossServiceStack start() throws IOException { initialRoomEntities, initialFriendPresenceResponse, gameLogic, - gameSession); + gameSession, + useDefaultDemoCatalogFixture); } private void requireConfigured() { 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..aa09750a17 --- /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 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/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/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..399496dcb5 --- /dev/null +++ b/services/world-management-service/src/main/java/net/firedevops/firemud/worldmanagement/dto/InitialAdmissionBindOwnerProof.java @@ -0,0 +1,32 @@ +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 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/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/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..7011b84675 --- /dev/null +++ b/services/world-management-service/src/main/java/net/firedevops/firemud/worldmanagement/repository/InitialAdmissionBindHoldRepository.java @@ -0,0 +1,235 @@ +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; +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 +@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, " + + "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 hasNonterminalForRealm(long tenantId, String realmUuid) { + 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'))", + tenantId, + 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( + 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) { + 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( + 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/RoomRepository.java b/services/world-management-service/src/main/java/net/firedevops/firemud/worldmanagement/repository/RoomRepository.java index ba89b5a531..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 @@ -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,42 @@ 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() { + 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 " + + quotedSequenceName + + "), 1)), true)", + sequenceName); + } + 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/repository/WorldInstanceRepository.java b/services/world-management-service/src/main/java/net/firedevops/firemud/worldmanagement/repository/WorldInstanceRepository.java index df1fc9d9c7..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 @@ -32,6 +32,33 @@ 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) { + 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'))", + tenantId, + 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) { 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..dadcb6a870 --- /dev/null +++ b/services/world-management-service/src/main/java/net/firedevops/firemud/worldmanagement/service/impl/InitialAdmissionBindHoldReconciler.java @@ -0,0 +1,153 @@ +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; +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; + +/** + * Automatically reconciles World holds and keeps them fenced when owner readback is unavailable. + */ +@Component +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, + MeterRegistry meterRegistry) { + this(holdRepository, holdService, proofClientProvider, Clock.systemUTC(), meterRegistry); + } + + InitialAdmissionBindHoldReconciler( + InitialAdmissionBindHoldRepository holdRepository, + InitialAdmissionBindHoldService holdService, + ObjectProvider proofClientProvider, + 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}") + public void reconcilePendingHolds() { + List holds = + holdRepository.findNonterminal(32); + if (holds.isEmpty()) { + return; + } + GameSessionInitialAdmissionBindProofClient proofClient = proofClientProvider.getIfAvailable(); + for (var hold : holds) { + boolean overdue = !hold.diagnosticExpiresAt().isAfter(clock.instant()); + String errorCode = boundedErrorCode(hold.reconciliationError()); + try { + errorCode = reconcileHold(hold, proofClient); + } catch (RuntimeException exception) { + logger.warn( + "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 String reconcileHold( + net.firedevops.firemud.worldmanagement.entity.InitialAdmissionBindHold hold, + GameSessionInitialAdmissionBindProofClient proofClient) { + if (proofClient == null) { + holdService.requireReconciliation(hold.holdId(), "GS_OWNER_READ_UNAVAILABLE"); + return "GS_OWNER_READ_UNAVAILABLE"; + } + + InitialAdmissionBindOwnerProof ownerProof; + try { + ownerProof = proofClient.readOwnerProof(hold); + } catch (RuntimeException exception) { + logger.warn( + "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/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..b90eca438c --- /dev/null +++ b/services/world-management-service/src/main/java/net/firedevops/firemud/worldmanagement/service/impl/InitialAdmissionBindHoldServiceImpl.java @@ -0,0 +1,449 @@ +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.beans.factory.annotation.Autowired; +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; + + @Autowired + 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); + 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() == 1L + && 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.pointerAuditRequestDigest() == null + || proof.pointerAuditRequestDigest().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.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..e726827acf --- /dev/null +++ b/services/world-management-service/src/test/java/integration/net/firedevops/firemud/worldmanagement/InitialAdmissionBindHoldPostgresIntegrationTest.java @@ -0,0 +1,303 @@ +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.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; +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; +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.jooq.Record; +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 GrpcGameSessionInitialAdmissionBindProofClient bindProofClient; + @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); + AtomicInteger acquisitionBackendPid = new AtomicInteger(); + TransactionTemplate transactionTemplate = new TransactionTemplate(transactionManager); + + try (ExecutorService executor = Executors.newFixedThreadPool(2)) { + Future acquireFuture = + executor.submit( + () -> + transactionTemplate.execute( + status -> { + 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 = + 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(); + 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)); + 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 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 = ?", + 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/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..2418d459fa --- /dev/null +++ b/services/world-management-service/src/test/java/integration/net/firedevops/firemud/worldmanagement/RoomRepositoryPostgresIntegrationTest.java @@ -0,0 +1,121 @@ +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.client.GrpcGameSessionInitialAdmissionBindProofClient; +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.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.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; + @Autowired private DSLContext dsl; + + @MockitoBean private GrpcServerLifecycle grpcServerLifecycle; + @MockitoBean private GrpcGameSessionInitialAdmissionBindProofClient bindProofClient; + @MockitoBean private EntityManagementClient entityManagementClient; + @MockitoBean private GameDesignClient gameDesignClient; + @MockitoBean private GameSessionClient gameSessionClient; + + @Test + 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); + 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/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/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..11f2a47a53 --- /dev/null +++ b/services/world-management-service/src/test/java/unit/net/firedevops/firemud/worldmanagement/repository/InitialAdmissionBindHoldRepositoryTest.java @@ -0,0 +1,125 @@ +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; +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 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; + +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]); + } + + @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( + 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..9472f91fb1 --- /dev/null +++ b/services/world-management-service/src/test/java/unit/net/firedevops/firemud/worldmanagement/service/impl/InitialAdmissionBindHoldReconcilerTest.java @@ -0,0 +1,274 @@ +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; +import org.junit.jupiter.api.Test; +import org.mockito.Mockito; +import org.springframework.beans.factory.ObjectProvider; +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()) { + 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(SimpleMeterRegistry.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, 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( + "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", + diagnosticExpiresAt, + null, + null, + null, + null, + reconciliationError, + 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 new file mode 100644 index 0000000000..f23515e255 --- /dev/null +++ b/services/world-management-service/src/test/java/unit/net/firedevops/firemud/worldmanagement/service/impl/InitialAdmissionBindHoldServiceImplTest.java @@ -0,0 +1,513 @@ +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.assertNotNull; +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.Clock; +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; +import org.springframework.context.annotation.AnnotationConfigApplicationContext; + +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 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<>(); + 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, 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, "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, REQUEST_DIGEST, 2L)); + + 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, REQUEST_DIGEST), + invocation.getArgument(3)); + persisted.set(committed); + return Optional.of(committed); + }); + + var first = + service.reconcileOwnerProof(HOLD_ID, ownerProof(Outcome.COMMITTED, true, REQUEST_DIGEST)); + var retry = + service.reconcileOwnerProof(HOLD_ID, ownerProof(Outcome.COMMITTED, 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, 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, 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()); + } + + @Test + void abortedTombstoneRejectsPointerAuditRequestDigest() { + 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, true, REQUEST_DIGEST)); + + 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 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, + 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 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, + 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, + pointerVersion, + auditDigest, + 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..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 @@ -6,8 +6,11 @@ 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.times; import static org.mockito.Mockito.verify; import static org.mockito.Mockito.when; @@ -29,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; @@ -42,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; @@ -159,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, @@ -181,11 +205,43 @@ 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()); + assertEquals(0L, storedInstance.get().getRowVersion()); 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 @@ -285,6 +341,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 +510,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 +680,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 -> { @@ -653,6 +746,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 fbfd3d491d..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 @@ -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,182 @@ 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()); + + 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); + } + + @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");