diff --git a/design/architecture/microservices/game-session-service/api-contracts.md b/design/architecture/microservices/game-session-service/api-contracts.md index 849c2c366a..44ed3630df 100644 --- a/design/architecture/microservices/game-session-service/api-contracts.md +++ b/design/architecture/microservices/game-session-service/api-contracts.md @@ -119,6 +119,8 @@ The internal front-end to lease-owner path is a **target-state** fenced gameplay **Target state:** Gameplay admission uses `JOIN_REQUIRED` only as a next-step response when fresh authority confirms that the selected target is publicly visible and public-production joining is allowed, while the caller's membership is absent or `INACTIVE` under [Account's explicit membership lifecycle](../../decisions/adr-0025-explicit-open-enrollment-membership.md#decision). A public-production policy denial remains `PUBLIC_PRODUCTION_ADMISSION_DENIED`; unavailable, stale, malformed, or ambiguous authority uses the applicable unavailable or invalid-authority outcome instead. Private/playtest admission always requires an existing caller-bound membership, the current membership authority generation, and the applicable Account-owned realm grant; a grant never replaces membership. **Current implementation:** text `PLAY` also returns `JOIN_REQUIRED` when a membership exists but `gameplayAdmissionAllowed=false`. It enforces the current non-public realm grant, while current connect-token issuance does not validate that grant; target connect-token issuance adds the same fresh grant gate. +- **Admission-pointer CAS inputs:** existing-row writes compare the exact `expectedPointerVersion` and `expectedCatalogRevision` pair. The current owner-local no-record insert requires `0/0` as its expected-absent precondition; because no row exists to version-check, insert-race safety comes from runtime-target locking and database uniqueness constraints, not a row-version CAS. Neither condition is proof of realm/catalog initialization or permission to create a pointer. The `SetAdmissionPointer` and `ExecutePreparedVersionCutover` control-plane RPCs remain fail-closed until their complete owner contracts are supported. Initial admission still requires the separate World lifecycle, canonical realm/catalog identity, pointer/audit transaction, and exact owner-readback proof described in [Initial admission bind](#initial-admission-bind). + ### ADR-0048 operator-write contract **Target state:** every mutating operator RPC listed above (`StartSession`, `StopSession`, `RestartSession`, `ToggleFeatureFlag`, `PauseTicksForScope`, `ResumeTicksForScope`, `SetAdmissionPointer`, `ExecutePreparedVersionCutover`, and `PrepareVersionUpgrade`) requires the same durable request identity: `controlPlaneRequestId` plus the canonical `mutationDigest`. Account binds both values into the bounded operator authorization reference, and Game Session recomputes and validates the digest before execution. The owner durably records the request before execution and records a terminal result only after owner-specific commit proof; PostgreSQL-owned mutations commit domain state and result atomically, while Redis-backed projections use the durable claim, fenced mutation marker, and reconciliation contract in ADR 0048. A duplicate request carrying the same digest returns the previously committed result, while the same request identifier with a different digest returns `IDEMPOTENCY_CONFLICT` without applying either payload. A timeout must not create a new request identifier; Logging & Admin may use that identifier only for owner result lookup until the exact operation is reconciled. `FENCE_REJECTED` is non-rearmable and prohibits mutation redelivery. A retry against a current owner or fence is permitted only after the owner has durably recorded terminal `NOT_EXECUTED` proof for the original attempt; it uses a new `ownerMutationId` and a newly fenced attempt while retaining the external request tuple. After authorization expiry, reconciliation is read-only. diff --git a/design/architecture/microservices/logging-admin-service/api-contracts.md b/design/architecture/microservices/logging-admin-service/api-contracts.md index 2acb2050f8..7ca506ddb7 100644 --- a/design/architecture/microservices/logging-admin-service/api-contracts.md +++ b/design/architecture/microservices/logging-admin-service/api-contracts.md @@ -8,7 +8,9 @@ The canonical Account-to-Logging & Admin audit ingress is the existing `logging_ Target `CreateLogEventRequest` carries `scope` (`platform` or `tenant`), `tenantId` only for `tenant` scope and never for `platform` scope, stable `auditEventId` generated and persisted by Account, `producerService`, `eventType`, producer `occurredAt`, positive `schemaVersion`, exact UTF-8 `payload`, `payloadDigestVersion` exactly `1` until a later canonical digest-version registry is accepted, and `payloadDigest`. Global registration, `account_security_lock`, `platform_access_ban`, recovery, and suspicious-activity events use `platform` scope with no `tenantId`; tenant profile and JOIN events use `tenant` scope with the exact committed `tenantId`. Unsupported digest versions fail before deduplication or persistence. `producerService` is derived from the authenticated Account workload identity and a mismatching request value is rejected. An upstream producer domain-event digest, when present inside `payload`, remains opaque payload evidence and is distinct from the receiver's `payloadDigest`. `payloadDigest` is `sha256:` followed by 64 lowercase hexadecimal characters over the exact UTF-8 payload bytes under `payloadDigestVersion=1`; no JSON reserialization or alternate canonicalization is permitted. Retry equivalence is the complete immutable `(scope, tenantId-if-tenant, auditEventId, producerService, eventType, occurredAt, schemaVersion, payloadDigestVersion, payloadDigest, exact payload bytes)` tuple: while exact payload bytes remain retained, an exact match returns the original receipt, while any changed field or payload bytes fails closed as `IDEMPOTENCY_CONFLICT`. After the safe watermark permits payload minimization, the retained identity and metadata may still detect a changed non-payload field, but the receiver must not claim exact payload equality or replay; a matching late request is a terminal non-replayable result. Timeout, transport failure, or an ambiguous response is not success; the producer retries or reconciles with the same identity and digest and never mints a replacement event. -`CreateLogEventResponse` returns `scope`, the matching `tenantId` only for tenant scope, `auditEventId`, stable receiver-generated `receiptId`, receiver `logEventId`, `schemaVersion`, `payloadDigestVersion`, `payloadDigest`, `status`, and `outcome`. The durable envelope/receipt stores and exact-compares the complete immutable tuple and exact payload bytes defined above while they are retained, and exposes the receipt fields for readback. Its status/outcome vocabulary is `COMMITTED/ACCEPTED` for the first durable write, `COMMITTED/DUPLICATE` for an exact retry before minimization, `MINIMIZED/NON_REPLAYABLE` for a matching request after payload minimization, and `CONFLICT/IDEMPOTENCY_CONFLICT` for a mismatch proven by retained metadata. `MINIMIZED/NON_REPLAYABLE` is a successful typed domain result, so both `CreateLogEvent` and `ReadLogEventReceipt` return gRPC status `OK` with only the bounded digest-only receipt metadata; they do not return payload bytes, claim exact payload equality, or create a replacement identity. The concrete readback is `logging_admin.v1.LoggingAdminService/ReadLogEventReceipt`, whose request carries the same complete tuple and whose response is `ReadLogEventReceiptResponse` with the same receipt fields. Before minimization, an exact readback returns `OK` with `COMMITTED/DUPLICATE` or the original terminal result; after minimization, an exact identity/digest read returns `OK` with `MINIMIZED/NON_REPLAYABLE`. A missing receipt returns canonical non-OK gRPC status `NOT_FOUND`; receiver/dependency unavailability returns canonical non-OK gRPC status `UNAVAILABLE`; neither is an empty typed success. Authorization is a workload-only method: the receiver derives the exact `account-service` mTLS identity, requires the `CreateLogEvent` or `ReadLogEventReceipt` method-specific allowlist entry, and accepts no bearer token or `AdminRole` in that path. The current proto now declares the target envelope and receipt fields, but the `CreateLogEvent` handler remains a fail-closed `AdminRoleGuard` placeholder that returns `UNAVAILABLE` to authorized callers without dispatch, `ReadLogEventReceipt` has no handler, and the target mTLS-only receiver, durable receipt/readback, and runtime proof remain unavailable as separate #2848 work. +`CreateLogEventResponse` returns `scope`, the matching `tenantId` only for tenant scope, `auditEventId`, stable receiver-generated `receiptId`, receiver `logEventId`, `schemaVersion`, `payloadDigestVersion`, `payloadDigest`, `status`, and `outcome`. The durable envelope/receipt stores and exact-compares the complete immutable tuple and exact payload bytes defined above while they are retained, and exposes the receipt fields for readback. Its status/outcome vocabulary is `COMMITTED/ACCEPTED` for the first durable write, `COMMITTED/DUPLICATE` for an exact retry before minimization, `MINIMIZED/NON_REPLAYABLE` for a matching request after payload minimization, and `CONFLICT/IDEMPOTENCY_CONFLICT` for a mismatch proven by retained metadata. `MINIMIZED/NON_REPLAYABLE` is a successful typed domain result, so both `CreateLogEvent` and `ReadLogEventReceipt` return gRPC status `OK` with only the bounded digest-only receipt metadata; they do not return payload bytes, claim exact payload equality, or create a replacement identity. The concrete readback is `logging_admin.v1.LoggingAdminService/ReadLogEventReceipt`, whose request carries the same complete tuple and whose response is `ReadLogEventReceiptResponse` with the same receipt fields. Before minimization, an exact readback returns `OK` with `COMMITTED/DUPLICATE` or the original terminal result; after minimization, an exact identity/digest read returns `OK` with `MINIMIZED/NON_REPLAYABLE`. A missing receipt returns canonical non-OK gRPC status `NOT_FOUND`; receiver/dependency unavailability returns canonical non-OK gRPC status `UNAVAILABLE`; neither is an empty typed success. Authorization is a workload-only method: the receiver derives the exact `account-service` mTLS identity, requires the `CreateLogEvent` or `ReadLogEventReceipt` method-specific allowlist entry, and accepts no bearer token or `AdminRole` in that path. + +At this stage, `CreateLogEvent` returns gRPC `UNIMPLEMENTED` before request validation or dispatch, and `ReadLogEventReceipt` has no handler. The target workload-only mTLS/method-allowlist receiver, durable receipt/readback, and runtime proof remain unavailable; the target contract is not an implementation claim. The receipt retention class and cleanup owner are defined in [Logging & Admin Runtime and Data](./runtime-and-data.md#audit-envelope-and-receipt-retention). @@ -24,12 +26,13 @@ Routine rollback is expected to leave ordinary gameplay available while scoped A ## Implementation Status -- Feature-flag toggles and scoped tick-remediation pause/resume ingress routes now hard fail closed as unavailable operator mutations until the minimum three-part schema/authorization gate exists: their action-family schemas, shared cross-language `mutationDigest/v1` golden vectors, and Account-issued authorization-reference issuance plus redemption by the receiving authoritative owner. This minimum gate is necessary but not sufficient for live-success support; supported execution also requires the complete durable, idempotent, fenced owner-mutation contract in [ADR 0048](../../decisions/adr-0048-durable-idempotent-operator-write-execution.md), including durable intent/audit, stable digest-bound request identity, authoritative-owner state, safety/recovery gates, and durable acknowledgement. The HTTP entrypoints preserve authentication, authorization, and basic request validation, then return `503 Service Unavailable` with stable action-specific unavailable error codes (`FEATURE_FLAG_TOGGLE_UNAVAILABLE` or `TICK_REMEDIATION_UNAVAILABLE`) without invoking a service, owner, or audit dependency. The internal `ToggleFeatureFlag` gRPC entrypoint preserves admin-role, positive-tenant, and feature-name validation, then returns an application-level `UNAVAILABLE` error without dispatch. No Logging & Admin feature-flag or tick forwarding method remains callable internally. Admission-pointer reads, audit, and prepared-upgrade proof reads remain live. Public POST/operator mutation routes under `/admission-pointers`, `/cutover`, or `/version-upgrades` are target-only absent: no public HTTP handlers or Gateway write forwarding exist. Internal preparation/cutover service and control-plane implementation remains behind internal trust boundaries, and there is no current UI control. +- Account-to-Logging audit delivery remains partial in this reconstruction: typed `CreateLogEvent` returns gRPC `UNIMPLEMENTED` and never invokes the legacy generic `log_events` writer. The typed receipt receiver implementation and focused proof are owned by [#2848](https://github.com/benhook1013/FireMUD/pull/2848) and are not integrated in this revision; the target contract above is unchanged. Account's post-commit best-effort delivery path does not establish receiver durability or receipt confirmation. +- Feature-flag toggles and scoped tick-remediation pause/resume ingress routes now hard fail closed as unavailable operator mutations until the minimum three-part schema/authorization gate exists: their action-family schemas, shared cross-language `mutationDigest/v1` golden vectors, and Account-issued authorization-reference issuance plus redemption by the receiving authoritative owner. This minimum gate is necessary but not sufficient for live-success support; supported execution also requires the complete durable, idempotent, fenced owner-mutation contract in [ADR 0048](../../decisions/adr-0048-durable-idempotent-operator-write-execution.md), including durable intent/audit, stable digest-bound request identity, authoritative-owner state, safety/recovery gates, and durable acknowledgement. The HTTP entrypoints preserve authentication, authorization, and basic request validation, then return `503 Service Unavailable` with stable action-specific unavailable error codes (`FEATURE_FLAG_TOGGLE_UNAVAILABLE` or `TICK_REMEDIATION_UNAVAILABLE`) without invoking a service, owner, or audit dependency. The internal `ToggleFeatureFlag` gRPC entrypoint preserves admin-role, positive-tenant, and feature-name validation, then returns an application-level `UNAVAILABLE` error without dispatch. No Logging & Admin feature-flag or tick forwarding method remains callable internally. Admission-pointer reads, audit, and prepared-upgrade proof reads remain live. The current-pointer list forwards only the caller's authorized tenant scopes; an empty owner request remains reserved for global platform administrators and moderators. Each current pointer in the selected scope requires exact latest-audit identity/catalog evidence, and unavailable authority in that scope returns `503`. Public POST/operator mutation routes under `/admission-pointers`, `/cutover`, or `/version-upgrades` are target-only absent: no public HTTP handlers or Gateway write forwarding exist. Internal preparation/cutover service and control-plane implementation remains behind internal trust boundaries, and there is no current UI control. - Availability vocabulary is explicit: **implemented-but-externally-gated** means an executable public controller/owner path exists but the shared mutation gate is incomplete; **target-only absent** means no executable public route exists. Admission-pointer mutation, version-upgrade preparation, and prepared cutover use the latter classification at public HTTP ingress even though internal preparation/cutover implementation remains. Quota-override ingress is also target-only absent. No generic tick-remediation payload or reserved `remediate` route is part of the target; each future recovery operation requires a named typed contract implemented by its authoritative workflow owner. - No forwarded owner mutation is currently supported as a live Logging & Admin capability until its minimum schema/authorization gate and the complete durable, idempotent, fenced owner-execution contract in [ADR 0048](../../decisions/adr-0048-durable-idempotent-operator-write-execution.md) are implemented and proved. The service-local `POST /moderation/actions` endpoint and `ApplyModerationAction` gRPC path now hard fail closed after their narrow tenant/admin checks: HTTP returns `503 Service Unavailable`, gRPC returns an application-level `UNAVAILABLE` error, and neither path dispatches or persists the generic legacy `moderation_actions` row. They remain unsupported, nonconformant implementation drift and must not be wired or called as available mutations; separate fixed-category policy/audit evidence and owner enforcement state are absent, and they are not Gateway-forwarded or supported at external ingress. In the target local workflow, once its applicable schema/authorization and local durable intent/audit requirements are implemented, Logging & Admin records durable intent/case/audit evidence and redeems its one Account reference exactly once; it never forwards that reference or performs owner enforcement. A future typed owner-enforcement command uses a separately issued reference redeemed by its receiving owner. Game Session and Social & Groups synchronously consume the live `EvaluateModerationPolicy` read at the `GAMEPLAY_ADMISSION` and `CHAT_SEND` enforcement boundaries, but that evaluation does not make the legacy action route live. Fixed-category owner commands, monotonic owner state, bounded appeals, and broader policy coverage are not implemented. Existing Game Session `/sessions*` lifecycle routes are current owner-local hooks, not a complete external Logging & Admin route family. Separate current read and investigation surfaces include the PostgreSQL-backed log query, saga reads, metrics, and owner/control-plane reads; profile-aware indexed or console/journal query integration and embedded dashboard endpoints remain target-only and unimplemented. - Current `POST /logs/query` and `QueryLogs` read only the service-owned PostgreSQL `log_events` table. They require an exact tenant and apply case-insensitive containment to the stored message, returning the matching messages. They do not query deployed structured logs, mirror data to Elasticsearch, prove the ADR 0162 emitter-to-query path, implement a compatible indexed or console/journal profile, or expose Kibana/Grafana embedding. - The current moderation proto's `scope` and `action` fields are unrestricted strings, which is drift from ADR 0141's closed typed target rather than permission to accept arbitrary categories. Converged moderation ingress must validate the closed-category, typed-scope vocabulary and reject unknown values, `account_security_lock`, and its aliases before persistence. Only Account-owned security policy and recovery may create, extend, expire, remove, or clear `account_security_lock`; the moderation action route cannot create or clear it. `EvaluateModerationPolicy` remains a live read and carries no mutation authorization reference. -- Live admission-pointer reads, audit, and prepared-upgrade proof reads are part of the core operator/control-plane availability model and must not depend on observability backends. Admission-pointer mutation and preparation handlers are absent from public HTTP ingress and OpenAPI; their internal service/control-plane implementation must not be described as current live operator mutation support. +- Admission-pointer reads, audit, and prepared-upgrade proof reads are part of the core operator/control-plane availability model and must not depend on observability backends. `GET /admission-pointers` returns unavailable when a current pointer lacks matching latest audit identity/catalog evidence; historical audit remains a raw read that preserves unknown legacy identity. Admission-pointer mutation and preparation handlers are absent from public HTTP ingress and OpenAPI; their internal service/control-plane implementation must not be described as current live operator mutation support. - The internal `SetAdmissionPointerRequest` DTO omits `actorPrincipal`. `AdmissionPointerServiceImpl` derives the actor from the authenticated internal caller context and writes that derived value to the control-plane request; `actorPrincipal` is response/audit data, not client-supplied write authority. - Public administrative report persistence is currently unavailable. The unsafe controller that formerly occupied `POST /reports` and its `/api/admin/reports/**` Gateway exposure have been removed because the canonical role- and purpose-scoped authorization and live reference-validation checks are not implemented. Any restored administrative surface uses the distinct `POST /admin/reports` service path. `POST /reports` is reserved for the separate player-bootstrap submission contract and must bind the `player-bootstrap` subject and live tenant membership; it must not be inferred from or share the unavailable administrative route. The internal `CreateReport` gRPC contract is not public HTTP or player ingress, but its target exact workload/method authorization is unproved: current transport mTLS alone does not establish an allowlisted receiver identity. The interim receiver requires an internal-service JWT naming `social-groups-service`, while certificate-derived exact workload/method authorization remains unproved. Caller-supplied tenant, reporter, and optional target identities are data references only. - `ApplyModerationAction` has an implementation path, but `/moderation/actions` plus the gRPC action now hard fail closed after narrow tenant/admin checks. HTTP returns `503 Service Unavailable`, gRPC returns an application-level `UNAVAILABLE` error, and neither path dispatches or persists the generic legacy `moderation_actions` row. They remain unsupported/nonconformant drift, not available mutation support. The target gate requires the action-family schema, shared cross-language `mutationDigest/v1` vectors, Account authorization-reference issuance, and receiving-boundary validation/redemption. Separate fixed-category policy/audit evidence and owner enforcement are absent, and no forwarding occurs. Target behavior is Logging & Admin intent/case/audit persistence followed by exactly-once redemption of its local Account reference; that reference is never forwarded. A separate future owner-enforcement command has its own Account reference and receiving-owner redemption. The separate live `EvaluateModerationPolicy` contract supplies synchronous decisions consumed by Game Session at `GAMEPLAY_ADMISSION` and Social & Groups at `CHAT_SEND`; that compatibility read is a legacy, deny-only lookup over generic action rows ordered by recency, is nonconformant with ADR 0141's broadest-effect response precedence (`platform_access_ban` over `account_security_lock`, `chat_ban` over `chat_mute`), and does not implement or prove all five fixed categories or their independent lifecycles. It is not operator mutation support. Fixed-category owner-local enforcement, bounded appeals, and broader coverage remain target work under [Moderation Policies](./moderation-policies.md). @@ -65,7 +68,7 @@ The interim legacy numeric pin-read contract must also remain exact across JavaS - The service-local route `/moderation/actions` is an unavailable/gated human mutation and is not Gateway-forwarded or supported at external ingress until its action-family schema, shared cross-language `mutationDigest/v1` golden vectors, Account authorization-reference issuance, and Logging & Admin validation/redemption exist. Current behavior hard fails closed after narrow tenant checks without dispatch or persistence; separate fixed-category policy/audit evidence and owner enforcement are absent, and no Gateway route forwards it. Target behavior records and redeems the local Logging & Admin intent/audit mutation with one Account reference; that reference is never forwarded. A separate future typed owner-enforcement command has its own request identity/digest and Account reference, redeemed by the receiving owner. They separately consume the synchronous `EvaluateModerationPolicy` result at `GAMEPLAY_ADMISSION` and `CHAT_SEND` while the target command path remains unimplemented. - `GET /sagas` – list Logging & Admin-local Saga instances; this is not platform-wide adopter aggregation. Returns `503 SAGA_DASHBOARD_UNAVAILABLE` when the conditional Saga/database beans are unavailable. - `GET /sagas/{id}/steps` – inspect steps for a known Logging & Admin-local Saga instance. An unknown instance returns `404 NOT_FOUND`; a known instance with no steps returns `200` with an empty list. Returns `503 SAGA_DASHBOARD_UNAVAILABLE` when the conditional Saga/database beans are unavailable. -- `GET /admission-pointers` – list the caller-visible Game Session route records joined with their separately revisioned catalog/policy projection, including `OPEN`/`CLOSED`, the route version, and the explicit public-production policy used by admission and first-join membership creation. +- `GET /admission-pointers` – list the caller-visible Game Session route records joined with their separately revisioned catalog/policy projection, including `OPEN`/`CLOSED`, the route version, and the explicit public-production policy used by admission and first-join membership creation. The list is available only while each current pointer's latest audit row exactly matches its catalog revision, `realmId`, and playable-state namespace; unavailable or incomplete current authority returns HTTP 503. Historical audit reads preserve unknown legacy identity fields. See the [current implementation and proof status](../../../project-management/implementation-tracking/game-session-runtime-and-tick-coordination.md#operator-readback-and-facade-boundaries). - `GET /admission-pointers/{tenantId}/{worldSlug}/{realmSlug}/audit` – read the append-only cutover audit history for one gameplay realm pointer, using the same canonical `{tenantId, worldSlug, realmSlug}` key as admission authority itself instead of inferring tenant ownership from world/realm selectors after the read. - Realm display, visibility, and public-production policy mutations use a separately revisioned catalog/policy control-plane surface; they must not be smuggled through a route mutation or invalidate active gameplay merely by changing presentation metadata. - Admission-pointer mutation, version-upgrade preparation, and prepared-cutover execution are target-only absent public HTTP/operator capabilities under `/admission-pointers`, `/cutover`, and `/version-upgrades`: they have no public HTTP handlers or Gateway write forwarding. Internal preparation/cutover service and control-plane implementation remains available only behind internal trust boundaries, and there is no current UI control. @@ -106,9 +109,11 @@ For every forwarded owner mutation, excluding the separate local `/moderation/ac The internal admission-pointer service/owner paths represent exactly one of two same-target Game Session control-plane operations for `{tenantId, worldSlug, realmSlug}`. These CAS operations and version-upgrade preparation are not public HTTP or OpenAPI capabilities; the supported public boundary is limited to admission-pointer reads, audit, and prepared-upgrade proof reads. +The current internal `SetAdmissionPointer` and `ExecutePreparedVersionCutover` request adapters carry both `expectedPointerVersion` and `expectedCatalogRevision`, forwarding the pair to Game Session. Game Session owns the exact comparison and expected-absent semantics; see the admission-pointer CAS inputs in its [gRPC contract](../game-session-service/api-contracts.md#grpc-apis). This request shape does not make either mutation available at public HTTP ingress or enable the complete owner write contracts. + - `OpenAdmissionPointer` performs `CLOSED -> OPEN(target)`. The target must exist, belong to `tenantId`, and be the prepared/active runtime for the same world and realm. It must pass current runtime lifecycle and entitlement/admission checks; display names, slugs, or a caller-supplied instance id are not proof of that relationship. If validation is unavailable or ambiguous, the operation fails closed. `preparedVersionUpgradeId` is forbidden because this operation cannot replace an already open target. - `CloseAdmissionPointer` performs `OPEN(target) -> CLOSED`. Game Session first checks the idempotency record for `controlPlaneRequestId`: an exact completed duplicate replays its original successful response and audit identity before current pointer-state validation. For a new request ID, the request must identify the exact currently open `gameInstanceId`; a missing pointer, already closed pointer, or different current target fails without mutation. Reusing a completed request ID with a different digest conflicts. Closing is a safety operation and therefore does not require the target to remain lifecycle- or entitlement-admissible. It cannot select a replacement target, and `preparedVersionUpgradeId` is forbidden. The resulting pointer makes no `gameInstanceId` gameplay-admissible while preserving the former target in audit evidence. -- Both requests carry the complete routing identity, target `gameInstanceId`, expected route version (`expectedPointerVersion`), reason, and idempotent `controlPlaneRequestId`. The schema does not accept a client-supplied actor: the actor is derived server-side from the authenticated operator session or workload. The response and audit record expose that actor and the resulting monotonic `pointerVersion`. `pointerVersion` is the route version and CAS token for exactly `{tenantId, worldSlug, realmSlug}`. The write succeeds only when the stored version equals the expected version; otherwise it returns a conflict and leaves the route unchanged. An absent route record uses `expectedPointerVersion=0` for the first open rather than an unscoped blind write. +- Both requests carry the complete routing identity, target `gameInstanceId`, expected CAS pair (`expectedPointerVersion` and `expectedCatalogRevision`), reason, and idempotent `controlPlaneRequestId`. For an existing pointer, both expected revisions must match; creating an absent pointer requires the explicit `0/0` pair. The schema does not accept a client-supplied actor: the actor is derived server-side from the authenticated operator session or workload. The response and audit record expose that actor and the resulting monotonic `pointerVersion`. `pointerVersion` is the route version and CAS token for exactly `{tenantId, worldSlug, realmSlug}`. A mismatch returns a conflict and leaves the route unchanged. - Replacing or rolling back `OPEN(old)` to `OPEN(new)` is a prepared cutover, not a generic open. It must use the internal `ExecutePreparedVersionCutover` control-plane operation with one durable `preparedVersionUpgradeId`; that operation revalidates the preparation, source and target identities, and CAS version before atomically swapping the route. Preparation is proof for cutover, not a substitute for route-version concurrency control. - Game Session remains the sole routing-state writer and audits the transition under the same identity and CAS result. Internal callers must not maintain a competing pointer or infer `tenantId` from `worldSlug` or `realmSlug`; Logging & Admin's public REST surface reads the resulting state and audit evidence only. diff --git a/design/architecture/microservices/logging-admin-service/runtime-and-data.md b/design/architecture/microservices/logging-admin-service/runtime-and-data.md index f58464631b..52a4809b29 100644 --- a/design/architecture/microservices/logging-admin-service/runtime-and-data.md +++ b/design/architecture/microservices/logging-admin-service/runtime-and-data.md @@ -31,7 +31,7 @@ The current shipped scope is narrower than this target contract: - The service exposes core admin investigation reads, saga inspection of Logging & Admin-local rows only, coordination-health reads, and a narrow log query whose current implementation reads only the service-owned PostgreSQL `log_events` table for an exact tenant plus case-insensitive message containment. Saga inspection does not aggregate adopter-local state; target cross-owner visibility requires owner read APIs plus a bounded aggregation/read model and must distinguish an unknown or unavailable adopter from an empty result. Moderation policy-input and report-persistence paths are only unsupported legacy transport/internal seams that hard fail closed or remain authorization-unproved; they are not exposed current capabilities. The service does not implement the target profile-aware indexed or console/journal query integrations, Kibana/Grafana clients, embedded dashboards, separate admin UI, or the complete target control-plane workflow for every recovery, regional, or aggregate operation. - The moderation policy-input and audit persistence mutation has present legacy transport stubs through `POST /moderation/actions` and the internal `ApplyModerationAction` gRPC ingress; after narrow tenant/admin checks they hard fail closed with HTTP `503 Service Unavailable` or an application-level gRPC `UNAVAILABLE` error, without dispatch or persistence. They are unsupported, nonconformant implementation drift and must not be wired or called as available mutations. They do not provide the target fixed-category policy-input/audit record or Account, Game Session, or Social & Groups enforcement state. Current execution performs no Account authorization-reference issuance or redemption, owner forwarding, or owner enforcement. Once its action-family schema, shared cross-language `mutationDigest/v1` golden vectors, Account authorization-reference issuance, and Logging & Admin receiving-boundary validation/redemption are complete, Logging & Admin redeems the separate intent-persistence reference exactly once at its receiving boundary; that reference is never forwarded or reused and the path does not require owner-side authorization-reference redemption or enforcement. Any future owner-enforcement command uses a separately issued reference redeemed once by its receiving owner. The separate `EvaluateModerationPolicy` compatibility read remains live at the owner enforcement boundaries and carries no mutation authorization reference. Public administrative report persistence at `POST /admin/reports` is unavailable: the HTTP controller and Gateway route were removed because canonical authorization and live reference validation are not implemented. The internal `CreateReport` gRPC ingress is not public; its interim receiver guard requires an internal-service JWT naming `social-groups-service`, which the Social & Groups client emits, while certificate-derived exact workload/method authorization remains unproved. The reserved player-bootstrap `POST /reports` submission route is separate and also unavailable until its caller-bound subject and live tenant-membership checks exist. -- Admission-pointer reads, audit, and prepared-upgrade proof reads are implemented and live. Internal admission-pointer mutation, version-upgrade preparation, and prepared-cutover owner paths have implementation-participating surfaces, but the current pointer writer is read-then-write/nonconformant; the target atomic open/close CAS and prepared cutover remain unimplemented and externally unavailable behind internal trust boundaries, with public HTTP/Gateway write support unavailable and no current UI control. Target-only absent is reserved for operations with no executable owner path at all, such as quota-override mutations or future named typed recovery actions whose owner contracts do not yet exist. +- Admission-pointer reads, audit, and prepared-upgrade proof reads are implemented and live. Game Session's owner-local pointer persistence primitive now uses a row-locked dual-revision CAS and atomically persists the pointer and audit event. This primitive does not establish the complete operator write contracts: the `SetAdmissionPointer` and `ExecutePreparedVersionCutover` control-plane RPCs remain fail-closed, the target atomic open/close workflow and prepared cutover remain unsupported, and public HTTP/Gateway write support and UI controls remain unavailable. Version-upgrade preparation remains an internal owner path, not a public HTTP capability. Target-only absent is reserved for operations with no executable owner path at all, such as quota-override mutations or future named typed recovery actions whose owner contracts do not yet exist. - **Implemented but externally gated:** The per-instance tick pause/resume ingress is declared at the `` boundary, not a claim of live admin UI or automation, and no Logging & Admin forwarding method is callable. Its minimum schema/authorization gate is the action-family schema, shared cross-language `mutationDigest/v1` golden vectors, Account authorization-reference issuance, and exact owner-side redemption/authentication and scope binding. That minimum gate only establishes that a typed request can be authorized for admission; it is not the complete execution contract. A forwarded tick mutation also remains unavailable until ADR 0048's complete durable, phase-qualified intent and authorization record, canonical `postAuthorizationExecutionTuple`, owner durable idempotency/result record, current owner/gameplay fence, and fenced no-accept/no-commit reconciliation proof are implemented and proved. Regional pause/resume and named regional recovery actions remain target-only behavior, with no claim that the target instance contract implicitly expands to a region or aggregate scope; they are tracked in [Game Session runtime and tick coordination](../../../project-management/implementation-tracking/game-session-runtime-and-tick-coordination.md#capability-status). - Logging & Admin consumes Game Session health and requests Game Session-owned control APIs; it does not directly mutate Redis or runtime coordination state. - Moderation policy intent, fixed-category case/audit data, bounded appeal cases/evidence, and operator history remain owned here, while Account, Game Session, and Social & Groups enforce their respective local restriction state. Active [ADR 0146](../../decisions/adr-0146-owner-local-moderation-enforcement.md) (mapped from reviewed archive record `archive-ADR-0133`) is the owner-local authority outcome: one typed digest-bound command reaches the enforcement owner, which commits monotonic local state, and routine boundary reads do not call Logging & Admin. Quota/limit override is hypothetical target UX only; no current Account owner mutation route exists. The legacy policy-input/audit transport stubs now hard fail closed before dispatch or persistence; they do not persist target fixed-category policy input or audit evidence, represent a domain-owner enforcement mutation, or provide target proof. Current execution performs no Account authorization-reference redemption. The current `EvaluateModerationPolicy` read is an implementation compatibility seam, not target authority; target owner commands and bounded appeal outcomes follow [Moderation Policies](./moderation-policies.md). Once the target persistence gate is complete, Logging & Admin validates and redeems its one separate intent-persistence reference exactly once for its own persistence path; it never forwards or reuses that reference. Future receiving enforcement owners redeem separately issued command-bound Account references and retain their own state. diff --git a/design/architecture/service-responsibility-matrix.md b/design/architecture/service-responsibility-matrix.md index 95ba5eaa98..963e91409b 100644 --- a/design/architecture/service-responsibility-matrix.md +++ b/design/architecture/service-responsibility-matrix.md @@ -12,7 +12,7 @@ The matrix below is the target participation and ownership contract. `Authoritat - Live external operator availability includes the Gateway edge plus Logging & Admin domain ingress for reads, investigation, admission-pointer reads/audit, and prepared-upgrade proof reads. TCP Proxy does not participate in this HTTP operator read/proof-read path. `EvaluateModerationPolicy` is a separate live internal owner-boundary read consumed by Game Session and Social & Groups, not external operator availability. The target mutation rows below are normative contracts, not claims that every listed mutation is currently routable. - The service-local `/moderation/actions` and `ApplyModerationAction` paths are present legacy transport stubs that hard fail closed after narrow tenant/admin checks, without dispatch or persistence; they are unavailable at external Gateway ingress, persist no separate fixed-category audit evidence, and perform no owner-side enforcement. The target path remains gated pending the action-family schema, shared cross-language `mutationDigest/v1` golden vectors, Account authorization-reference issuance, and Logging & Admin receiving-service validation/redemption. Synchronous `EvaluateModerationPolicy` consumption at `GAMEPLAY_ADMISSION` and `CHAT_SEND` remains a separate live owner-boundary read for Game Session and Social & Groups; those services own gameplay/chat enforcement, while Logging & Admin retains policy-input responsibility rather than consuming those enforcement decisions. -- Feature-flag overrides and scoped per-instance tick pause/resume are implemented-but-externally-gated ingress stubs pending their action-family schemas, shared cross-language `mutationDigest/v1` golden vectors, and Account-issued authorization-reference issuance/redemption flow and, where applicable, the target-only `privileged_control` issuance flow. That minimum gate is necessary but not sufficient for live success: supported owner execution also requires the complete durable, idempotent, fenced contract in [ADR 0048](./decisions/adr-0048-durable-idempotent-operator-write-execution.md). Version-upgrade preparation and admission-pointer CAS/cutover have internal implementation-participating, nonconformant preparation/read-then-write/prepared-cutover seams, but their public HTTP/operator mutation paths are target-only absent because no public route or Gateway write forwarding exists; the target atomic open/close CAS and prepared cutover remain unimplemented. Broader guarded tick enumeration, regional mutation, and reset/remediate orchestration remain target-only. +- Feature-flag overrides and scoped per-instance tick pause/resume are implemented-but-externally-gated ingress stubs pending their action-family schemas, shared cross-language `mutationDigest/v1` golden vectors, and Account-issued authorization-reference issuance/redemption flow and, where applicable, the target-only `privileged_control` issuance flow. That minimum gate is necessary but not sufficient for live success: supported owner execution also requires the complete durable, idempotent, fenced contract in [ADR 0048](./decisions/adr-0048-durable-idempotent-operator-write-execution.md). Version-upgrade preparation and admission-pointer CAS/cutover have internal implementation-participating seams; the pointer persistence primitive now checks both expected revisions under a row lock and commits pointer plus audit atomically, but public HTTP/operator mutation paths remain unavailable because no public route or Gateway write forwarding exists. Full prepared-cutover execution and target open/close behavior remain unimplemented; see the [Realm Routing implementation tracker](../project-management/implementation-tracking/realm-routing-and-playable-state.md). Broader guarded tick enumeration, regional mutation, and reset/remediate orchestration remain target-only. - Game Session `/sessions*` routes are current owner-local hooks; direct owner edge exposure is denied. The target external lifecycle ingress is `Gateway -> Logging & Admin -> Game Session` owner RPCs, but lifecycle forwarding is target-only and non-routable until its owner contract, minimum schema/authorization gate, and [ADR 0048](./decisions/adr-0048-durable-idempotent-operator-write-execution.md)'s complete durable, idempotent, fenced owner-execution contract exist. No complete current external `/sessions*` family is claimed. - Versioned moderation propagation, hypothetical quota overrides, and broader tick remediation remain target-only/non-routable coverage without current executable owner routes. They cannot be exposed through Gateway or treated as Logging & Admin forwarding routes until the owning service contract and minimum schema/authorization gate exist, together with [ADR 0048](./decisions/adr-0048-durable-idempotent-operator-write-execution.md)'s complete durable, idempotent, fenced owner-execution contract for any family that forwards to an owner. The currently supported ingress remains limited to the live reads, investigation, admission-pointer reads/audit, prepared-upgrade proof reads, and internal owner-boundary moderation evaluation listed above; this target-only status does not remove or widen those current paths. - The causal-read fence/composite room-view row is target-state only: current proto/request paths remain floor-free, and implementation/proof are unimplemented. See [ADR 0059](./decisions/adr-0059-causal-floor-cross-service-presentation-reads.md) and the [world-runtime-and-movement tracker](../project-management/implementation-tracking/world-runtime-and-movement.md) for current status. The accepted responsibility split remains Game Session allocation, Game Logic composition, and World Management/Entity Management participant provision. @@ -91,7 +91,7 @@ The matrix below is the target participation and ownership contract. `Authoritat | Authoritative owner: `versionStateEpoch` CAS enforcement | ✔ | | | | | | | | | | | | Version-state CAS API invocation for activation/rollback (`versionStateEpoch`) | ✔ | | | ✔ | | | | | ✔ | | | | Live admission-pointer reads/audit and prepared-upgrade proof reads (non-mutating; Account participates only in external read authorization, Gateway provides the edge, Logging & Admin provides domain ingress, and Game Session supplies owner state; mutation action-family schemas, `mutationDigest/v1` vectors, authorization references, and ADR 0048 owner execution are not prerequisites for these reads) | | | ✔ | ✔ | | | | | ✔ | | ✔ | -| Authoritative owner: Game Session internal version-upgrade preparation, read-then-write admission-pointer update, and prepared-cutover execution seams (nonconformant and externally gated; an action-family schema, shared cross-language `mutationDigest/v1` golden vectors, Account-issued authorization references with receiving-owner redemption, and the complete durable, idempotent, fenced owner-execution contract in [ADR 0048](./decisions/adr-0048-durable-idempotent-operator-write-execution.md) are required before any supported preparation or write execution); target atomic open/close `pointerVersion` CAS and atomic prepared-cutover commit remain unimplemented and externally unavailable | | | | ✔ | | | | | | | | +| Authoritative owner: Game Session internal version-upgrade preparation, dual-revision conditional pointer update with atomic pointer/audit persistence, and prepared-cutover execution seams (publicly unavailable; an action-family schema, shared cross-language `mutationDigest/v1` golden vectors, Account-issued authorization references with receiving-owner redemption, and the complete durable, idempotent, fenced owner-execution contract in [ADR 0048](./decisions/adr-0048-durable-idempotent-operator-write-execution.md) are required before supported external execution); target open/close `pointerVersion` CAS and atomic prepared-cutover commit remain unimplemented and externally unavailable | | | | ✔ | | | | | | | | | External version-upgrade preparation and admission-pointer open/close or prepared-cutover mutation ingress (target-only absent; the action-family schema, shared cross-language `mutationDigest/v1` golden vectors, Account-issued authorization reference and receiving-owner redemption, and complete ADR 0048 owner execution are mandatory before support; Gateway and Logging & Admin participation is target-state only, and all current mutation ingress remains unavailable) | | | ✔ | ✔ | | | | | ✔ | | ✔ | | Runtime feature-flag truth and override participation (Game Session owns runtime truth) | | | | ✔ | | | | | ✔ | | | | Tick & coordination health metrics (diagnostic scope: ``) | | | | ✔ | | | | | | | | @@ -167,7 +167,7 @@ Route-review procedure: 1. Classify the proposed route using the [canonical route-review examples and traffic split](./system-architecture-overview.md#external-admin-traffic-split-canonical). 2. Confirm the matching participation and ingress rows below; participation alone does not authorize a direct external mutation. -- The exact current matrix rows are **External operator read/proof-read ingress** and **External operator write ingress**; their current availability and drift are recorded in **Implementation Status**, while the rows remain the canonical participation contract. Version-upgrade preparation is a mutation and belongs only to the gated write-ingress row; the read row covers proof reads, not preparation writes. Admission-pointer control has internal implementation-participating read-then-write and prepared-cutover surfaces, but the target atomic open/close CAS and prepared cutover remain unimplemented and externally unavailable; its ownership row must not be read as current external support or as an absent owner contract. +- The exact current matrix rows are **External operator read/proof-read ingress** and **External operator write ingress**; their current availability and drift are recorded in **Implementation Status**, while the rows remain the canonical participation contract. Version-upgrade preparation is a mutation and belongs only to the gated write-ingress row; the read row covers proof reads, not preparation writes. Internally, the admission-pointer persistence primitive applies a row-locked conditional update against the expected pointer/catalog revision pair and commits pointer plus audit atomically. Public open/close mutation and full prepared cutover remain unavailable; see the [canonical Game Session owner contract](./microservices/game-session-service/api-contracts.md#world-lifecycle-and-admission-boundary) and [Realm Routing implementation status](../project-management/implementation-tracking/realm-routing-and-playable-state.md). - Proposed route: `POST /api/session/game-sessions/{id}/feature-flags/{flagKey}:toggle`. Matrix check: `Game Session` participates in `Admin/creator API participation`, but the **External operator write ingress** row routes this workflow through `Logging & Admin`, so the direct external Game Session route is not allowed without a design update; current availability is governed by **Implementation Status**. - Proposed route: `POST /api/design/templates`. Matrix check: `Game Design` participates in `Admin/creator API participation`, and `Bypass-safe Game Design creator writes for tenant-scoped assets and templates` delegates this domain-local creator write to the Game Design service contract, so the route may be edge-routable when Game Design documents tenant access, validation, and audit behavior. - Proposed route: `GET /api/account/accounts/{id}`. Matrix check: `Account Service` participates in `Admin/creator API participation`, and the request is an external admin read rather than an operator mutation covered by the **External operator write ingress** row, so the route may be edge-routable when the owning service documents it as a bypass-safe read contract. @@ -176,7 +176,7 @@ The moderation policy-intent row assigns target `POST /moderation/actions` polic ## Notes on Redis Ownership and Participation -- **Independent version and admission CAS domains** – Game Design Service owns the version lifecycle state and `versionStateEpoch` CAS contract used for activation and rollback. Game Session and Logging & Admin may invoke that typed lifecycle API through their documented control-plane paths, but neither owns the version epoch. Game Session owns the admission-pointer read/preparation implementation and internal pointer-write/prepared-cutover surfaces for `{tenantId, worldSlug, realmSlug}`; the current writer is read-then-write/nonconformant, while the target atomic open/close `pointerVersion` CAS and prepared cutover remain unimplemented and externally unavailable. Gateway participates at the edge for operator/proof reads and write ingress, while Logging & Admin is the domain ingress for the gated target operation. Neither edge participation nor operator ingress transfers authority from Game Session. The two CAS tokens are independent and must not be substituted for one another. +- **Independent version and admission CAS domains** – Game Design Service owns the version lifecycle state and `versionStateEpoch` CAS contract used for activation and rollback. Game Session and Logging & Admin may invoke that typed lifecycle API through their documented control-plane paths, but neither owns the version epoch. Game Session owns admission-pointer reads, preparation, and internal persistence. Canonical realm-ID addressing, explicit `CLOSED`, World hold/lifecycle fencing, and bounded drain remain gaps; see the [Realm Routing implementation tracker](../project-management/implementation-tracking/realm-routing-and-playable-state.md) and [Game Session owner contract](./microservices/game-session-service/api-contracts.md#world-lifecycle-and-admission-boundary). Gateway participates at the edge for operator/proof reads and write ingress, while Logging & Admin is the domain ingress for the gated target operation. Neither edge participation nor operator ingress transfers authority from Game Session. The two CAS tokens are independent and must not be substituted for one another. - **Authoritative owner: Coordination Redis gameplay sessions (`session:game:*`)** – Game Session Service owns gameplay session bindings, lifecycle, and reset scope expectations for these keys. Other services participate only through documented shared helper libraries and key contracts; they do not introduce new gameplay session prefixes or modify TTLs/payload semantics without Game Session ownership and Redis design review. - **Authoritative owner: Coordination Redis gameplay coordination keys (`tick:*`, generic `timer:*`, `retry:*`, `tick-executor-lease:*`, and the target-only, once-implemented Game Session-produced `tick-events:{tenantRegionTag}` stream)** – Game Session Service owns gameplay coordination schema and lifecycle for these prefixes. Generic `timer:*` excludes Automation's `automation:timer:*` and `script-scheduler:*` families. Other services participate only through documented shared helper libraries and key contracts; they do not introduce new gameplay coordination prefixes or modify TTLs/payload semantics without Game Session ownership and Redis design review. diff --git a/design/architecture/system-architecture-authz-route-matrix.md b/design/architecture/system-architecture-authz-route-matrix.md index 5c47648bb6..de1007239d 100644 --- a/design/architecture/system-architecture-authz-route-matrix.md +++ b/design/architecture/system-architecture-authz-route-matrix.md @@ -229,7 +229,7 @@ For every first public-production text entry, the target command sequence is `LO | Logging & Admin | `POST /feature-flags/toggle`, `POST /tick-remediation/pause`, `POST /tick-remediation/resume` | `tenant_regular` operator ingress | **Target; not currently routable.** Exact `control-ui` profile and current operator role. Tenant-role branches require live membership and membership-generation freshness; privileged global-role branches require live `current_global_role` and `role_appropriate_assurance`, while the global `platformAdmin` branch uses target-tenant generation without target membership. Each mutation also requires its action schema, shared `mutationDigest/v1` golden vectors, and Account authorization-reference issuance/redemption before enablement. | | Logging & Admin | `POST /moderation/actions` | `tenant_regular` operator ingress for `gameplay_ban`, `chat_mute`, and `chat_ban`; `account_scoped` platform-jurisdiction ingress for `platform_access_ban` | **Target; unavailable/gated.** The closed `action` selector selects exactly one matrix variant and rejects `account_security_lock`, unknown, and legacy values before branch authorization. Tenant-scoped categories retain the `tenant_regular` branch: `moderator`, `tenantAdmin`, and `platformAdmin` use the existing tenant membership/tenant-generation or global target-tenant-generation consequences. `platform_access_ban` uses the separate `account_scoped` branch: only global `platformAdmin` with `privileged_control`, explicit global target-account binding and platform scope, no `tenantId`, no tenant billing generation, and no membership or tenant-generation checks. Both variants link the root moderation policy-intent authorization contract: Logging & Admin redeems the local Account reference at its receiving boundary; any later owner-enforcement command uses a distinct identity/digest/reference/fingerprint and is redeemed by the selected owner. Target mutation contract: `durable_intent_then_moderation_record_idempotency`. Account remains the enforcement owner for the global restriction; target Game Session and Social & Groups enforcement reads the applicable owner-local durable restriction state or projection. **Current compatibility drift:** both consumers instead call the live `EvaluateModerationPolicy` read at their enforcement boundaries; that read is not a second target moderation authority. Owner-enforcement command coverage remains a recorded gap. | | Logging & Admin | `POST /reports` | `player_bootstrap_tenant` | **Target-only; not currently routable.** Accepts caller-bound `player-bootstrap`, derives `tenantId` and `reporterAccountId` from the authenticated caller and live membership, applies `moderation_report_policy`, and writes a caller-bound durable report record. | -| Logging & Admin | `CreateLogEvent` | `internal_workload` Account audit ingress | **Target-only; receiver and proof unavailable.** The target accepts only the exact Account Service workload mTLS identity (`spiffe://firemud/ns/{namespace}/sa/account-service`), with no bearer token or operator role. The current placeholder retains `AdminRoleGuard` denial ordering and returns `UNAVAILABLE` for authorized callers without dispatching or writing a receipt; the target receiver, PostgreSQL runtime, and direct end-to-end proof remain unavailable. | +| Logging & Admin | `CreateLogEvent` | `internal_workload` Account audit ingress | **Target-only; receiver and proof unavailable.** The target accepts only the exact Account Service workload mTLS identity (`spiffe://firemud/ns/{namespace}/sa/account-service`), with no bearer token or operator role. The current handler returns gRPC `UNIMPLEMENTED` before request validation, dispatch, or receipt writing; it does not implement the target typed Account receipt capability. The target receiver, PostgreSQL runtime, and direct end-to-end proof remain unavailable. | | Logging & Admin | `ReadLogEventReceipt` | `internal_workload` Account audit receipt readback | **Target-only; handler and proof unavailable.** The target uses the same exact Account Service mTLS-only caller boundary and no bearer token or operator role, then reads the receipt by the complete immutable envelope tuple. The current service has no read handler and returns gRPC `UNIMPLEMENTED`; receipt readback, PostgreSQL runtime, and direct end-to-end proof remain unavailable. | | Logging & Admin | `POST /admission-pointers`, `POST /admission-pointers/cutover`, `POST /admission-pointers/version-upgrades` | `tenant_regular` operator ingress | **Target; not currently routable.** This is a target inventory row only: the public OpenAPI surface no longer exposes the admission-pointer open/close/cutover mutations, and the remaining controller/owner paths are implementation drift. The `GET` read/audit/proof-read routes remain live; the `POST` preparation operation is separately gated. Exact `control-ui` profile and current operator role are required for any future ingress. Tenant-role branches require live membership and membership-generation freshness; privileged global-role branches require live `current_global_role` and `role_appropriate_assurance`, while the global `platformAdmin` branch uses target-tenant generation without target membership. Action schemas, shared `mutationDigest/v1` vectors, and Account authorization-reference issuance/redemption are required before external support; the global branch additionally requires target-only `privileged_control`. | | Game Session Service | `ToggleFeatureFlag`, `PauseTicksForScope`, `ResumeTicksForScope`, `SetAdmissionPointer`, `PrepareVersionUpgrade`, `ExecutePreparedVersionCutover` | `internal_workload` mirrored owner RPCs | **Target; not currently routable.** Exact Logging & Admin mTLS workload identity plus an Account-redeemed bounded operator authorization reference; no end-user JWT. These owner RPCs cannot be enabled until the corresponding action schema, shared `mutationDigest/v1` golden vectors, and Account authorization-reference issuance/redemption flow exist. | diff --git a/design/architecture/system-architecture-multi-tenancy.md b/design/architecture/system-architecture-multi-tenancy.md index edddbdf005..bb9a7e209e 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 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. +Implementation status and execution evidence belong in the owning trackers or PR, following the [validation and runtime proof workflow](../developer-workflows/validation-and-runtime-proof.md). Current routing, admission, account/session, and Game Session implementation and proof remain partial; see the [realm-routing tracker](../project-management/implementation-tracking/realm-routing-and-playable-state.md#current-status), [player-access tracker](../project-management/implementation-tracking/player-access-and-session.md#current-status), and [Game Session runtime tracker](../project-management/implementation-tracking/game-session-runtime-and-tick-coordination.md#current-status). These status records do not change the normative tenant, namespace, routing, and isolation contracts in this document. --- @@ -201,7 +201,7 @@ Pointer freshness and cutover rules: Migrations create tables directly inside dedicated service schemas rather than the `public` schema. - Databases are **shared across tenants**. Tenant-owned records carry and enforce `tenantId`; genuinely platform-global records such as the core account identity do not acquire a placeholder tenant merely to satisfy this convention. Relationships between a global record and a game live in explicit tenant-scoped tables. Domain services also scope their versioned data by `version_id` so multiple published or draft configurations can coexist per tenant. - Services enforce the `tenantId` filter on queries for tenant-owned data to prevent cross-game access. They do not apply tenant filters to platform-global account, credential, recovery, or security records; links between those records and a game are represented by explicit tenant-scoped relationships and authorized separately. -- Every Redis key family must use its canonical key builder and representative formats defined in the [Redis Architecture](./system-architecture-redis.md#coordination-key-examples), rather than hand-rolled strings. The target-only authenticated gameplay session family is `session:game:{tenantGameplayTag}::`, where `tenantGameplayTag` is loaded or allocated through the authoritative persisted tenant-to-tag mapping defined above; `tenantId` remains the authoritative identity and validation field. Current Game Session context remains on `sessionctx:*`. For tick-related keys, this prefix is combined with a region identifier into a single normalized region hash tag token (for example `tick:{tenantRegionTag}:lock:`). The hash tag only co-locates related keys in one Redis Cluster slot for shard-local atomic operations; it is not a tenant-isolation boundary. Tenant isolation comes from canonical key builders and owner-side tenant validation. The untagged global account active-binding index and other explicitly global families are exceptions to the physical key-prefix rule; tenant isolation for the account index is enforced by its tenant-qualified `bindingRef` members and owner-controlled validation, never by treating the global key as tenant-local authority. +- Every Redis key family must use its canonical key builder and representative formats defined in the [Redis Architecture](./system-architecture-redis.md#coordination-key-examples), rather than hand-rolled strings. The target-only authenticated gameplay session family is `session:game:{tenantGameplayTag}::`, where `tenantGameplayTag` is a deterministic, injective projection of authoritative `tenantId`, loaded from or allocated through an authoritative persisted tenant-to-tag mapping with an immutable allocation version; `tenantId` remains the authoritative identity and validation field. Existing assignments are reused, and first allocation atomically enforces uniqueness for both tenant and tag, rejecting a candidate already assigned to another tenant even across allocation versions. Encoding or version changes preserve existing mappings and apply only to future allocations; encoding and version remain opaque to clients and other services. Current Game Session context remains on `sessionctx:*`. Gameplay controller uniqueness is `{tenantId, playableStateNamespaceId, characterId}`; its binding value/evidence retains `{sessionId, gameInstanceId, bindingGeneration}`, while server-derived `playableStateScope` remains binding/routing evidence. For tick-related keys, this prefix is combined with a region identifier into a single normalized region hash tag token (for example `tick:{tenantRegionTag}:lock:`). The hash tag only co-locates related keys in one Redis Cluster slot for shard-local atomic operations; it is not a tenant-isolation boundary. Tenant isolation comes from canonical key builders and owner-side tenant validation. The untagged global account active-binding index and other explicitly global families are exceptions to the physical key-prefix rule; tenant isolation for the account index is enforced by its tenant-qualified `bindingRef` members and owner-controlled validation, never by treating the global key as tenant-local authority. - Focused proof for this boundary must demonstrate that distinct `tenantId` values produce distinct tags, a tenant's tag and allocation version remain stable across process restart, concurrent first allocation returns one persisted assignment, a candidate tag collision is rejected when another tenant owns it under a different allocation version, and the owning active-binding validator rejects a `bindingRef` from another tenant. Redis slot co-location alone is not proof of isolation. Apply the [validation and runtime-proof workflow](../developer-workflows/validation-and-runtime-proof.md) when selecting and recording this focused proof. - The React frontend loads per-tenant, version-scoped assets from a published `manifest.json` in object storage; the Game Design Service is not queried at diff --git a/design/architecture/system-architecture-overview.md b/design/architecture/system-architecture-overview.md index 24d7824cf3..437e7a628c 100644 --- a/design/architecture/system-architecture-overview.md +++ b/design/architecture/system-architecture-overview.md @@ -15,7 +15,7 @@ Replacement and authoring boundaries are likewise explicit: durable playable sta This overview is target-state canonical; implementation coverage is partial and must not be inferred from the target tables alone. The current operator-control boundary is: - Runtime feature-flag overrides and scoped tick `PauseTicks`/`ResumeTicks` have implemented Logging & Admin ingress stubs that hard fail closed; the former Logging & Admin forwarding clients/methods are removed, so no forwarding path is currently callable. Game Session retains runtime and coordination mutation authority. These owner mutations are not canonically supportable or externally enableable until the minimum schema/authorization gate and the complete durable, idempotent, fenced owner-execution contract in [ADR 0048](./decisions/adr-0048-durable-idempotent-operator-write-execution.md) exist and are consumed and proved by every participant. -- Admission-pointer reads and audit have implemented Logging & Admin paths. Live prepared-upgrade proof reads are distinct from the internal Game Session preparation handlers (`PrepareVersionUpgrade` and `ValidateInstanceCutoverCompatibility`); neither read nor preparation handler is an admission-pointer CAS/cutover mutation. Separate internal pointer-write and prepared-cutover implementation-participating surfaces exist behind internal trust boundaries but remain nonconformant and externally unavailable: the current writer is a read-then-write/separate-repository path rather than the target atomic boundary. The target atomic admission-pointer open/close CAS and prepared cutover, including explicit `CLOSED` handling, remain unimplemented and must not be read as a current external support claim. See [Versioning & Runtime Configuration](./system-architecture-versioning-runtime.md) for the canonical owner contract. +- Admission-pointer reads and audit have implemented Logging & Admin paths. Live prepared-upgrade proof reads are distinct from the internal Game Session preparation handlers (`PrepareVersionUpgrade` and `ValidateInstanceCutoverCompatibility`); neither read nor preparation handler is an admission-pointer CAS/cutover mutation. The owner-local pointer persistence primitive now checks the expected `{pointerVersion, catalogRevision}` under a row lock, conditionally updates against both prior values, and commits the pointer with its audit event in one transaction. This does not enable external pointer mutation or prove full prepared cutover: those paths remain fail-closed/unavailable, the current route remains positive-target-only rather than supporting explicit `CLOSED`, and canonical `{tenantId, realmId}` addressing plus World hold, lifecycle fencing, and bounded source drain remain gaps. See the [Realm Routing implementation tracker](../project-management/implementation-tracking/realm-routing-and-playable-state.md) for current status and [Versioning & Runtime Configuration](./system-architecture-versioning-runtime.md) for the owner contract. - Public administrative report persistence is currently unavailable. The unsafe Logging & Admin HTTP controller and `/api/admin/reports/**` Gateway route were removed because canonical authorization and live reference-validation checks are not implemented. The internal report gRPC contract remains separate behind its existing workload boundary; the target player-bootstrap submission route is also unavailable. - Moderation action persistence and audit are currently gated/unavailable: `POST /moderation/actions` and `ApplyModerationAction` are present legacy transport stubs that hard fail closed after narrow tenant/admin checks, without dispatch or persistence; separate fixed-category audit evidence and owner-side enforcement are absent, and no Gateway moderation route exposes this local REST/gRPC path. The separate `EvaluateModerationPolicy` read remains live at the Game Session and Social & Groups owner boundaries (`GAMEPLAY_ADMISSION` and `CHAT_SEND`), with applicable high-risk decisions failing closed when fresh policy evidence is unavailable. That compatibility seam is a legacy, deny-only lookup over generic action rows ordered by recency; it is nonconformant with ADR 0141's broadest-effect response precedence (`platform_access_ban` over `account_security_lock`, `chat_ban` over `chat_mute`) and does not implement or prove all five fixed categories or their independent lifecycles. For chat, that current fail-closed seam covers only new sends: the current effect replay can return before the policy read and lacks authenticated-caller and request-digest binding, so chat retry/replay remains an explicit implementation gap. Target state uses the fixed categories and owner-local durable enforcement commands defined in [Moderation Policies](./microservices/logging-admin-service/moderation-policies.md) and active [ADR 0146](./decisions/adr-0146-owner-local-moderation-enforcement.md) (mapped from reviewed archive record `archive-ADR-0133`), with lifecycle rules from [ADR 0141](./decisions/adr-0141-fixed-safety-restriction-categories-and-independent-lifecycles.md) and appeals from [ADR 0142](./decisions/adr-0142-bounded-moderation-appeal-cases.md); complete persistence, owner command delivery, enforcement, and appeal handling remain missing. - Quota override is a hypothetical target overlay on Account entitlements; no current OpenAPI route or Account owner mutation contract exists. diff --git a/design/architecture/system-architecture-versioning-runtime.md b/design/architecture/system-architecture-versioning-runtime.md index 883588f441..b14e4f8fd0 100644 --- a/design/architecture/system-architecture-versioning-runtime.md +++ b/design/architecture/system-architecture-versioning-runtime.md @@ -12,7 +12,7 @@ FireMUD's target state treats versioned publishing, release attestation, runtime ## Implementation Status -The versioned publish and replacement-cutover substrate is partially implemented, including durable cutover preparation and execution records. The current admission-pointer writer performs a read-then-write version check and persists pointer, audit, and prepared-upgrade execution changes through separate repository calls; it does not yet prove the target single-transaction compare-and-set boundary described below. Current cutover implementation drift is also explicit: it clears active bindings rather than preserving them through the target bounded source-drain sequence of a persisted deadline, World Management lifecycle fence with confirmed command rejection, one bounded notice attempt after that fence, unconditional socket closure, and terminal `InstanceTermination` workflow. Notice failure never keeps source sockets open or delays termination. Current Game Session pin reads and the live `EnqueueAutomationCommandIfAbsent` handoff now carry the script patch, positive epoch, and owner request evidence; Game Session rejects incomplete or stale tuples at handoff, while current Automation instance-bound ingress, timer, and work-item admission paths also reject same-version work from an older epoch. Append-only request-idempotent rollout history, complete source/target command identity, and remote final-effect fencing remain implementation/proof gaps; Automation rollout rows/events remain synthetic, non-authoritative projections. The target sections that follow are normative design, not proof that the current runtime already satisfies those effects. +The versioned publish and replacement-cutover substrate is partially implemented, including durable cutover preparation and execution records. The current Game Session admission-pointer persistence primitive checks the expected `{pointerVersion, catalogRevision}` under a row lock, performs an existing-row conditional update against both prior values, and commits the pointer and audit event in one transaction. This owner-local pointer/audit boundary does not make public `SetAdmissionPointer` or `ExecutePreparedVersionCutover` callable, and prepared-upgrade execution is still recorded outside the pointer transaction; the full target prepared-cutover boundary is not proved. Explicit `CLOSED`, canonical `{tenantId, realmId}` addressing, World Management hold/lifecycle fencing, and bounded source drain remain gaps. Current cutover implementation drift is also explicit: it clears active bindings rather than preserving them through the target bounded source-drain sequence of a persisted deadline, World Management lifecycle fence with confirmed command rejection, one bounded notice attempt after that fence, unconditional socket closure, and terminal `InstanceTermination` workflow. Notice failure never keeps source sockets open or delays termination. Current Game Session pin reads and the live `EnqueueAutomationCommandIfAbsent` handoff now carry the script patch, positive epoch, and owner request evidence; Game Session rejects incomplete or stale tuples at handoff, while current Automation instance-bound ingress, timer, and work-item admission paths also reject same-version work from an older epoch. Append-only request-idempotent rollout history, complete source/target command identity, and remote final-effect fencing remain implementation/proof gaps; Automation rollout rows/events remain synthetic, non-authoritative projections. The target sections that follow are normative design, not proof that the current runtime already satisfies those effects. Historical Game Design migration status is also unresolved: `V5__update_version_table.sql` dropped the legacy `version.revision_ids` relationship, and `V17__revision_version_scope.sql` later assigned each tenant's revisions to its latest version. The current lineage therefore cannot prove immutable revision/version history. This is a retained-data deployment blocker: an affected deployment must first record either a verified no-data boundary or an explicit retained-row disposition/mapping, with exact readback and revision/version lineage evidence. No recovery is implied for already-dropped arrays; future migration/proof remediation remains required, and this status does not invent a replacement lineage design. diff --git a/design/grpc-docs/grpc-api.md b/design/grpc-docs/grpc-api.md index 971894fcfe..798879e1ce 100644 --- a/design/grpc-docs/grpc-api.md +++ b/design/grpc-docs/grpc-api.md @@ -413,6 +413,8 @@ for conventions on schema evolution and error handling. See each service's - [GetGameSessionPinConvergenceResponse](#game_session-v1-GetGameSessionPinConvergenceResponse) - [GetGameplayCommandStatusRequest](#game_session-v1-GetGameplayCommandStatusRequest) - [GetGameplayCommandStatusResponse](#game_session-v1-GetGameplayCommandStatusResponse) + - [GetInitialAdmissionBindProofRequest](#game_session-v1-GetInitialAdmissionBindProofRequest) + - [GetInitialAdmissionBindProofResponse](#game_session-v1-GetInitialAdmissionBindProofResponse) - [GetPinnedScriptPatchVersionRequest](#game_session-v1-GetPinnedScriptPatchVersionRequest) - [GetPinnedScriptPatchVersionResponse](#game_session-v1-GetPinnedScriptPatchVersionResponse) - [GetPreparedVersionUpgradeRequest](#game_session-v1-GetPreparedVersionUpgradeRequest) @@ -493,6 +495,7 @@ for conventions on schema evolution and error handling. See each service's - [AccountRecentPresenceDisposition](#game_session-v1-AccountRecentPresenceDisposition) - [CutoverCompatibilityResult](#game_session-v1-CutoverCompatibilityResult) - [ExpectedCurrentPin.Kind](#game_session-v1-ExpectedCurrentPin-Kind) + - [InitialAdmissionBindOwnerProofOutcome](#game_session-v1-InitialAdmissionBindOwnerProofOutcome) - [TickStatus](#game_session-v1-TickStatus) - [GameSessionControlPlaneService](#game_session-v1-GameSessionControlPlaneService) @@ -598,6 +601,8 @@ for conventions on schema evolution and error handling. See each service's - [TcpProxyService](#tcp_proxy-v1-TcpProxyService) - [world-management/v1/world_management_service.proto](#world-management_v1_world_management_service-proto) + - [AcquireInitialAdmissionBindHoldRequest](#world_management-v1-AcquireInitialAdmissionBindHoldRequest) + - [AcquireInitialAdmissionBindHoldResponse](#world_management-v1-AcquireInitialAdmissionBindHoldResponse) - [ActivatePreparedWorldInstanceRequest](#world_management-v1-ActivatePreparedWorldInstanceRequest) - [ActivatePreparedWorldInstanceResponse](#world_management-v1-ActivatePreparedWorldInstanceResponse) - [ApplyRoomAmbientStatePatchRequest](#world_management-v1-ApplyRoomAmbientStatePatchRequest) @@ -620,6 +625,7 @@ for conventions on schema evolution and error handling. See each service's - [GetWorldInstanceLifecycleRequest](#world_management-v1-GetWorldInstanceLifecycleRequest) - [GetWorldInstanceLifecycleResponse](#world_management-v1-GetWorldInstanceLifecycleResponse) - [HazardAmbientState](#world_management-v1-HazardAmbientState) + - [InitialAdmissionBindHold](#world_management-v1-InitialAdmissionBindHold) - [ListRoomOccupantsRequest](#world_management-v1-ListRoomOccupantsRequest) - [ListRoomOccupantsResponse](#world_management-v1-ListRoomOccupantsResponse) - [PingRequest](#world_management-v1-PingRequest) @@ -647,6 +653,7 @@ for conventions on schema evolution and error handling. See each service's - [DoorState](#world_management-v1-DoorState) - [EntityTemplateReferenceType](#world_management-v1-EntityTemplateReferenceType) - [HazardState](#world_management-v1-HazardState) + - [InitialAdmissionBindHoldStatus](#world_management-v1-InitialAdmissionBindHoldStatus) - [RoomOccupantType](#world_management-v1-RoomOccupantType) - [UpgradeValidationResult](#world_management-v1-UpgradeValidationResult) - [WorldDesignAggregateType](#world_management-v1-WorldDesignAggregateType) @@ -7430,7 +7437,8 @@ Operator/control-plane surface for patch lifecycle visibility and rollback suppo | actor_principal | [string](#string) | | | | reason | [string](#string) | | | | control_plane_request_id | [string](#string) | | | -| expected_pointer_version | [int64](#int64) | optional | | +| expected_pointer_version | [int64](#int64) | optional | Existing-row mutations require both expected revisions to match the current row. Creating a missing row is supported only with both fields explicitly present as zero. Optional presence does not enable the currently disabled public mutation RPC or imply valid mutation semantics. | +| expected_catalog_revision | [int64](#int64) | optional | Must be supplied with expected_pointer_version under the same existing-row or creation rules. | @@ -7826,6 +7834,67 @@ Operator/control-plane surface for patch lifecycle visibility and rollback suppo + + +### GetInitialAdmissionBindProofRequest + + + +| Field | Type | Label | Description | +| ----- | ---- | ----- | ----------- | +| hold_id | [string](#string) | | | +| hold_fence | [string](#string) | | | +| tenant_id | [string](#string) | | | +| realm_uuid | [string](#string) | | | +| playable_state_namespace_uuid | [string](#string) | | | +| playable_state_scope | [entity_management.v1.PlayableStateScope](#entity_management-v1-PlayableStateScope) | | | +| game_instance_id | [string](#string) | | | +| version_id | [string](#string) | | | +| active_lifecycle_epoch | [int64](#int64) | | | +| initial_admission_request_id | [string](#string) | | | +| request_digest | [string](#string) | | | +| expected_no_prior_pointer | [bool](#bool) | | | +| expected_catalog_revision | [int64](#int64) | | | + + + + + + + + +### GetInitialAdmissionBindProofResponse + + + +| Field | Type | Label | Description | +| ----- | ---- | ----- | ----------- | +| hold_id | [string](#string) | | Echoes the complete request tuple so World can reject proof for another hold or target. | +| hold_fence | [string](#string) | | | +| tenant_id | [string](#string) | | | +| realm_uuid | [string](#string) | | | +| playable_state_namespace_uuid | [string](#string) | | | +| playable_state_scope | [entity_management.v1.PlayableStateScope](#entity_management-v1-PlayableStateScope) | | | +| game_instance_id | [string](#string) | | | +| version_id | [string](#string) | | | +| active_lifecycle_epoch | [int64](#int64) | | | +| initial_admission_request_id | [string](#string) | | | +| request_digest | [string](#string) | | | +| expected_no_prior_pointer | [bool](#bool) | | | +| expected_catalog_revision | [int64](#int64) | | | +| outcome | [InitialAdmissionBindOwnerProofOutcome](#game_session-v1-InitialAdmissionBindOwnerProofOutcome) | | | +| owner_proof_id | [string](#string) | | | +| pointer_audit_id | [string](#string) | | | +| pointer_version | [int64](#int64) | | | +| pointer_audit_request_digest | [string](#string) | | | +| future_commit_prevented | [bool](#bool) | | | +| error | [shared.v1.ErrorDetail](#shared-v1-ErrorDetail) | | | + + + + + + ### GetPinnedScriptPatchVersionRequest @@ -8089,6 +8158,11 @@ Operator/control-plane surface for patch lifecycle visibility and rollback suppo +| Field | Type | Label | Description | +| ----- | ---- | ----- | ----------- | +| tenant_ids | [string](#string) | repeated | Empty requires a global privileged caller for the all-tenant read. Current authority accepts only positive decimal values; UUID-form tenant IDs remain unsupported until owner storage migrates to the canonical UUID-string tenantId. Each current numeric ID must be individually authorized by the forwarded caller context. | + + @@ -9283,9 +9357,10 @@ Resume ticks after an authorized maintenance workflow completes. | actor_principal | [string](#string) | | | | reason | [string](#string) | | | | control_plane_request_id | [string](#string) | | | -| expected_pointer_version | [int64](#int64) | optional | | +| expected_pointer_version | [int64](#int64) | optional | Existing-row mutations require both expected revisions to match the current row. Creating a missing row is supported only with both fields explicitly present as zero. Optional presence does not enable the currently disabled public mutation RPC or imply valid mutation semantics. | | prepared_version_upgrade_id | [string](#string) | | | | public_production_realm | [bool](#bool) | | | +| expected_catalog_revision | [int64](#int64) | optional | Must be supplied with expected_pointer_version under the same existing-row or creation rules. | @@ -9576,6 +9651,23 @@ Resume ticks after an authorized maintenance workflow completes. + + +### InitialAdmissionBindOwnerProofOutcome + + +| Name | Number | Description | +| ---- | ------ | ----------- | +| 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 | | + + + ### TickStatus @@ -9604,6 +9696,7 @@ plus scoped tick pause/resume used for rollback safety. | GetPinnedScriptPatchVersion | [GetPinnedScriptPatchVersionRequest](#game_session-v1-GetPinnedScriptPatchVersionRequest) | [GetPinnedScriptPatchVersionResponse](#game_session-v1-GetPinnedScriptPatchVersionResponse) | | | GetGameSessionPinConvergence | [GetGameSessionPinConvergenceRequest](#game_session-v1-GetGameSessionPinConvergenceRequest) | [GetGameSessionPinConvergenceResponse](#game_session-v1-GetGameSessionPinConvergenceResponse) | | | GetGameInstanceRuntimeState | [GetGameInstanceRuntimeStateRequest](#game_session-v1-GetGameInstanceRuntimeStateRequest) | [GetGameInstanceRuntimeStateResponse](#game_session-v1-GetGameInstanceRuntimeStateResponse) | | +| GetInitialAdmissionBindProof | [GetInitialAdmissionBindProofRequest](#game_session-v1-GetInitialAdmissionBindProofRequest) | [GetInitialAdmissionBindProofResponse](#game_session-v1-GetInitialAdmissionBindProofResponse) | Read exact durable owner proof for a World-owned initial-admission hold. | | ValidateBuiltInCommandAlias | [ValidateBuiltInCommandAliasRequest](#game_session-v1-ValidateBuiltInCommandAliasRequest) | [ValidateBuiltInCommandAliasResponse](#game_session-v1-ValidateBuiltInCommandAliasResponse) | | | ListAdmissionPointers | [ListAdmissionPointersRequest](#game_session-v1-ListAdmissionPointersRequest) | [ListAdmissionPointersResponse](#game_session-v1-ListAdmissionPointersResponse) | | | ListAdmissionPointerAudit | [ListAdmissionPointerAuditRequest](#game_session-v1-ListAdmissionPointerAuditRequest) | [ListAdmissionPointerAuditResponse](#game_session-v1-ListAdmissionPointerAuditResponse) | | @@ -11082,6 +11175,47 @@ Semantics and failure expectations: - Events may be delivered more than once; th + + +### AcquireInitialAdmissionBindHoldRequest + + + +| Field | Type | Label | Description | +| ----- | ---- | ----- | ----------- | +| tenant_id | [string](#string) | | | +| game_instance_id | [string](#string) | | | +| version_id | [string](#string) | | | +| expected_active_lifecycle_epoch | [int64](#int64) | | | +| initial_admission_request_id | [string](#string) | | | +| request_digest | [string](#string) | | | +| realm_uuid | [string](#string) | | | +| playable_state_namespace_uuid | [string](#string) | | | +| playable_state_scope | [entity_management.v1.PlayableStateScope](#entity_management-v1-PlayableStateScope) | | | +| expected_no_prior_pointer | [bool](#bool) | | | +| expected_catalog_revision | [int64](#int64) | | | + + + + + + + + +### AcquireInitialAdmissionBindHoldResponse + + + +| Field | Type | Label | Description | +| ----- | ---- | ----- | ----------- | +| hold | [InitialAdmissionBindHold](#world_management-v1-InitialAdmissionBindHold) | | | +| error | [shared.v1.ErrorDetail](#shared-v1-ErrorDetail) | | | + + + + + + ### ActivatePreparedWorldInstanceRequest @@ -11486,6 +11620,35 @@ Semantics and failure expectations: - Events may be delivered more than once; th + + +### InitialAdmissionBindHold + + + +| Field | Type | Label | Description | +| ----- | ---- | ----- | ----------- | +| hold_id | [string](#string) | | | +| hold_fence | [string](#string) | | | +| tenant_id | [string](#string) | | | +| realm_uuid | [string](#string) | | | +| playable_state_namespace_uuid | [string](#string) | | | +| playable_state_scope | [entity_management.v1.PlayableStateScope](#entity_management-v1-PlayableStateScope) | | | +| game_instance_id | [string](#string) | | | +| version_id | [string](#string) | | | +| active_lifecycle_epoch | [int64](#int64) | | | +| initial_admission_request_id | [string](#string) | | | +| request_digest | [string](#string) | | | +| expected_no_prior_pointer | [bool](#bool) | | | +| expected_catalog_revision | [int64](#int64) | | | +| status | [InitialAdmissionBindHoldStatus](#world_management-v1-InitialAdmissionBindHoldStatus) | | | +| diagnostic_expires_at_epoch_millis | [int64](#int64) | | | + + + + + + ### ListRoomOccupantsRequest @@ -11965,6 +12128,21 @@ Semantics and failure expectations: - Events may be delivered more than once; th + + +### InitialAdmissionBindHoldStatus + + +| Name | Number | Description | +| ---- | ------ | ----------- | +| 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 | | + + + ### RoomOccupantType @@ -12096,6 +12274,7 @@ Semantics and failure expectations: - Events may be delivered more than once; th | ActivatePreparedWorldInstance | [ActivatePreparedWorldInstanceRequest](#world_management-v1-ActivatePreparedWorldInstanceRequest) | [ActivatePreparedWorldInstanceResponse](#world_management-v1-ActivatePreparedWorldInstanceResponse) | | | FailPreparedWorldInstance | [FailPreparedWorldInstanceRequest](#world_management-v1-FailPreparedWorldInstanceRequest) | [FailPreparedWorldInstanceResponse](#world_management-v1-FailPreparedWorldInstanceResponse) | | | GetWorldInstanceLifecycle | [GetWorldInstanceLifecycleRequest](#world_management-v1-GetWorldInstanceLifecycleRequest) | [GetWorldInstanceLifecycleResponse](#world_management-v1-GetWorldInstanceLifecycleResponse) | | +| AcquireInitialAdmissionBindHold | [AcquireInitialAdmissionBindHoldRequest](#world_management-v1-AcquireInitialAdmissionBindHoldRequest) | [AcquireInitialAdmissionBindHoldResponse](#world_management-v1-AcquireInitialAdmissionBindHoldResponse) | | | TerminateWorldInstance | [TerminateWorldInstanceRequest](#world_management-v1-TerminateWorldInstanceRequest) | [TerminateWorldInstanceResponse](#world_management-v1-TerminateWorldInstanceResponse) | | | GetRoom | [GetRoomRequest](#world_management-v1-GetRoomRequest) | [GetRoomResponse](#world_management-v1-GetRoomResponse) | | | GetRoomSnapshot | [GetRoomSnapshotRequest](#world_management-v1-GetRoomSnapshotRequest) | [GetRoomSnapshotResponse](#world_management-v1-GetRoomSnapshotResponse) | | diff --git a/design/project-management/ai-observations.md b/design/project-management/ai-observations.md index 599779a134..9715e879de 100644 --- a/design/project-management/ai-observations.md +++ b/design/project-management/ai-observations.md @@ -28,3 +28,10 @@ Entry format: - Expected pattern: alongside the code change, restrict privileged GitHub environments to the trusted deployment branch and clear or rotate credentials exposed by old runner state; verify the live environment policies before declaring the trust boundary effective. - Current status: The live `trusted-hosted-cluster` Environment allows only `develop`; its environment-scoped secret-name list is empty, while repository secrets still include legacy `PREVIEW_KUBECONFIG`. The scoped credential bootstrap/finalization, token rotation, legacy binding removal, and old-identity RBAC denial proof remain unverified. - Reconsideration trigger: before the next privileged deployment or declaring cutover complete, an authorized operator should provision and verify the canonical scoped credentials, finalize removal and revocation of the legacy credential and binding, and prove the old identity cannot read Secrets, create CertificateRequests, or change an Issuer. Secret-name presence or absence alone is not rotation or RBAC proof. + +- `2026-10-03`: Native process handles may be scoped to the launching agent + - Context: Gameplay tried to transfer an already-running full CLI command's native process handle to a read-only sentinel. + - Observation: the sentinel received `Unknown process id`, while the launching agent could still read the same live process. Shared filesystem access did not imply shared process-handle access; the review was neither restarted nor canceled. + - Expected pattern: retain an existing native process wait in its launching agent. For delegated external waits, let the sentinel launch its own canonical read-only waiter for the exact durable trigger or CI run; never retry the evidence-producing operation merely because a handle is unavailable in another agent. + - Current status: the launching Gameplay agent retained the live CLI wait. Whether cross-agent process handles are supported in other execution environments is unverified. + - Reconsideration trigger: revisit if a future harness requires cross-platform handle portability or a canonical watcher fix is verified. 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 eaf5c7804a..f57a4b0491 100644 --- a/design/project-management/implementation-tracking/game-session-runtime-and-tick-coordination.md +++ b/design/project-management/implementation-tracking/game-session-runtime-and-tick-coordination.md @@ -8,6 +8,8 @@ This is a non-normative implementation tracker for Game Session runtime and tick This tracker consolidates the live Game Session execution substrate by capability. The recorded boundaries describe current implementation status and bounded follow-up work. +Gameplay-session context remains on the implementation-local `sessionctx:*` keys and per-instance binding identity. The target authenticated `session:game:{tenantGameplayTag}:...` family, persisted tenant-tag allocation, and namespace-qualified controller uniqueness are not implemented or end-to-end proved; the canonical tenancy and focused-isolation requirements remain in [Multi-Tenancy](../../architecture/system-architecture-multi-tenancy.md#data-separation-per-service). + 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 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. @@ -162,6 +164,10 @@ Game Session control-plane reads are canonical and bounded. The runtime-state re Logging & Admin consumes Game Session directly and has no parallel command, ownership, coordinator, follow-up, or result database. Current REST surfaces are `GET /game-session-pins/{tenantId}/{gameInstanceId}`, `GET /game-session-pins/{tenantId}/{gameInstanceId}/convergence`, `GET /gameplay-commands/{tenantId}/{gameInstanceId}/{commandId}`, `GET /remote-command-coordinators/{tenantId}/{coordinatorId}`, `GET /remote-command-coordinators/{tenantId}`, `GET /remote-followups/{tenantId}/{followupId}`, `GET /remote-followups/{tenantId}`, `GET /remote-followup-results/{tenantId}/{resultId}`, `GET /remote-followup-results/{tenantId}`, and `GET /tick-remediation/status/{tenantId}`. Every route is tenant-guarded; point reads validate tenant and exact id, list reads validate every returned row, invalid enum filters fail closed, and control-plane scope mismatches are rejected. +The live `GET /admission-pointers` list now forwards only the caller's authorized positive tenant scopes through the Game Session RPC. Scoped callers cannot send an empty scope; an empty `tenant_ids` request preserves the global platform-admin/moderator all-tenant read. Game Session validates every requested tenant before reading, filters current pointers before audit lookups, and denies unauthorized or missing caller context before authority access. Missing, incomplete, or mismatched latest audit evidence for a pointer within the selected scope returns `AUTHORITY_UNAVAILABLE`, which Logging & Admin exposes as HTTP 503. Historical audit reads remain available and preserve legacy unknown identity fields rather than filling them from the current pointer. Ordinary admission-pointer writes remain closed; the separate audited present-attestation operation and retained-row database proof are unimplemented. See the [Game Session current-pointer guard](../../../services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/service/impl/GameSessionAdmissionPointerControlPlaneService.java), [guard proof](../../../services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/service/impl/GameSessionControlPlaneGrpcServiceTest.java), and [Logging & Admin response mapping](../../../services/logging-admin-service/src/main/java/net/firedevops/firemud/loggingadmin/service/impl/AdmissionPointerServiceImpl.java) with its [focused tests](../../../services/logging-admin-service/src/test/java/unit/net/firedevops/firemud/loggingadmin/service/impl/AdmissionPointerServiceImplTest.java). + +When the admission-pointer store is empty, configured seed data is validated but is not published: configuration does not carry owner-validated World `ACTIVE` lifecycle/epoch proof or a fence binding that proof to the pointer and audit commit. Startup logs that admission remains closed. Existing persisted pointers and their read guards are unchanged on restart. Enabling bootstrap publication requires a separately implemented and proved owner-provisioning/fence contract; no later `ACTIVE` observation or restart automatically publishes these seeds. See the [World Lifecycle and Admission Boundary](../../architecture/microservices/game-session-service/api-contracts.md#world-lifecycle-and-admission-boundary) and [ADR 0123](../../architecture/decisions/adr-0123-database-authoritative-temporal-coordinated-world-lifecycle.md). + Coordinator listing has a bounded REST filter set of origin/target game instance and region, state, follow-up id, command id, and limit. Upstream coordinator, follow-up, and result reads also expose first-class filters across scope and epochs, routing bundle, script/plugin/dispatch provenance, payload/source/queue/claim state, target entity/effect and target-command identity/outcomes, deadlines and late-result policy, script-event identity, and result error/message/outcomes. Rich list hydration is bounded in bulk rather than issuing one point lookup per row. Point and list DTOs preserve linked follow-up, result, target-command, publication, event, source, deadline, and current runtime comparison fields. ### Lifecycle and Feature Authority diff --git a/design/project-management/implementation-tracking/realm-routing-and-playable-state.md b/design/project-management/implementation-tracking/realm-routing-and-playable-state.md index a7bb6391dc..f908fd1ee5 100644 --- a/design/project-management/implementation-tracking/realm-routing-and-playable-state.md +++ b/design/project-management/implementation-tracking/realm-routing-and-playable-state.md @@ -6,7 +6,7 @@ This is a non-normative implementation tracker for realm routing and playable st ## Current Status -The working realm-catalog projection, admission-pointer reads, bootstrap/connect-scope flow, session-freshness normalization, runtime projections, and currently live playable-state boundaries are implemented. This is not a claim that routing is fully implemented. The direct-text [REALMS-to-JOIN scope handoff](../../architecture/system-architecture-authentication.md#direct-text-realms-to-join-scope-normative) remains target-only and unimplemented; Account issuance/validation and Game Session transport-local scope retention, retry, terminal-outcome, and expiry behavior still need implementation and proof. The complete routing boundary remains partial: persisted routes cannot represent explicit `CLOSED`, catalog and route revisions are combined, the key is not tenant-qualified, version checking is not an atomic database CAS, prepared-cutover execution is recorded after the pointer transaction, and active bindings are invalidated from current pointer state rather than ending through the target bounded drain. Public/grant policy is also partial because explicit grant expiry, monotonic mutation outcomes/tombstones, and tenant-admin management are absent. Playtest initialization/reset, all-owner manifests, lifecycle generations, and close/expiry orchestration are not implemented or end-to-end proved; their target owner contracts are linked below. +The working realm-catalog projection, admission-pointer reads, bootstrap/connect-scope flow, session-freshness normalization, runtime projections, and currently live playable-state boundaries are implemented. This is not a claim that routing is fully implemented. The direct-text [REALMS-to-JOIN scope handoff](../../architecture/system-architecture-authentication.md#direct-text-realms-to-join-scope-normative) remains target-only and unimplemented; Account issuance/validation and Game Session transport-local scope retention, retry, terminal-outcome, and expiry behavior still need implementation and proof. The complete routing boundary remains partial: persisted routes require a positive runtime target and cannot represent explicit `CLOSED`; the current proto/repository key remains `{tenantId, worldSlug, realmSlug}` rather than canonical `{tenantId, realmId}`; public pointer mutation and prepared-cutover RPCs remain fail-closed; and pointer-plus-audit persistence does not establish the full prepared execution/cutover boundary. World hold, source drain, lifecycle fencing, and the target bounded active-session drain remain gaps; current active bindings are invalidated from pointer state. Public/grant policy is also partial because explicit grant expiry, monotonic mutation outcomes/tombstones, and tenant-admin management are absent. Playtest initialization/reset, all-owner manifests, lifecycle generations, and close/expiry orchestration are not implemented or end-to-end proved; their target owner contracts are linked below. ## Packet 4 Status and Proof Gaps @@ -19,9 +19,9 @@ These links add decision provenance only; they do not upgrade routing or playabl | Capability | Implementation | Verification | Design | Implementation anchors | Proof anchors | Secondary handoffs | Gap or decision | | --- | --- | --- | --- | --- | --- | --- | --- | -| `AA-3.1` World and realm discovery catalog | `partial` | `drift-found` | [Multi-tenancy](../../architecture/system-architecture-multi-tenancy.md); [Authentication and authorization](../../architecture/system-architecture-authentication.md); [Versioning and runtime](../../architecture/system-architecture-versioning-runtime.md) | [GameplayWorldCatalog.java](../../../services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/command/text/GameplayWorldCatalog.java); [Database pointer authority](../../../services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/service/impl/DatabaseGameplayAdmissionPointerAuthorityService.java); [AuthController.java](../../../services/account-service/src/main/java/net/firedevops/firemud/accountservice/controller/AuthController.java); [AccountServiceImpl.java](../../../services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/impl/AccountServiceImpl.java); [pointer 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) | [GameplayWorldCatalogTest.java](../../../services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/command/text/GameplayWorldCatalogTest.java); [AccountServiceImplTest.java](../../../services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/service/impl/AccountServiceImplTest.java); [GameplayAdmissionPointerBootstrapInitializerTest.java](../../../services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/data/GameplayAdmissionPointerBootstrapInitializerTest.java) | [Player Access](./player-access-and-session.md); [Player Experience](./player-experience-commands-and-communication.md) | Filtered WORLDS/REALMS/CHARS discovery is live, but the baseline unique index is `(world_slug, realm_slug)` rather than canonical `{tenantId, worldSlug, realmSlug}`; cross-tenant duplicate selectors are not schema-safe. | +| `AA-3.1` World and realm discovery catalog | `partial` | `drift-found` | [Multi-tenancy](../../architecture/system-architecture-multi-tenancy.md); [Authentication and authorization](../../architecture/system-architecture-authentication.md); [Versioning and runtime](../../architecture/system-architecture-versioning-runtime.md) | [GameplayWorldCatalog.java](../../../services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/command/text/GameplayWorldCatalog.java); [Database pointer authority](../../../services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/service/impl/DatabaseGameplayAdmissionPointerAuthorityService.java); [AuthController.java](../../../services/account-service/src/main/java/net/firedevops/firemud/accountservice/controller/AuthController.java); [AccountServiceImpl.java](../../../services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/impl/AccountServiceImpl.java); [pointer 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) | [GameplayWorldCatalogTest.java](../../../services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/command/text/GameplayWorldCatalogTest.java); [AccountServiceImplTest.java](../../../services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/service/impl/AccountServiceImplTest.java); [GameplayAdmissionPointerBootstrapInitializerTest.java](../../../services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/data/GameplayAdmissionPointerBootstrapInitializerTest.java) | [Player Access](./player-access-and-session.md); [Player Experience](./player-experience-commands-and-communication.md) | Filtered WORLDS/REALMS/CHARS discovery is live. V2 now enforces tenant-local selector uniqueness, and V6 persists generated realm IDs for retained supported rows; canonical `{tenantId, realmId}` repository addressing and retained catalog-to-realm mapping remain gaps (see AA-3.3). | | `AA-3.2` Public visibility, explicit grants, and playable-state policy | `partial` | `drift-found` | [Multi-tenancy](../../architecture/system-architecture-multi-tenancy.md); [Authentication and authorization](../../architecture/system-architecture-authentication.md); [Account API contracts](../../architecture/microservices/account-service/api-contracts.md); [ADR 0137](../../architecture/decisions/adr-0137-isolated-playtest-state-modes-and-reset.md); [ADR 0138](../../architecture/decisions/adr-0138-expiring-playtest-grants-with-bounded-active-revocation.md); [ADR 0139](../../architecture/decisions/adr-0139-tenant-owned-runtime-lifecycle-with-audited-break-glass.md) | [AccountServiceImpl.java](../../../services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/impl/AccountServiceImpl.java); [InternalRuntimeController.java](../../../services/account-service/src/main/java/net/firedevops/firemud/accountservice/controller/InternalRuntimeController.java); [AccountRealmAccessGrant.java](../../../services/account-service/src/main/java/net/firedevops/firemud/accountservice/entity/AccountRealmAccessGrant.java); [V17__account_realm_access_grants.sql](../../../services/account-service/src/main/resources/db/migration/V17__account_realm_access_grants.sql); [ScopedCharacterResolver.java](../../../services/entity-management-service/src/main/java/net/firedevops/firemud/entitymanagement/service/ScopedCharacterResolver.java); [PlayableStateKeyResolver.java](../../../services/entity-management-service/src/main/java/net/firedevops/firemud/entitymanagement/service/PlayableStateKeyResolver.java); [account_service.proto](../../../protos/account/v1/account_service.proto) | [AccountServiceImplTest.java](../../../services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/service/impl/AccountServiceImplTest.java); [CharacterServiceImplListTest.java](../../../services/entity-management-service/src/test/java/unit/net/firedevops/firemud/entitymanagement/service/impl/CharacterServiceImplListTest.java); [PublicBootstrapRoutesProdProfileTest.java](../../../services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/controller/PublicBootstrapRoutesProdProfileTest.java) | [Player Access](./player-access-and-session.md); [Player Experience](./player-experience-commands-and-communication.md) | Public-production admission, non-public discovery requiring both current admitting membership and realm grant, grant reads, and shared/isolated state projection are live; the grant entity/schema has no expiry and only internal grant endpoints, so tenant-admin grant management is absent. | -| `AA-3.3` Runtime target identity, admission pointers, and routing freshness | `partial` | `drift-found` | [Multi-tenancy](../../architecture/system-architecture-multi-tenancy.md); [Versioning and runtime](../../architecture/system-architecture-versioning-runtime.md); [Redis architecture](../../architecture/system-architecture-redis.md) | [GameplayAdmissionPointerSnapshots.java](../../../services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/service/GameplayAdmissionPointerSnapshots.java); [DatabaseGameplayAdmissionPointerAuthorityService.java](../../../services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/service/impl/DatabaseGameplayAdmissionPointerAuthorityService.java); [GameSessionAdmissionPointerControlPlaneService.java](../../../services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/service/impl/GameSessionAdmissionPointerControlPlaneService.java); [SessionRoutingNormalizationService.java](../../../services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/service/SessionRoutingNormalizationService.java); [pointer 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) | [GameplayAdmissionPointerSnapshotsTest.java](../../../services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/service/GameplayAdmissionPointerSnapshotsTest.java); [DatabaseGameplayAdmissionPointerAuthorityServiceTest.java](../../../services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/service/impl/DatabaseGameplayAdmissionPointerAuthorityServiceTest.java); [SessionRoutingNormalizationServiceTest.java](../../../services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/service/SessionRoutingNormalizationServiceTest.java); [GameSessionControlPlaneGrpcServiceTest.java](../../../services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/service/impl/GameSessionControlPlaneGrpcServiceTest.java) | [Player Access](./player-access-and-session.md); [Game Session Runtime](./game-session-runtime-and-tick-coordination.md) | Pointer reads and audit reads are live. Internal sequential expected-version and prepared-cutover seams exist but are nonconformant and do not establish the target atomic CAS/cutover. Explicit closure, atomic CAS/cutover bookkeeping, catalog revision separation, tenant-qualified persistence, and bounded active-session drain remain unimplemented. Entity’s current scoped APIs still use legacy `playableStateKey` resolution; stable namespace columns and namespace-qualified API fields remain target/partial (see the [Entity Management runtime/data owner status](../../architecture/microservices/entity-management-service/runtime-and-data.md#implementation-status)). | +| `AA-3.3` Runtime target identity, admission pointers, and routing freshness | `partial` | `drift-found` | [Multi-tenancy](../../architecture/system-architecture-multi-tenancy.md); [Versioning and runtime](../../architecture/system-architecture-versioning-runtime.md); [Redis architecture](../../architecture/system-architecture-redis.md) | [GameplayAdmissionPointerSnapshots.java](../../../services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/service/GameplayAdmissionPointerSnapshots.java); [DatabaseGameplayAdmissionPointerAuthorityService.java](../../../services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/service/impl/DatabaseGameplayAdmissionPointerAuthorityService.java); [GameSessionAdmissionPointerControlPlaneService.java](../../../services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/service/impl/GameSessionAdmissionPointerControlPlaneService.java); [SessionRoutingNormalizationService.java](../../../services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/service/SessionRoutingNormalizationService.java); [pointer schema](../../../services/game-session-service/src/main/resources/db/migration/V1__baseline.sql); [tenant-local pointer key migration](../../../services/game-session-service/src/main/resources/db/migration/V2__scope_gameplay_command_identity.sql); [realm identity migration](../../../services/game-session-service/src/main/resources/db/migration/V6__persist_gameplay_realm_identity.sql); [game_session_service.proto](../../../protos/game-session/v1/game_session_service.proto) | [GameplayAdmissionPointerSnapshotsTest.java](../../../services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/service/GameplayAdmissionPointerSnapshotsTest.java); [DatabaseGameplayAdmissionPointerAuthorityServiceTest.java](../../../services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/service/impl/DatabaseGameplayAdmissionPointerAuthorityServiceTest.java); [SessionRoutingNormalizationServiceTest.java](../../../services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/service/SessionRoutingNormalizationServiceTest.java); [GameSessionControlPlaneGrpcServiceTest.java](../../../services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/service/impl/GameSessionControlPlaneGrpcServiceTest.java) | [Player Access](./player-access-and-session.md); [Game Session Runtime](./game-session-runtime-and-tick-coordination.md) | Pointer/audit reads are live. The internal authority now uses a row-locked expected `{pointerVersion, catalogRevision}` check, a conditional existing-row update, separate route/catalog revisions, and one pointer-plus-audit transaction. Public pointer mutation/cutover RPCs remain fail-closed, so the full target cutover operation is not live. Explicit `CLOSED`, repository addressing by the canonical `{tenantId, realmId}` key and retained catalog mapping, full prepared-execution/hold/drain atomicity, and bounded active-session drain remain gaps. Entity’s current scoped APIs still use legacy `playableStateKey` resolution; stable namespace columns and namespace-qualified API fields remain target/partial (see the [Entity Management runtime/data owner status](../../architecture/microservices/entity-management-service/runtime-and-data.md#implementation-status)). | ## Canonical Design Sources @@ -35,11 +35,11 @@ These links add decision provenance only; they do not upgrade routing or playabl ### Authority and Pointer Contract -Players address a visible `{tenantId, worldSlug, realmSlug}` realm, never a raw `gameInstanceId`. Game Session persists `gameplay_admission_pointer` rows and append-only audit events. The current row always requires one positive runtime target and cannot yet express the target `CLOSED` state. It combines runtime target, visibility/public-production classification, display metadata, `stateScope`, character-selection requirements, and character-creation policy under one `pointerVersion`; the target separates catalog revision from runtime routing. +Players address a visible `{tenantId, worldSlug, realmSlug}` realm, never a raw `gameInstanceId`. Game Session persists `gameplay_admission_pointer` rows and append-only audit events. The current row always requires one positive runtime target and cannot yet express the target `CLOSED` state. `pointerVersion` tracks runtime-target changes while `catalogRevision` tracks catalog/policy changes; see the [Versioning & Runtime Configuration owner status](../../architecture/system-architecture-versioning-runtime.md#implementation-status) for the current persistence boundary and remaining cutover gaps. -Selectors resolve to a tenant-local durable `realmId` before direct pointer authority is read. The target canonical singular key is `{tenantId, realmId}`; `GetAdmissionPointer(tenantId, realmId)` reads direct pointer authority using that key and does not reconstruct authority through browse projection. The current Game Session proto and `GameplayAdmissionPointerAuthorityService` still use `{tenantId, worldSlug, realmSlug}` slug lookup; realm-ID lookup and caller support remain implementation drift and are not claimed as live. Target Account bootstrap admission, public-production membership creation, prepared cutover validation, live admission, and operator audit reads use the same resolved realm identity. Membership join and connect-token issuance have separate idempotency contracts: each binds its own `requestId` to its operation, caller, verified discovery scope, and resolved target digest, and the two request IDs are not interchangeable. Current pointer writes use a tenant-qualified slug lookup and may compare `expectedPointerVersion` after that read, but the repository then updates by row ID without a version predicate. This is not an atomic CAS under concurrent writers. The baseline migration also defines the unique pointer index as `(world_slug, realm_slug)` without `tenant_id`, so persistence has not converged with the target `{tenantId, realmId}` key. +Selectors resolve to a tenant-local durable `realmId` before direct pointer authority is read. The target canonical singular key is `{tenantId, realmId}`; `GetAdmissionPointer(tenantId, realmId)` reads direct pointer authority using that key and does not reconstruct authority through browse projection. The current Game Session proto and `GameplayAdmissionPointerAuthorityService` still use `{tenantId, worldSlug, realmSlug}` slug lookup; realm-ID lookup and caller support remain implementation drift and are not claimed as live. Target Account bootstrap admission, public-production membership creation, prepared cutover validation, live admission, and operator audit reads use the same resolved realm identity. Membership join and connect-token issuance have separate idempotency contracts: each binds its own `requestId` to its operation, caller, verified discovery scope, and resolved target digest, and the two request IDs are not interchangeable. The current persistence primitive checks the expected `{pointerVersion, catalogRevision}` under a row lock, conditionally updates an existing row against both prior values, and commits the pointer with its audit event in one transaction. This is owner-local persistence proof, not public mutation or full prepared-cutover support; see the [Versioning & Runtime Configuration owner status](../../architecture/system-architecture-versioning-runtime.md#implementation-status). V2 enforces tenant-local selector uniqueness, but persistence has not converged on canonical `{tenantId, realmId}` addressing or retained catalog-to-realm mapping. -Startup seeds pointers only when the persisted store is empty, using dedicated bootstrap pointer-seed properties. After seeding, runtime reads and mutations use persisted pointer authority. `GameplayCatalogProperties` is not production routing authority: Game Session's production catalog projection is pointer-backed, Account Service no longer ships the old local catalog config, and property-to-catalog construction remains only in explicit test support. +Configured bootstrap pointer seeds are validated but not published automatically: startup creates no authority rows without World-owned lifecycle proof, and an empty store remains closed. `GameplayCatalogProperties` is not production routing authority: Game Session's production catalog projection is pointer-backed, Account Service no longer ships the old local catalog config, and property-to-catalog construction remains only in explicit test support. See the canonical [World Lifecycle and Admission Boundary](../../architecture/microservices/game-session-service/api-contracts.md#world-lifecycle-and-admission-boundary) and the [Game Session runtime tracker](./game-session-runtime-and-tick-coordination.md) for current implementation and proof status. Game Session exposes canonical world, realm, and pointer reads plus pointer list, audit, runtime-state, prepared-upgrade, and cutover control-plane surfaces. The public selector-shaped singular helper and preferred runtime-target lookup have been removed; reverse runtime-target consumers use `listByRuntimeTarget(...)` so multiplicity is observable. Logging & Admin is an operator ingress over these contracts, not a second routing owner. Its audit route is `GET /admission-pointers/{tenantId}/{worldSlug}/{realmSlug}/audit`; authenticated tenant access is checked before the call, response tenant mismatches fail closed, and operator pointer mutation derives `actorPrincipal` from the authenticated session rather than caller input. @@ -106,11 +106,11 @@ The full `WORLDS` -> `LOGIN` -> `REALMS` -> conditional `JOIN` -> conditional `C - Blank-scope login/bootstrap command staging currently retains the normalized shell selection hint with `playableStateScope=UNSPECIFIED` when runtime-target authority is absent, ambiguous, or incomplete. The implementation still needs focused proof that this hint cannot be consumed as routing authority or downstream gameplay metadata, plus convergence if any consumer crosses that boundary. - Region-partitioned runtime ownership and broader region fencing are tracked separately from admission routing. Current runtime projections carry region hints where available but do not implement the final execution-partition topology. - Replacement-instance migration/remap mechanics and domain-specific carry-forward rules remain unimplemented, including economy, guild, and combat-specific policy. -- The current pointer model cannot represent explicit `CLOSED`, increments its one version for every upsert including display metadata, and invalidates active bindings against current pointer state rather than ending them through the target bounded drain. +- The current pointer model cannot represent explicit `CLOSED`. Runtime-target changes advance `pointerVersion`; catalog/policy changes advance separate `catalogRevision`, so display and other catalog-only edits do not advance the runtime route version. Current active bindings are still fenced against current pointer state rather than ended through the target bounded drain. - The target replacement cutover also requires one World-owned durable `cutoverHoldId`/`cutoverHoldFence` after target `ACTIVE` proof. The current implementation has no hold record or coordinated acquire/finalize/readback surface; it does not block source/target termination while the hold is unresolved, bind the hold into the pointer/audit/prepared-execution/source-cleanup/drain-fence transaction, or prove safe abort versus finalization. Expiry and contradictory evidence therefore have no implemented reconciliation proof. -- `expectedPointerVersion` is checked after a read, but the database update is not conditional on the expected version. Concurrent writers and duplicate committed versions are not prevented or proven. -- Pointer state and audit event commit together, but `ExecutePreparedVersionCutover` marks the prepared upgrade executed afterward. A crash in that interval lacks the target atomic retry/reconciliation behavior; the target drain work item, acknowledgement, and readback must each remain bound to the exact `sourceGameInstanceId` as well as `sourceDrainId`. -- The pointer migration's unique index is `(world_slug, realm_slug)` rather than the canonical tenant-qualified key, so cross-tenant duplicate world/realm selectors are not schema-safe even though repository reads include `tenant_id`. +- The internal authority locks an existing pointer row, requires the expected `pointerVersion` and `catalogRevision` pair, and issues the existing-row update with both prior values in the database predicate. This owner-local CAS does not enable control-plane mutation: the public mutation path remains fail-closed, and full prepared-cutover CAS/readback is unimplemented. +- The internal pointer authority commits pointer state and its audit event together. The `ExecutePreparedVersionCutover` RPC currently fails closed before authority/preparation reads or execution marking, so no live cutover writes prepared-execution state in that transaction. The full target atomic retry/reconciliation boundary, including prepared execution and hold/drain evidence, remains unimplemented; drain work, acknowledgement, and readback must each remain bound to the exact `sourceGameInstanceId` as well as `sourceDrainId`. +- Current storage uses the tenant-local selector key `(tenant_id, world_slug, realm_slug)` (V2) and separately persists globally unique `realm_id` values (V6). The target composite `{tenantId, realmId}` key/index is not yet the repository lookup or uniqueness key; canonical realm-ID addressing and retained catalog-to-realm mapping remain unimplemented. - The canonical grant record permits expiry and calls for tenant-admin management; the current Account grant row and internal-only grant endpoints do not implement that follow-through. - The current documentation-only slice passed `./gradlew linkCheck lintMarkdown`. Validation and runtime-proof selection follows the [validation and runtime-proof workflow](../../developer-workflows/validation-and-runtime-proof.md); runtime proof is not applicable to this documentation-only checkpoint. @@ -122,7 +122,7 @@ No competing implementation is recorded for visible realm addressing, world-qual | Owner | Current responsibility | Primary contract boundary | | --- | --- | --- | -| Game Session | Persisted realm catalog and admission pointers; current audit/read-then-write version check/cutover; catalog projection; session normalization; runtime, tick, command, remote, and operator projections | World-qualified admission-pointer gRPC/control-plane APIs; persisted pointer authority; normalized session helpers | +| Game Session | Persisted realm catalog and admission pointers; internal row-locked dual-revision CAS with atomic pointer/audit persistence; catalog projection; session normalization; runtime, tick, command, remote, and operator projections. Public pointer-mutation and cutover RPCs remain fail-closed. | World-qualified admission-pointer gRPC/control-plane APIs; persisted pointer authority; normalized session helpers | | Account Service | Tenant membership/grants; bootstrap worlds/realms/characters; membership exit; membership-required connect-token issuance; target explicit public-production join | Bootstrap/auth REST and gRPC APIs; runtime membership/grant/entitlement reads; target explicit-join behavior | | Gateway and TCP Proxy | Trusted first-party/Telnet routing propagation; explicit disconnect runtime metadata; authenticated callbacks | Connect context; all-or-none routing headers; `gameInstanceId` disconnect envelope | | Entity Management | Scoped character, roster, item, friend, progression, resource, condition, and playable-state persistence | `{tenantId, gameInstanceId, playableStateScope}` APIs and attested gameplay calls | diff --git a/design/project-management/implementation-tracking/shared-runtime-contracts-and-persistence.md b/design/project-management/implementation-tracking/shared-runtime-contracts-and-persistence.md index 2d4754a5a6..ff0e360ab7 100644 --- a/design/project-management/implementation-tracking/shared-runtime-contracts-and-persistence.md +++ b/design/project-management/implementation-tracking/shared-runtime-contracts-and-persistence.md @@ -119,7 +119,7 @@ The [gRPC outcome and transport classification](../../architecture/system-archit ### Audit, Moderation, and Authority Boundaries -Logging & Admin exposes dedicated non-destructive `CreateLogEvent` ingress, but account-creation audit delivery remains partial: it is still a post-commit best-effort effect rather than the target owner-local outbox and receiver contract. The normative receiver contract is [Account Audit Ingress and Receipt](../../architecture/microservices/logging-admin-service/api-contracts.md#account-audit-ingress-and-receipt); see [Account Runtime and Data](../../architecture/microservices/account-service/runtime-and-data.md#implementation-status) for the producer's current implementation, proof, and gap status. Account logging for payment uses the existing RPC and `LogEvent` persistence path; it does not fabricate moderation fields, delete accounts, or stop sessions. Moderation mutation remains a separate explicit operator/admin operation. Focused tests prove the current log-event behavior and the absence of destructive account/session effects. +Logging & Admin's typed `CreateLogEvent` RPC is present but currently returns gRPC `UNIMPLEMENTED` without invoking the legacy generic `log_events` writer, so it is not an available ingress. Target account-audit receipt/readback persistence and focused receiver proof remain unimplemented; the normative receiver contract is [Account Audit Ingress and Receipt](../../architecture/microservices/logging-admin-service/api-contracts.md#account-audit-ingress-and-receipt). Account-creation audit delivery remains partial: the producer is still a post-commit best-effort effect rather than the target owner-local outbox, and it does not establish receiver durability or receipt confirmation; see [Account Runtime and Data](../../architecture/microservices/account-service/runtime-and-data.md#implementation-status) for its current implementation, proof, and gap status. Account logging for payment uses the separate existing `LogEvent` RPC and persistence path; it does not fabricate moderation fields, delete accounts, or stop sessions. Moderation mutation remains a separate explicit operator/admin operation. Current status only: Logging & Admin exposes the non-destructive `EvaluateModerationPolicy` read and a gated/unavailable moderation-action seam; current focused proof is partial and covers bounded read, denied, and validation paths only. It does not cover target mutation or appeal workflows, or focused `CHAT_SEND` stale/unavailable dependency and owner-read failure cases. The remaining implementation and proof gaps are tracked against [ADR 0141](../../architecture/decisions/adr-0141-fixed-safety-restriction-categories-and-independent-lifecycles.md) and [ADR 0142](../../architecture/decisions/adr-0142-bounded-moderation-appeal-cases.md). @@ -174,7 +174,7 @@ Current runtime wiring keeps gameplay ticks, Redis coordination, per-command exe | --- | --- | --- | | Common platform/security | Internal auth propagation, service identity parsing, deprecated gameplay-attestation helpers pending removal and authority-boundary proof, gRPC app-error representation/observability, and proto time-field guard | Shared Java seams, deprecated attestation debt pending removal, gRPC helpers, Gradle/root verification | | Owning domain services | Domain authority, tenant/access enforcement, local transaction boundary, durable local state, and app-error mapping | Service REST/gRPC APIs and service-local Flyway schema | -| Logging & Admin | Non-destructive log-event ingress, moderation policy definition/evaluation, operator projections, and target moderation/report persistence (currently unavailable/gated) | Audit/log-event and moderation/control-plane REST/gRPC contracts | +| Logging & Admin | Current separate `LogEvent` RPC and `log_events` persistence path; typed `CreateLogEvent` RPC is present but returns `UNIMPLEMENTED` and is unavailable; moderation policy definition/evaluation, operator projections, and target moderation/report persistence (currently unavailable/gated) | Audit/log-event and moderation/control-plane REST/gRPC contracts; target receiver boundary: [Account Audit Ingress and Receipt](../../architecture/microservices/logging-admin-service/api-contracts.md#account-audit-ingress-and-receipt) | | Game Session | Player-session authority, exact script-pin authority and rollout-history ownership, gameplay-attestation call sites pending removal and consumer-level authority proof, lifecycle finalization/compensation, tick runtime coordination, and gameplay control-plane delegation | Session/gameplay gRPC, script-pin and rollout-history contracts, deprecated attestation debt pending removal, Redis/runtime records, and durable SQL ledgers | | Common saga | Shared saga repository ownership and short synchronous saga persistence/runner contract | Schema-qualified jOOQ repositories and saga steps | | jOOQ/Flyway tooling | Generated relational access, migration history, service-schema conventions, and Postgres-backed proof support | Build/codegen tasks, Flyway resources, reset/bootstrap tooling | diff --git a/gradle/proto-convention.gradle b/gradle/proto-convention.gradle index 2f0c4333f5..fdf7a8e6a0 100644 --- a/gradle/proto-convention.gradle +++ b/gradle/proto-convention.gradle @@ -1,6 +1,8 @@ apply plugin: 'com.google.protobuf' def libs = project.extensions.getByName('libs') +def protobufConfigurationCacheIncompatibilityReason = + "protobuf-gradle-plugin ${libs.plugins.protobuf.get().version.requiredVersion} retains Gradle Project and SourceDirectorySet state with Gradle ${gradle.gradleVersion}" // Define proto source directory before configuring the protobuf plugin so that // the plugin wires the generate tasks and compile dependencies correctly. @@ -30,9 +32,7 @@ protobuf { } generateProtoTasks { all().configureEach { task -> - task.notCompatibleWithConfigurationCache( - "protobuf-gradle-plugin ${libs.plugins.protobuf.get().version.requiredVersion} retains Gradle Project and SourceDirectorySet state with Gradle ${gradle.gradleVersion}" - ) + task.notCompatibleWithConfigurationCache(protobufConfigurationCacheIncompatibilityReason) } ofSourceSet('main').each { task -> task.doNotTrackState("Generated protobuf outputs are rewritten opportunistically and Gradle 9 output snapshotting can observe transiently missing files.") @@ -43,6 +43,14 @@ protobuf { } } +// Protobuf extraction tasks retain the same non-serializable plugin state as +// generation tasks, so keep them out of the configuration cache as well. +def protobufExtractTaskClass = plugins.getPlugin('com.google.protobuf').class.classLoader + .loadClass('com.google.protobuf.gradle.ProtobufExtract') +tasks.withType(protobufExtractTaskClass).configureEach { task -> + task.notCompatibleWithConfigurationCache(protobufConfigurationCacheIncompatibilityReason) +} + // Ensure that the Java compilation runs after Protobuf code generation. tasks.named('compileJava') { dependsOn('generateProto') diff --git a/protos/game-session/v1/game_session_service.proto b/protos/game-session/v1/game_session_service.proto index d0a6f8dc3e..adf1810f08 100644 --- a/protos/game-session/v1/game_session_service.proto +++ b/protos/game-session/v1/game_session_service.proto @@ -426,7 +426,13 @@ message AdmissionPointerControlPlaneEntry { string playable_state_namespace_id = 20; } -message ListAdmissionPointersRequest {} +message ListAdmissionPointersRequest { + // Empty requires a global privileged caller for the all-tenant read. + // Current authority accepts only positive decimal values; UUID-form tenant IDs remain + // unsupported until owner storage migrates to the canonical UUID-string tenantId. + // Each current numeric ID must be individually authorized by the forwarded caller context. + repeated string tenant_ids = 1; +} message ListAdmissionPointersResponse { repeated AdmissionPointerControlPlaneEntry pointers = 1; @@ -1152,9 +1158,14 @@ message SetAdmissionPointerRequest { string actor_principal = 11; string reason = 12; string control_plane_request_id = 13; + // Existing-row mutations require both expected revisions to match the current row. Creating a + // missing row is supported only with both fields explicitly present as zero. Optional presence + // does not enable the currently disabled public mutation RPC or imply valid mutation semantics. optional int64 expected_pointer_version = 14; string prepared_version_upgrade_id = 15; bool public_production_realm = 16; + // Must be supplied with expected_pointer_version under the same existing-row or creation rules. + optional int64 expected_catalog_revision = 17; } message SetAdmissionPointerResponse { @@ -1171,7 +1182,12 @@ message ExecutePreparedVersionCutoverRequest { string actor_principal = 6; string reason = 7; string control_plane_request_id = 8; + // Existing-row mutations require both expected revisions to match the current row. Creating a + // missing row is supported only with both fields explicitly present as zero. Optional presence + // does not enable the currently disabled public mutation RPC or imply valid mutation semantics. optional int64 expected_pointer_version = 9; + // Must be supplied with expected_pointer_version under the same existing-row or creation rules. + optional int64 expected_catalog_revision = 10; } message ExecutePreparedVersionCutoverResponse { diff --git a/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/repository/GameplayAdmissionPointerEventRepository.java b/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/repository/GameplayAdmissionPointerEventRepository.java index 276817318a..7210542b41 100644 --- a/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/repository/GameplayAdmissionPointerEventRepository.java +++ b/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/repository/GameplayAdmissionPointerEventRepository.java @@ -5,11 +5,18 @@ import static net.firedevops.firemud.gamesession.jooq.tables.GameplayAdmissionPointerEvent.GAMEPLAY_ADMISSION_POINTER_EVENT; import edu.umd.cs.findbugs.annotations.SuppressFBWarnings; +import java.util.ArrayList; +import java.util.Comparator; +import java.util.LinkedHashSet; import java.util.List; +import java.util.Optional; import net.firedevops.firemud.gamesession.entity.GameplayAdmissionPointerEvent; import net.firedevops.firemud.gamesession.jooq.tables.records.GameplayAdmissionPointerEventRecord; +import net.firedevops.firemud.gamesession.service.GameplayAdmissionPointerAuthorityService.PointerAuditKey; +import org.jooq.Condition; import org.jooq.DSLContext; import org.jooq.Record; +import org.jooq.impl.DSL; import org.springframework.stereotype.Repository; @Repository @@ -17,13 +24,15 @@ value = "EI_EXPOSE_REP2", justification = "Injected DSLContext is an internal Spring collaborator.") public class GameplayAdmissionPointerEventRepository { + private static final int POINTER_KEY_QUERY_CHUNK_SIZE = 500; + private final DSLContext dsl; public GameplayAdmissionPointerEventRepository(DSLContext dsl) { this.dsl = dsl; } - public List findByWorldSlugAndRealmSlugOrderByOccurredAtDesc( + public List findByWorldSlugAndRealmSlugOrderByIdDesc( String worldSlug, String realmSlug) { return dsl.selectFrom(GAMEPLAY_ADMISSION_POINTER_EVENT) .where( @@ -31,15 +40,12 @@ public List findByWorldSlugAndRealmSlugOrderByOcc .WORLD_SLUG .eq(worldSlug) .and(GAMEPLAY_ADMISSION_POINTER_EVENT.REALM_SLUG.eq(realmSlug))) - .orderBy( - GAMEPLAY_ADMISSION_POINTER_EVENT.OCCURRED_AT.desc(), - GAMEPLAY_ADMISSION_POINTER_EVENT.ID.desc()) + .orderBy(GAMEPLAY_ADMISSION_POINTER_EVENT.ID.desc()) .fetch(this::toEntity); } - public List - findByTenantIdAndWorldSlugAndRealmSlugOrderByOccurredAtDesc( - Long tenantId, String worldSlug, String realmSlug) { + public List findByTenantIdAndWorldSlugAndRealmSlugOrderByIdDesc( + Long tenantId, String worldSlug, String realmSlug) { return dsl.selectFrom(GAMEPLAY_ADMISSION_POINTER_EVENT) .where( GAMEPLAY_ADMISSION_POINTER_EVENT @@ -47,12 +53,62 @@ public List findByWorldSlugAndRealmSlugOrderByOcc .eq(tenantId) .and(GAMEPLAY_ADMISSION_POINTER_EVENT.WORLD_SLUG.eq(worldSlug)) .and(GAMEPLAY_ADMISSION_POINTER_EVENT.REALM_SLUG.eq(realmSlug))) - .orderBy( - GAMEPLAY_ADMISSION_POINTER_EVENT.OCCURRED_AT.desc(), - GAMEPLAY_ADMISSION_POINTER_EVENT.ID.desc()) + .orderBy(GAMEPLAY_ADMISSION_POINTER_EVENT.ID.desc()) .fetch(this::toEntity); } + public Optional findLatestByTenantIdAndWorldSlugAndRealmSlug( + Long tenantId, String worldSlug, String realmSlug) { + return dsl.selectFrom(GAMEPLAY_ADMISSION_POINTER_EVENT) + .where( + GAMEPLAY_ADMISSION_POINTER_EVENT + .TENANT_ID + .eq(tenantId) + .and(GAMEPLAY_ADMISSION_POINTER_EVENT.WORLD_SLUG.eq(worldSlug)) + .and(GAMEPLAY_ADMISSION_POINTER_EVENT.REALM_SLUG.eq(realmSlug))) + .orderBy(GAMEPLAY_ADMISSION_POINTER_EVENT.ID.desc()) + .limit(1) + .fetchOptional(this::toEntity); + } + + public List findLatestByPointerKeys(List keys) { + if (keys.isEmpty()) { + return List.of(); + } + List uniqueKeys = new ArrayList<>(new LinkedHashSet<>(keys)); + List latestEvents = new ArrayList<>(); + for (int offset = 0; offset < uniqueKeys.size(); offset += POINTER_KEY_QUERY_CHUNK_SIZE) { + List keyChunk = + uniqueKeys.subList( + offset, Math.min(offset + POINTER_KEY_QUERY_CHUNK_SIZE, uniqueKeys.size())); + Condition selectedKeys = DSL.falseCondition(); + for (PointerAuditKey key : keyChunk) { + selectedKeys = + selectedKeys.or( + GAMEPLAY_ADMISSION_POINTER_EVENT + .TENANT_ID + .eq(key.tenantId()) + .and(GAMEPLAY_ADMISSION_POINTER_EVENT.WORLD_SLUG.eq(key.worldSlug())) + .and(GAMEPLAY_ADMISSION_POINTER_EVENT.REALM_SLUG.eq(key.realmSlug()))); + } + var latestIds = + dsl.select(DSL.max(GAMEPLAY_ADMISSION_POINTER_EVENT.ID)) + .from(GAMEPLAY_ADMISSION_POINTER_EVENT) + .where(selectedKeys) + .groupBy( + GAMEPLAY_ADMISSION_POINTER_EVENT.TENANT_ID, + GAMEPLAY_ADMISSION_POINTER_EVENT.WORLD_SLUG, + GAMEPLAY_ADMISSION_POINTER_EVENT.REALM_SLUG); + latestEvents.addAll( + dsl.selectFrom(GAMEPLAY_ADMISSION_POINTER_EVENT) + .where(GAMEPLAY_ADMISSION_POINTER_EVENT.ID.in(latestIds)) + .orderBy(GAMEPLAY_ADMISSION_POINTER_EVENT.ID.asc()) + .fetch(this::toEntity)); + } + latestEvents.sort(Comparator.comparing(GameplayAdmissionPointerEvent::getId)); + return latestEvents; + } + public GameplayAdmissionPointerEvent save(GameplayAdmissionPointerEvent entity) { if (entity.getId() == null) { GameplayAdmissionPointerEventRecord record = dsl.newRecord(GAMEPLAY_ADMISSION_POINTER_EVENT); diff --git a/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/repository/GameplayAdmissionPointerRepository.java b/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/repository/GameplayAdmissionPointerRepository.java index f63c20ef60..11921b509e 100644 --- a/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/repository/GameplayAdmissionPointerRepository.java +++ b/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/repository/GameplayAdmissionPointerRepository.java @@ -49,6 +49,19 @@ public Optional findByTenantIdAndWorldSlugAndRealmSlug .fetchOptional(this::toEntity); } + public Optional findByTenantIdAndWorldSlugAndRealmSlugForUpdate( + Long tenantId, String worldSlug, String realmSlug) { + return dsl.selectFrom(GAMEPLAY_ADMISSION_POINTER) + .where( + GAMEPLAY_ADMISSION_POINTER + .TENANT_ID + .eq(tenantId) + .and(GAMEPLAY_ADMISSION_POINTER.WORLD_SLUG.eq(worldSlug)) + .and(GAMEPLAY_ADMISSION_POINTER.REALM_SLUG.eq(realmSlug))) + .forUpdate() + .fetchOptional(this::toEntity); + } + public Optional findByTenantIdAndGameInstanceId( Long tenantId, Long gameInstanceId) { return findAllByTenantIdAndGameInstanceId(tenantId, gameInstanceId).stream().findFirst(); @@ -76,6 +89,19 @@ public List findAllByOrderByWorldSlugAscRealmSlugAsc() .fetch(this::toEntity); } + public List findAllByTenantIdInOrderByWorldSlugAscRealmSlugAsc( + List tenantIds) { + if (tenantIds.isEmpty()) { + return List.of(); + } + return dsl.selectFrom(GAMEPLAY_ADMISSION_POINTER) + .where(GAMEPLAY_ADMISSION_POINTER.TENANT_ID.in(tenantIds)) + .orderBy( + GAMEPLAY_ADMISSION_POINTER.WORLD_SLUG.asc(), + GAMEPLAY_ADMISSION_POINTER.REALM_SLUG.asc()) + .fetch(this::toEntity); + } + public List findAllByTenantIdOrderByWorldSlugAscRealmSlugAsc( Long tenantId) { return dsl.selectFrom(GAMEPLAY_ADMISSION_POINTER) @@ -292,6 +318,10 @@ private void lockRuntimeTargets( } private void lockRuntimeTarget(String lockKey) { + lockAdvisoryTransaction(lockKey); + } + + private void lockAdvisoryTransaction(String lockKey) { // The test profile uses H2, which does not implement PostgreSQL advisory locks. // Production remains protected by the transaction-scoped PostgreSQL lock. if (dsl.dialect().family() != SQLDialect.POSTGRES) { diff --git a/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/service/GameplayAdmissionPointerAuditEntry.java b/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/service/GameplayAdmissionPointerAuditEntry.java index f195c3ba29..1375b51bfb 100644 --- a/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/service/GameplayAdmissionPointerAuditEntry.java +++ b/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/service/GameplayAdmissionPointerAuditEntry.java @@ -11,6 +11,9 @@ public record GameplayAdmissionPointerAuditEntry( long tenantId, long gameInstanceId, long pointerVersion, + Long catalogRevision, + UUID realmId, + UUID playableStateNamespaceId, boolean visible, boolean publicProductionRealm, boolean requiresCharacterSelection, @@ -20,7 +23,4 @@ public record GameplayAdmissionPointerAuditEntry( String reason, String controlPlaneRequestId, String preparedVersionUpgradeId, - Long catalogRevision, - UUID realmId, - UUID playableStateNamespaceId, Instant occurredAt) {} diff --git a/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/service/GameplayAdmissionPointerAuthorityService.java b/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/service/GameplayAdmissionPointerAuthorityService.java index b59568dbd6..1bd9e0eade 100644 --- a/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/service/GameplayAdmissionPointerAuthorityService.java +++ b/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/service/GameplayAdmissionPointerAuthorityService.java @@ -1,11 +1,16 @@ package net.firedevops.firemud.gamesession.service; import java.util.List; +import java.util.Map; import java.util.Optional; public interface GameplayAdmissionPointerAuthorityService { + record PointerAuditKey(long tenantId, String worldSlug, String realmSlug) {} + List listPointers(); + List listPointersForTenants(List tenantIds); + List listPointersByTenant(long tenantId); Optional findPointer( @@ -17,4 +22,10 @@ Optional findPointer( List listPointerAudit( long tenantId, String worldSlug, String realmSlug); + + Optional findLatestPointerAudit( + long tenantId, String worldSlug, String realmSlug); + + Map findLatestPointerAudits( + List keys); } diff --git a/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/service/impl/DatabaseGameplayAdmissionPointerAuthorityService.java b/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/service/impl/DatabaseGameplayAdmissionPointerAuthorityService.java index d6b36b9e89..851d2af4d9 100644 --- a/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/service/impl/DatabaseGameplayAdmissionPointerAuthorityService.java +++ b/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/service/impl/DatabaseGameplayAdmissionPointerAuthorityService.java @@ -3,8 +3,10 @@ import edu.umd.cs.findbugs.annotations.SuppressFBWarnings; import java.time.Instant; import java.util.List; +import java.util.Map; import java.util.Objects; import java.util.Optional; +import java.util.stream.Collectors; import net.firedevops.firemud.gamesession.entity.GameplayAdmissionPointer; import net.firedevops.firemud.gamesession.entity.GameplayAdmissionPointerEvent; import net.firedevops.firemud.gamesession.repository.GameplayAdmissionPointerEventRepository; @@ -13,6 +15,7 @@ import net.firedevops.firemud.gamesession.service.GameplayAdmissionCatalogPolicy; import net.firedevops.firemud.gamesession.service.GameplayAdmissionPointerAuditEntry; import net.firedevops.firemud.gamesession.service.GameplayAdmissionPointerAuthorityService; +import net.firedevops.firemud.gamesession.service.GameplayAdmissionPointerAuthorityService.PointerAuditKey; import net.firedevops.firemud.gamesession.service.GameplayAdmissionPointerMutation; import net.firedevops.firemud.gamesession.service.GameplayAdmissionPointerSnapshot; import org.springframework.stereotype.Service; @@ -46,6 +49,14 @@ public List listPointers() { .toList(); } + @Override + @Transactional(readOnly = true) + public List listPointersForTenants(List tenantIds) { + return pointerRepository.findAllByTenantIdInOrderByWorldSlugAscRealmSlugAsc(tenantIds).stream() + .map(this::toSnapshot) + .toList(); + } + @Override @Transactional(readOnly = true) public List listPointersByTenant(long tenantId) { @@ -82,7 +93,7 @@ public GameplayAdmissionPointerSnapshot upsertPointer(GameplayAdmissionPointerMu Instant now = Instant.now(); GameplayAdmissionPointer pointer = pointerRepository - .findByTenantIdAndWorldSlugAndRealmSlug( + .findByTenantIdAndWorldSlugAndRealmSlugForUpdate( mutation.tenantId(), mutation.worldSlug(), mutation.realmSlug()) .orElseGet(GameplayAdmissionPointer::new); if (pointer.getId() != null @@ -95,7 +106,7 @@ public GameplayAdmissionPointerSnapshot upsertPointer(GameplayAdmissionPointerMu throw new IllegalArgumentException( "state_scope changes require a new playable-state lifecycle"); } - enforceExpectedRevisions( + enforceExpectedVersions( pointer, mutation.expectedPointerVersion(), mutation.expectedCatalogRevision()); if (pointer.getId() != null && runtimeTargetMatches(pointer, mutation) @@ -167,34 +178,61 @@ && runtimeTargetMatches(pointer, mutation) public List listPointerAudit( long tenantId, String worldSlug, String realmSlug) { return eventRepository - .findByTenantIdAndWorldSlugAndRealmSlugOrderByOccurredAtDesc(tenantId, worldSlug, realmSlug) + .findByTenantIdAndWorldSlugAndRealmSlugOrderByIdDesc(tenantId, worldSlug, realmSlug) .stream() - .map( - event -> - new GameplayAdmissionPointerAuditEntry( - event.getWorldSlug(), - event.getRealmSlug(), - event.getWorldDisplayName(), - event.getRealmDisplayName(), - event.getTenantId(), - event.getGameInstanceId(), - event.getPointerVersion(), - event.isVisible(), - event.isPublicProductionRealm(), - event.isRequiresCharacterSelection(), - event.getStateScope(), - event.getCharacterCreationPolicy(), - event.getActorPrincipal(), - event.getReason(), - event.getControlPlaneRequestId(), - event.getPreparedVersionUpgradeId(), - event.getCatalogRevision(), - event.getRealmId(), - event.getPlayableStateNamespaceId(), - event.getOccurredAt())) + .map(this::toAuditEntry) .toList(); } + @Override + @Transactional(readOnly = true) + public Optional findLatestPointerAudit( + long tenantId, String worldSlug, String realmSlug) { + return eventRepository + .findLatestByTenantIdAndWorldSlugAndRealmSlug(tenantId, worldSlug, realmSlug) + .map(this::toAuditEntry); + } + + @Override + @Transactional(readOnly = true) + public Map findLatestPointerAudits( + List keys) { + if (keys.isEmpty()) { + return Map.of(); + } + return eventRepository.findLatestByPointerKeys(keys).stream() + .collect( + Collectors.toMap( + event -> + new PointerAuditKey( + event.getTenantId(), event.getWorldSlug(), event.getRealmSlug()), + this::toAuditEntry)); + } + + private GameplayAdmissionPointerAuditEntry toAuditEntry(GameplayAdmissionPointerEvent event) { + return new GameplayAdmissionPointerAuditEntry( + event.getWorldSlug(), + event.getRealmSlug(), + event.getWorldDisplayName(), + event.getRealmDisplayName(), + event.getTenantId(), + event.getGameInstanceId(), + event.getPointerVersion(), + event.getCatalogRevision(), + event.getRealmId(), + event.getPlayableStateNamespaceId(), + event.isVisible(), + event.isPublicProductionRealm(), + event.isRequiresCharacterSelection(), + event.getStateScope(), + event.getCharacterCreationPolicy(), + event.getActorPrincipal(), + event.getReason(), + event.getControlPlaneRequestId(), + event.getPreparedVersionUpgradeId(), + event.getOccurredAt()); + } + private GameplayAdmissionPointerSnapshot toSnapshot(GameplayAdmissionPointer pointer) { return new GameplayAdmissionPointerSnapshot( pointer.getWorldSlug(), @@ -260,32 +298,33 @@ private void requireText(String value, String message) { } } - private void enforceExpectedRevisions( + private void enforceExpectedVersions( GameplayAdmissionPointer pointer, Long expectedPointerVersion, Long expectedCatalogRevision) { + if (expectedPointerVersion == null || expectedCatalogRevision == null) { + throw new AdmissionPointerVersionMismatchException( + "expected_pointer_version and expected_catalog_revision are required"); + } if (pointer.getId() == null) { - if (!isAbsentOrZero(expectedPointerVersion) || !isAbsentOrZero(expectedCatalogRevision)) { + if (expectedPointerVersion != 0L || expectedCatalogRevision != 0L) { throw new AdmissionPointerVersionMismatchException( - "new admission pointers require absent or zero initial revisions"); + "new admission pointers require zero initial versions"); } return; } + long currentPointerVersion = + pointer.getPointerVersion() == null ? -1L : pointer.getPointerVersion(); + long currentCatalogRevision = + pointer.getCatalogRevision() == null ? -1L : pointer.getCatalogRevision(); if (!isPositive(expectedPointerVersion) - || !Objects.equals(pointer.getPointerVersion(), expectedPointerVersion)) { - throw new AdmissionPointerVersionMismatchException( - "expected_pointer_version does not match current pointer version"); - } - if (!isPositive(expectedCatalogRevision) - || !Objects.equals(pointer.getCatalogRevision(), expectedCatalogRevision)) { + || !isPositive(expectedCatalogRevision) + || currentPointerVersion != expectedPointerVersion + || currentCatalogRevision != expectedCatalogRevision) { throw new AdmissionPointerVersionMismatchException( - "expected_catalog_revision does not match current catalog revision"); + "expected admission-pointer version pair does not match current pointer state"); } } private boolean isPositive(Long value) { return value != null && value > 0L; } - - private boolean isAbsentOrZero(Long value) { - return value == null || value == 0L; - } } 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 index 81526a7066..55758189af 100644 --- 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 @@ -322,7 +322,7 @@ private InitialAdmissionBindOwnerProof readCommittedProof( GameplayAdmissionPointer pointer = maybePointer.get(); Optional maybeAudit = eventRepository - .findByTenantIdAndWorldSlugAndRealmSlugOrderByOccurredAtDesc( + .findByTenantIdAndWorldSlugAndRealmSlugOrderByIdDesc( attempt.tenantId(), catalog.worldSlug(), catalog.realmSlug()) .stream() .filter(event -> Objects.equals(event.getId(), attempt.auditEventId())) diff --git a/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/service/impl/GameSessionAdmissionPointerControlPlaneService.java b/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/service/impl/GameSessionAdmissionPointerControlPlaneService.java index ab677896bb..6a7e1ab8ca 100644 --- a/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/service/impl/GameSessionAdmissionPointerControlPlaneService.java +++ b/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/service/impl/GameSessionAdmissionPointerControlPlaneService.java @@ -1,7 +1,13 @@ package net.firedevops.firemud.gamesession.service.impl; +import java.util.LinkedHashSet; +import java.util.List; +import java.util.Map; +import java.util.Objects; +import java.util.Set; import net.firedevops.firemud.gamesession.service.GameplayAdmissionPointerAuditEntry; import net.firedevops.firemud.gamesession.service.GameplayAdmissionPointerAuthorityService; +import net.firedevops.firemud.gamesession.service.GameplayAdmissionPointerAuthorityService.PointerAuditKey; import net.firedevops.firemud.gamesession.service.GameplayAdmissionPointerSnapshot; import net.firedevops.firemud.gamesession.v1.AdmissionPointerControlPlaneEntry; import net.firedevops.firemud.gamesession.v1.ExecutePreparedVersionCutoverRequest; @@ -28,17 +34,36 @@ static final class AdmissionPointerMutationPreconditionException extends Runtime this.gameplayAdmissionPointerAuthorityService = gameplayAdmissionPointerAuthorityService; } - ListAdmissionPointersResponse listAdmissionPointers() { - java.util.List - pointers = gameplayAdmissionPointerAuthorityService.listPointers(); - java.util.List entries = + ListAdmissionPointersResponse listAdmissionPointers(List requestedTenantIds) { + List tenantIds = List.copyOf(new LinkedHashSet<>(requestedTenantIds)); + Set tenantScope = Set.copyOf(tenantIds); + List pointers = + (tenantScope.isEmpty() + ? gameplayAdmissionPointerAuthorityService.listPointers() + : gameplayAdmissionPointerAuthorityService.listPointersForTenants(tenantIds)) + .stream() + .filter( + pointer -> tenantScope.isEmpty() || tenantScope.contains(pointer.tenantId())) + .toList(); + List auditKeys = + pointers.stream() + .map( + pointer -> + new PointerAuditKey( + pointer.tenantId(), pointer.worldSlug(), pointer.realmSlug())) + .distinct() + .toList(); + Map latestAudits = + gameplayAdmissionPointerAuthorityService.findLatestPointerAudits(auditKeys); + List entries = pointers.stream() .map( pointer -> { - java.util.List audit = - gameplayAdmissionPointerAuthorityService.listPointerAudit( + PointerAuditKey key = + new PointerAuditKey( pointer.tenantId(), pointer.worldSlug(), pointer.realmSlug()); - if (audit.isEmpty()) { + GameplayAdmissionPointerAuditEntry latestAudit = latestAudits.get(key); + if (latestAudit == null) { throw new AdmissionPointerAuditUnavailableException( "Admission pointer audit unavailable for current pointer " + pointer.tenantId() @@ -47,7 +72,16 @@ ListAdmissionPointersResponse listAdmissionPointers() { + "/" + pointer.realmSlug()); } - return toCurrentEntry(pointer, audit.getFirst()); + if (!matchesCurrentPointer(pointer, latestAudit)) { + throw new AdmissionPointerAuditUnavailableException( + "Admission pointer audit does not match current pointer " + + pointer.tenantId() + + ":" + + pointer.worldSlug() + + "/" + + pointer.realmSlug()); + } + return toEntry(latestAudit); }) .toList(); return ListAdmissionPointersResponse.newBuilder().addAllPointers(entries).build(); @@ -58,7 +92,7 @@ ListAdmissionPointerAuditResponse listAdmissionPointerAudit( long tenantId = ControlPlaneRequestParser.parsePositiveLong(request.getTenantId(), "tenant_id"); requireText(request.getWorldSlug(), "world_slug is required"); requireText(request.getRealmSlug(), "realm_slug is required"); - java.util.List audit = + List audit = gameplayAdmissionPointerAuthorityService.listPointerAudit( tenantId, request.getWorldSlug(), request.getRealmSlug()); if (audit.isEmpty()) { @@ -84,8 +118,8 @@ ExecutePreparedVersionCutoverResponse executePreparedVersionCutover( requireText(request.getActorPrincipal(), "actor_principal is required"); requireText(request.getControlPlaneRequestId(), "control_plane_request_id is required"); throw new AdmissionPointerMutationPreconditionException( - "prepared cutover is temporarily disabled until catalog revision preconditions " - + "are supported"); + "prepared cutover is temporarily disabled until catalog revision preconditions, " + + "World hold binding, source drain, and durable execution contracts are supported"); } private AdmissionPointerControlPlaneEntry toEntry(GameplayAdmissionPointerAuditEntry entry) { @@ -107,7 +141,7 @@ private AdmissionPointerControlPlaneEntry toEntry(GameplayAdmissionPointerAuditE .setReason(entry.reason()) .setControlPlaneRequestId(entry.controlPlaneRequestId()) .setOccurredAtMs(entry.occurredAt().toEpochMilli()); - if (entry.catalogRevision() != null) { + if (entry.catalogRevision() != null && entry.catalogRevision() > 0L) { builder.setCatalogRevision(entry.catalogRevision()); } if (entry.realmId() != null) { @@ -122,39 +156,28 @@ private AdmissionPointerControlPlaneEntry toEntry(GameplayAdmissionPointerAuditE return builder.build(); } - private AdmissionPointerControlPlaneEntry toCurrentEntry( - GameplayAdmissionPointerSnapshot pointer, GameplayAdmissionPointerAuditEntry auditEntry) { - AdmissionPointerControlPlaneEntry.Builder builder = - AdmissionPointerControlPlaneEntry.newBuilder() - .setWorldSlug(pointer.worldSlug()) - .setWorldDisplayName(pointer.worldDisplayName()) - .setRealmSlug(pointer.realmSlug()) - .setRealmDisplayName(pointer.realmDisplayName()) - .setTenantId(Long.toString(pointer.tenantId())) - .setGameInstanceId(Long.toString(pointer.gameInstanceId())) - .setPointerVersion(pointer.pointerVersion()) - .setVisible(pointer.visible()) - .setPublicProductionRealm(pointer.publicProductionRealm()) - .setRequiresCharacterSelection(pointer.requiresCharacterSelection()) - .setStateScope(pointer.stateScope()) - .setCharacterCreationPolicy(pointer.characterCreationPolicy()) - .setActorPrincipal(auditEntry.actorPrincipal()) - .setReason(auditEntry.reason()) - .setControlPlaneRequestId(auditEntry.controlPlaneRequestId()) - .setOccurredAtMs(auditEntry.occurredAt().toEpochMilli()); - if (pointer.catalogRevision() > 0) { - builder.setCatalogRevision(pointer.catalogRevision()); - } - if (pointer.realmId() != null) { - builder.setRealmId(pointer.realmId().toString()); - } - if (pointer.playableStateNamespaceId() != null) { - builder.setPlayableStateNamespaceId(pointer.playableStateNamespaceId().toString()); - } - if (!normalizeBlank(auditEntry.preparedVersionUpgradeId()).isEmpty()) { - builder.setPreparedVersionUpgradeId(auditEntry.preparedVersionUpgradeId()); - } - return builder.build(); + private static boolean matchesCurrentPointer( + GameplayAdmissionPointerSnapshot pointer, GameplayAdmissionPointerAuditEntry audit) { + return Objects.equals(pointer.worldSlug(), audit.worldSlug()) + && Objects.equals(pointer.worldDisplayName(), audit.worldDisplayName()) + && Objects.equals(pointer.realmSlug(), audit.realmSlug()) + && Objects.equals(pointer.realmDisplayName(), audit.realmDisplayName()) + && pointer.tenantId() == audit.tenantId() + && pointer.gameInstanceId() == audit.gameInstanceId() + && pointer.pointerVersion() == audit.pointerVersion() + && pointer.catalogRevision() > 0L + && audit.catalogRevision() != null + && audit.catalogRevision() > 0L + && pointer.catalogRevision() == audit.catalogRevision() + && pointer.realmId() != null + && pointer.realmId().equals(audit.realmId()) + && pointer.playableStateNamespaceId() != null + && pointer.playableStateNamespaceId().equals(audit.playableStateNamespaceId()) + && pointer.visible() == audit.visible() + && pointer.publicProductionRealm() == audit.publicProductionRealm() + && pointer.requiresCharacterSelection() == audit.requiresCharacterSelection() + && Objects.equals(pointer.stateScope(), audit.stateScope()) + && Objects.equals(pointer.characterCreationPolicy(), audit.characterCreationPolicy()); } private String normalizeBlank(String value) { 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 277694ac44..bfe78ed281 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,6 +4,12 @@ import io.grpc.stub.StreamObserver; import io.micrometer.core.annotation.Timed; import io.micrometer.core.instrument.MeterRegistry; +import java.sql.SQLException; +import java.sql.SQLNonTransientConnectionException; +import java.sql.SQLRecoverableException; +import java.sql.SQLTimeoutException; +import java.sql.SQLTransientConnectionException; +import java.util.List; import java.util.Objects; import java.util.UUID; import java.util.regex.Pattern; @@ -80,6 +86,9 @@ import org.slf4j.LoggerFactory; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.beans.factory.annotation.Value; +import org.springframework.dao.DataAccessResourceFailureException; +import org.springframework.dao.QueryTimeoutException; +import org.springframework.dao.TransientDataAccessResourceException; import org.springframework.grpc.server.service.GrpcService; @GrpcService @@ -140,6 +149,14 @@ private long parseTenantId(String tenantId) { return ControlPlaneRequestParser.parsePositiveLong(tenantId, "tenant_id"); } + private long requireTenantAccess(String tenantId) { + long parsedTenantId = parseTenantId(tenantId); + if (!SessionContext.hasTenantAccess(parsedTenantId)) { + throw new AdminAuthorizationException("Tenant access required"); + } + return parsedTenantId; + } + private long parseGameInstanceId(String gameInstanceId) { return ControlPlaneRequestParser.parsePositiveLong(gameInstanceId, "game_instance_id"); } @@ -179,6 +196,48 @@ private ErrorDetail automationAdmissionReceiverFenceUnavailable(String operation AUTOMATION_ADMISSION_RECEIVER_FENCE_UNAVAILABLE); } + private ErrorDetail admissionPointerAuthorityUnavailableError(String operation) { + return authorityUnavailableError(operation, "Admission pointer authority unavailable"); + } + + private ErrorDetail authorityUnavailableError(String operation, String message) { + return GrpcAppErrors.error(meterRegistry, logger, operation, "AUTHORITY_UNAVAILABLE", message); + } + + private static boolean isPersistenceAvailabilityFailure(Throwable failure) { + Throwable cause = failure; + for (int depth = 0; cause != null && depth < 32; depth++) { + if (cause instanceof DataAccessResourceFailureException + || cause instanceof QueryTimeoutException + || cause instanceof TransientDataAccessResourceException + || cause instanceof SQLNonTransientConnectionException + || cause instanceof SQLRecoverableException + || cause instanceof SQLTimeoutException + || cause instanceof SQLTransientConnectionException) { + return true; + } + if (cause instanceof SQLException sqlException) { + String sqlState = sqlException.getSQLState(); + if (sqlState != null + && (sqlState.startsWith("08") + || "57014".equals(sqlState) + || "HYT00".equals(sqlState) + || "HYT01".equals(sqlState) + || "57P01".equals(sqlState) + || "57P02".equals(sqlState) + || "57P03".equals(sqlState))) { + return true; + } + } + Throwable next = cause.getCause(); + if (next == cause) { + break; + } + cause = next; + } + return false; + } + @Override @Timed(value = "gamesessionGrpc.controlPlane.getInitialAdmissionBindProof") public void getInitialAdmissionBindProof( @@ -348,8 +407,8 @@ public void listAdmissionPointers( ListAdmissionPointersRequest request, StreamObserver responseObserver) { try { - requireAdminRole(); - responseObserver.onNext(admissionPointerControlPlaneService.listAdmissionPointers()); + List tenantIds = validateAdmissionPointerListScope(request.getTenantIdsList()); + responseObserver.onNext(admissionPointerControlPlaneService.listAdmissionPointers(tenantIds)); responseObserver.onCompleted(); } catch (AdminAuthorizationException ex) { ListAdmissionPointersResponse response = @@ -358,21 +417,32 @@ public void listAdmissionPointers( .build(); responseObserver.onNext(response); responseObserver.onCompleted(); + } catch (IllegalArgumentException ex) { + ListAdmissionPointersResponse response = + ListAdmissionPointersResponse.newBuilder() + .setError(invalidArgumentError("ListAdmissionPointers", ex)) + .build(); + responseObserver.onNext(response); + responseObserver.onCompleted(); } catch (AdmissionPointerAuditUnavailableException ex) { logger.warn("ListAdmissionPointers authority unavailable", ex); ListAdmissionPointersResponse response = ListAdmissionPointersResponse.newBuilder() - .setError( - GrpcAppErrors.error( - meterRegistry, - logger, - "ListAdmissionPointers", - "AUTHORITY_UNAVAILABLE", - "Admission pointer audit authority unavailable")) + .setError(admissionPointerAuthorityUnavailableError("ListAdmissionPointers")) .build(); responseObserver.onNext(response); responseObserver.onCompleted(); } catch (Exception ex) { + if (isPersistenceAvailabilityFailure(ex)) { + logger.warn("ListAdmissionPointers persistence unavailable", ex); + ListAdmissionPointersResponse response = + ListAdmissionPointersResponse.newBuilder() + .setError(admissionPointerAuthorityUnavailableError("ListAdmissionPointers")) + .build(); + responseObserver.onNext(response); + responseObserver.onCompleted(); + return; + } logger.error("ListAdmissionPointers failed", ex); ListAdmissionPointersResponse response = ListAdmissionPointersResponse.newBuilder() @@ -383,13 +453,32 @@ public void listAdmissionPointers( } } + private List validateAdmissionPointerListScope(List tenantIds) { + if (tenantIds.isEmpty()) { + requireAdminRole(); + return List.of(); + } + + List validatedTenantIds = + tenantIds.stream() + .map(tenantId -> ControlPlaneRequestParser.parsePositiveLong(tenantId, "tenant_ids")) + .distinct() + .toList(); + for (long tenantId : validatedTenantIds) { + if (!SessionContext.hasTenantAccess(tenantId)) { + throw new AdminAuthorizationException("Tenant access required for admission pointer list"); + } + } + return validatedTenantIds; + } + @Override @Timed(value = "gamesessionGrpc.controlPlane.listAdmissionPointerAudit") public void listAdmissionPointerAudit( ListAdmissionPointerAuditRequest request, StreamObserver responseObserver) { try { - requireAdminRole(); + requireTenantAccess(request.getTenantId()); responseObserver.onNext( admissionPointerControlPlaneService.listAdmissionPointerAudit(request)); responseObserver.onCompleted(); @@ -414,6 +503,16 @@ public void listAdmissionPointerAudit( responseObserver.onNext(response); responseObserver.onCompleted(); } catch (Exception ex) { + if (isPersistenceAvailabilityFailure(ex)) { + logger.warn("ListAdmissionPointerAudit persistence unavailable", ex); + ListAdmissionPointerAuditResponse response = + ListAdmissionPointerAuditResponse.newBuilder() + .setError(admissionPointerAuthorityUnavailableError("ListAdmissionPointerAudit")) + .build(); + responseObserver.onNext(response); + responseObserver.onCompleted(); + return; + } logger.error("ListAdmissionPointerAudit failed", ex); ListAdmissionPointerAuditResponse response = ListAdmissionPointerAuditResponse.newBuilder() @@ -980,8 +1079,7 @@ public void getGameInstanceRuntimeState( GetGameInstanceRuntimeStateRequest request, StreamObserver responseObserver) { try { - requireAdminRole(); - long tenantId = parseTenantId(request.getTenantId()); + long tenantId = requireTenantAccess(request.getTenantId()); GetGameInstanceRuntimeStateResponse response = GetGameInstanceRuntimeStateResponse.newBuilder() .setRuntimeState( @@ -1017,6 +1115,18 @@ public void getGameInstanceRuntimeState( responseObserver.onNext(response); responseObserver.onCompleted(); } catch (Exception ex) { + if (isPersistenceAvailabilityFailure(ex)) { + logger.warn("GetGameInstanceRuntimeState persistence unavailable", ex); + GetGameInstanceRuntimeStateResponse response = + GetGameInstanceRuntimeStateResponse.newBuilder() + .setError( + authorityUnavailableError( + "GetGameInstanceRuntimeState", "Runtime state authority unavailable")) + .build(); + responseObserver.onNext(response); + responseObserver.onCompleted(); + return; + } logger.error("GetGameInstanceRuntimeState failed", ex); GetGameInstanceRuntimeStateResponse response = GetGameInstanceRuntimeStateResponse.newBuilder() @@ -1145,10 +1255,10 @@ public void validateInstanceCutoverCompatibility( ValidateInstanceCutoverCompatibilityRequest request, StreamObserver responseObserver) { try { - requireAdminRole(); + long tenantId = requireTenantAccess(request.getTenantId()); responseObserver.onNext( versionUpgradeControlPlaneService.validateInstanceCutoverCompatibility( - parseTenantId(request.getTenantId()), + tenantId, parseGameInstanceId(request.getSourceGameInstanceId()), parseGameInstanceId(request.getTargetVersionId()))); responseObserver.onCompleted(); @@ -1222,10 +1332,10 @@ public void getPreparedVersionUpgrade( GetPreparedVersionUpgradeRequest request, StreamObserver responseObserver) { try { - requireAdminRole(); + long tenantId = requireTenantAccess(request.getTenantId()); responseObserver.onNext( versionUpgradeControlPlaneService.getPreparedVersionUpgrade( - parseTenantId(request.getTenantId()), request.getPreparationId())); + tenantId, request.getPreparationId())); responseObserver.onCompleted(); } catch (AdminAuthorizationException ex) { GetPreparedVersionUpgradeResponse response = @@ -1242,6 +1352,19 @@ public void getPreparedVersionUpgrade( responseObserver.onNext(response); responseObserver.onCompleted(); } catch (Exception ex) { + if (isPersistenceAvailabilityFailure(ex)) { + logger.warn("GetPreparedVersionUpgrade persistence unavailable", ex); + GetPreparedVersionUpgradeResponse response = + GetPreparedVersionUpgradeResponse.newBuilder() + .setError( + authorityUnavailableError( + "GetPreparedVersionUpgrade", + "Prepared version upgrade authority unavailable")) + .build(); + responseObserver.onNext(response); + responseObserver.onCompleted(); + return; + } logger.error("GetPreparedVersionUpgrade failed", ex); GetPreparedVersionUpgradeResponse response = GetPreparedVersionUpgradeResponse.newBuilder() diff --git a/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/service/impl/GameSessionGrpcService.java b/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/service/impl/GameSessionGrpcService.java index 4c46634732..d415a8532e 100644 --- a/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/service/impl/GameSessionGrpcService.java +++ b/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/service/impl/GameSessionGrpcService.java @@ -559,9 +559,10 @@ public void listGameplayRealms( ListGameplayRealmsRequest request, StreamObserver responseObserver) { try { + String worldSelector = requireWorldSelector(request.getWorldSlug()); WorldView world = gameplayWorldCatalog - .resolvePublicWorldFromAuthoritySnapshot(request.getWorldSlug()) + .resolvePublicWorldFromAuthoritySnapshot(worldSelector) .orElseThrow(() -> new IllegalArgumentException("Unknown gameplay world selection")); List realms = gameplayWorldCatalog.visibleRealms(world).stream() @@ -841,6 +842,17 @@ private net.firedevops.firemud.gamesession.v1.GameplayRealm toGameplayRealm( .build(); } + private static String requireWorldSelector(String worldSelector) { + if (worldSelector == null || worldSelector.isBlank()) { + throw new IllegalArgumentException("worldSlug is required"); + } + String trimmed = worldSelector.trim(); + if (!trimmed.matches("[A-Za-z0-9]+(?:-[A-Za-z0-9]+)*")) { + throw new IllegalArgumentException("worldSlug must be a valid selector"); + } + return trimmed; + } + private static String requireIdentity(java.util.UUID identity, String fieldName) { if (identity == null) { throw new AuthorityProjectionUnavailableException( diff --git a/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/service/impl/GameSessionRuntimeControlPlaneReadService.java b/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/service/impl/GameSessionRuntimeControlPlaneReadService.java index a9392253b3..0a876ed6f6 100644 --- a/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/service/impl/GameSessionRuntimeControlPlaneReadService.java +++ b/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/service/impl/GameSessionRuntimeControlPlaneReadService.java @@ -373,7 +373,9 @@ private GameplayRoutingBundle toGameplayRoutingBundle(GameplayAdmissionPointerSn private AdmissionPointerControlPlaneEntry toControlPlaneEntry( GameplayAdmissionPointerSnapshot pointer) { - if (pointer.catalogRevision() <= 0L + if (pointer.tenantId() <= 0L + || pointer.gameInstanceId() <= 0L + || pointer.catalogRevision() <= 0L || pointer.realmId() == null || pointer.playableStateNamespaceId() == null) { throw new RuntimeStateException( diff --git a/services/game-session-service/src/test/java/integration/net/firedevops/firemud/gamesession/service/GameplayAdmissionPointerCasPostgresIntegrationTest.java b/services/game-session-service/src/test/java/integration/net/firedevops/firemud/gamesession/service/GameplayAdmissionPointerCasPostgresIntegrationTest.java new file mode 100644 index 0000000000..7332dd2f2c --- /dev/null +++ b/services/game-session-service/src/test/java/integration/net/firedevops/firemud/gamesession/service/GameplayAdmissionPointerCasPostgresIntegrationTest.java @@ -0,0 +1,376 @@ +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.List; +import java.util.Objects; +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.gamesession.repository.GameplayAdmissionPointerEventRepository; +import net.firedevops.firemud.gamesession.repository.GameplayAdmissionPointerRepository; +import net.firedevops.firemud.gamesession.service.impl.DatabaseGameplayAdmissionPointerAuthorityService; +import org.flywaydb.core.Flyway; +import org.jooq.DSLContext; +import org.jooq.SQLDialect; +import org.jooq.impl.DSL; +import org.junit.jupiter.api.BeforeEach; +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 GameplayAdmissionPointerCasPostgresIntegrationTest { + private static final String MIGRATION_LOCATION = + "filesystem:" + Path.of("src/main/resources/db/migration").toAbsolutePath().normalize(); + private static final long TENANT_ID = 419L; + private static final long INITIAL_GAME_INSTANCE_ID = 8201L; + private static final String WORLD_SLUG = "cas-world"; + private static final String REALM_SLUG = "cas-realm"; + + @Container + static PostgreSQLContainer postgres = + new PostgreSQLContainer<>("postgres:16-alpine") + .withCommand("postgres", "-c", "fsync=off", "-c", "track_activity_query_size=128"); + + @BeforeEach + void migrateIsolatedContainerSchema() { + DriverManagerDataSource dataSource = dataSource(); + Flyway flyway = + Flyway.configure() + .dataSource(dataSource) + .locations(MIGRATION_LOCATION) + .cleanDisabled(false) + .load(); + flyway.clean(); + flyway.migrate(); + } + + @Test + void competingWritersWithSamePositiveVersionPairCommitOnePointerAndAudit() throws Exception { + Fixture fixture = fixture(); + GameplayAdmissionPointerSnapshot initial = + fixture + .transactionTemplate() + .execute( + status -> + fixture + .service() + .upsertPointer( + mutation( + "Initial World", + INITIAL_GAME_INSTANCE_ID, + 0L, + 0L, + "initial-pointer"))); + assertThat(initial).isNotNull(); + assertThat(initial.pointerVersion()).isEqualTo(1L); + assertThat(initial.catalogRevision()).isEqualTo(1L); + assertThat(fixture.service().listPointerAudit(TENANT_ID, WORLD_SLUG, REALM_SLUG)).hasSize(1); + + CountDownLatch winningTransactionReady = new CountDownLatch(1); + CountDownLatch releaseWinningTransaction = new CountDownLatch(1); + CountDownLatch competingTransactionReady = new CountDownLatch(1); + AtomicInteger winningBackendPid = new AtomicInteger(); + AtomicInteger competingBackendPid = new AtomicInteger(); + ExecutorService executor = + Executors.newFixedThreadPool( + 2, + task -> { + Thread thread = new Thread(task, "admission-pointer-cas-test"); + thread.setDaemon(true); + return thread; + }); + Future first = + executor.submit( + () -> { + try { + GameplayAdmissionPointerSnapshot snapshot = + fixture + .transactionTemplate() + .execute( + status -> { + fixture.dsl().execute("SET LOCAL statement_timeout = '30000ms'"); + var backendPidRecord = + Objects.requireNonNull( + fixture.dsl().fetchOne("select pg_backend_pid()"), + "Winning backend PID query returned no row"); + winningBackendPid.set( + Objects.requireNonNull( + backendPidRecord.get(0, Integer.class), + "Winning backend PID query returned no value")); + GameplayAdmissionPointerSnapshot updated = + fixture + .service() + .upsertPointer( + mutation( + "Concurrent World A", + INITIAL_GAME_INSTANCE_ID, + 1L, + 1L, + "writer-a")); + winningTransactionReady.countDown(); + awaitLatch( + releaseWinningTransaction, + "release of winning pointer transaction"); + return updated; + }); + return new MutationAttempt(snapshot, null); + } catch (Throwable failure) { + return new MutationAttempt(null, failure); + } + }); + Future second = + executor.submit( + () -> { + try { + GameplayAdmissionPointerSnapshot snapshot = + fixture + .transactionTemplate() + .execute( + status -> { + fixture.dsl().execute("SET LOCAL statement_timeout = '30000ms'"); + var backendPidRecord = + Objects.requireNonNull( + fixture.dsl().fetchOne("select pg_backend_pid()"), + "Competing backend PID query returned no row"); + competingBackendPid.set( + Objects.requireNonNull( + backendPidRecord.get(0, Integer.class), + "Competing backend PID query returned no value")); + competingTransactionReady.countDown(); + awaitLatch( + winningTransactionReady, + "winning pointer transaction to acquire and hold its row lock"); + return fixture + .service() + .upsertPointer( + mutation( + "Concurrent World B", + INITIAL_GAME_INSTANCE_ID, + 1L, + 1L, + "writer-b")); + }); + return new MutationAttempt(snapshot, null); + } catch (Throwable failure) { + return new MutationAttempt(null, failure); + } + }); + + try { + assertThat(winningTransactionReady.await(10, TimeUnit.SECONDS)).isTrue(); + assertThat(competingTransactionReady.await(10, TimeUnit.SECONDS)).isTrue(); + assertThat(winningBackendPid.get()).isPositive(); + assertThat(competingBackendPid.get()).isPositive(); + assertThat(competingBackendPid.get()).isNotEqualTo(winningBackendPid.get()); + awaitPostgresRowLockWait(fixture.dsl(), competingBackendPid.get(), winningBackendPid.get()); + releaseWinningTransaction.countDown(); + + List attempts = + List.of(first.get(20, TimeUnit.SECONDS), second.get(20, TimeUnit.SECONDS)); + List winners = attempts.stream().filter(MutationAttempt::succeeded).toList(); + List conflicts = + attempts.stream().filter(attempt -> !attempt.succeeded()).toList(); + + assertThat(winners).hasSize(1); + assertThat(conflicts).hasSize(1); + assertThat(conflicts.get(0).failure()) + .isInstanceOf(AdmissionPointerVersionMismatchException.class); + + GameplayAdmissionPointerSnapshot current = + fixture.service().findPointer(TENANT_ID, WORLD_SLUG, REALM_SLUG).orElseThrow(); + assertThat(current.pointerVersion()).isEqualTo(initial.pointerVersion()); + assertThat(current.catalogRevision()).isEqualTo(initial.catalogRevision() + 1L); + assertThat(current.worldDisplayName()).isIn("Concurrent World A", "Concurrent World B"); + + List audit = + fixture.service().listPointerAudit(TENANT_ID, WORLD_SLUG, REALM_SLUG); + assertThat(audit).hasSize(2); + assertThat(audit.get(0).catalogRevision()).isEqualTo(current.catalogRevision()); + assertThat(audit.get(0).worldDisplayName()).isEqualTo(current.worldDisplayName()); + } finally { + releaseWinningTransaction.countDown(); + executor.shutdownNow(); + assertThat(executor.awaitTermination(10, TimeUnit.SECONDS)).isTrue(); + } + } + + @Test + void auditInsertFailureRollsBackPointerRevisionAndRuntimeTarget() { + Fixture fixture = fixture(); + GameplayAdmissionPointerSnapshot initial = + fixture + .transactionTemplate() + .execute( + status -> + fixture + .service() + .upsertPointer( + mutation( + "Initial World", + INITIAL_GAME_INSTANCE_ID, + 0L, + 0L, + "initial-pointer"))); + assertThat(initial).isNotNull(); + List initialAudit = + fixture.service().listPointerAudit(TENANT_ID, WORLD_SLUG, REALM_SLUG); + assertThat(initialAudit).hasSize(1); + + fixture + .dsl() + .execute( + "CREATE FUNCTION reject_gameplay_admission_audit() RETURNS trigger LANGUAGE plpgsql " + + "AS $$ BEGIN RAISE EXCEPTION 'forced admission audit insert failure'; " + + "END; $$"); + fixture + .dsl() + .execute( + "CREATE TRIGGER reject_gameplay_admission_audit BEFORE INSERT ON " + + "gameplay_admission_pointer_event FOR EACH ROW EXECUTE FUNCTION " + + "reject_gameplay_admission_audit()"); + + assertThatThrownBy( + () -> + fixture + .transactionTemplate() + .execute( + status -> + fixture + .service() + .upsertPointer( + mutation( + "Initial World", + INITIAL_GAME_INSTANCE_ID + 1L, + initial.pointerVersion(), + initial.catalogRevision(), + "failed-audit")))) + .isInstanceOf(RuntimeException.class) + .hasMessageContaining("forced admission audit insert failure"); + + GameplayAdmissionPointerSnapshot current = + fixture.service().findPointer(TENANT_ID, WORLD_SLUG, REALM_SLUG).orElseThrow(); + assertThat(current.pointerVersion()).isEqualTo(initial.pointerVersion()); + assertThat(current.catalogRevision()).isEqualTo(initial.catalogRevision()); + assertThat(current.gameInstanceId()).isEqualTo(initial.gameInstanceId()); + assertThat(current.worldDisplayName()).isEqualTo(initial.worldDisplayName()); + assertThat(fixture.service().listPointerAudit(TENANT_ID, WORLD_SLUG, REALM_SLUG)) + .containsExactlyElementsOf(initialAudit); + } + + private static void awaitPostgresRowLockWait(DSLContext dsl, int waiterPid, int blockerPid) { + long deadline = System.nanoTime() + TimeUnit.SECONDS.toNanos(10); + boolean blockedByWinner = false; + while (System.nanoTime() < deadline) { + // Activity SQL can be truncated, so lock state and blocker PIDs are the oracle. + var lockWaitRecord = + Objects.requireNonNull( + dsl.fetchOne( + "SELECT EXISTS (SELECT 1 FROM pg_stat_activity WHERE pid = ? " + + "AND wait_event_type = 'Lock' " + + "AND ? = ANY(pg_blocking_pids(pid)))", + waiterPid, + blockerPid), + "PostgreSQL lock-wait query returned no row"); + blockedByWinner = + Objects.requireNonNull( + lockWaitRecord.get(0, Boolean.class), "PostgreSQL lock-wait query returned no value"); + if (blockedByWinner) { + break; + } + try { + Thread.sleep(10L); + } catch (InterruptedException exception) { + Thread.currentThread().interrupt(); + throw new IllegalStateException( + "Interrupted while observing PostgreSQL row lock wait", exception); + } + } + assertThat(blockedByWinner) + .as("competing backend waits on a PostgreSQL lock held by the winning transaction") + .isTrue(); + } + + private static void awaitLatch(CountDownLatch latch, String awaitedState) { + try { + if (!latch.await(30, TimeUnit.SECONDS)) { + throw new IllegalStateException("Timed out waiting for " + awaitedState); + } + } catch (InterruptedException exception) { + Thread.currentThread().interrupt(); + throw new IllegalStateException("Interrupted while waiting for " + awaitedState, exception); + } + } + + private static Fixture fixture() { + DriverManagerDataSource dataSource = dataSource(); + TransactionAwareDataSourceProxy transactionAwareDataSource = + new TransactionAwareDataSourceProxy(dataSource); + DSLContext dsl = DSL.using(transactionAwareDataSource, SQLDialect.POSTGRES); + TransactionTemplate transactionTemplate = + new TransactionTemplate(new DataSourceTransactionManager(dataSource)); + DatabaseGameplayAdmissionPointerAuthorityService service = + new DatabaseGameplayAdmissionPointerAuthorityService( + new GameplayAdmissionPointerRepository(dsl), + new GameplayAdmissionPointerEventRepository(dsl)); + return new Fixture(dsl, transactionTemplate, service); + } + + 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 GameplayAdmissionPointerMutation mutation( + String worldDisplayName, + long gameInstanceId, + long expectedPointerVersion, + long expectedCatalogRevision, + String requestId) { + return new GameplayAdmissionPointerMutation( + WORLD_SLUG, + worldDisplayName, + REALM_SLUG, + "CAS Realm", + TENANT_ID, + gameInstanceId, + true, + true, + false, + "SHARED", + "ALLOW_NEW", + "postgres-integration-test", + "verify pointer CAS transaction", + requestId, + expectedPointerVersion, + expectedCatalogRevision, + null); + } + + private record Fixture( + DSLContext dsl, + TransactionTemplate transactionTemplate, + DatabaseGameplayAdmissionPointerAuthorityService service) {} + + private record MutationAttempt(GameplayAdmissionPointerSnapshot snapshot, Throwable failure) { + private boolean succeeded() { + return failure == null; + } + } +} diff --git a/services/game-session-service/src/test/java/integration/net/firedevops/firemud/gamesession/websocket/GameSessionWebSocketHandlerIntegrationTest.java b/services/game-session-service/src/test/java/integration/net/firedevops/firemud/gamesession/websocket/GameSessionWebSocketHandlerIntegrationTest.java index 6d14a0662f..50a75aa443 100644 --- a/services/game-session-service/src/test/java/integration/net/firedevops/firemud/gamesession/websocket/GameSessionWebSocketHandlerIntegrationTest.java +++ b/services/game-session-service/src/test/java/integration/net/firedevops/firemud/gamesession/websocket/GameSessionWebSocketHandlerIntegrationTest.java @@ -41,6 +41,7 @@ import net.firedevops.firemud.gamesession.service.CommandService; import net.firedevops.firemud.gamesession.service.GameplayAdmissionPointerAuthorityService; import net.firedevops.firemud.gamesession.service.GameplayAdmissionPointerMutation; +import net.firedevops.firemud.gamesession.service.GameplayAdmissionPointerSnapshot; import net.firedevops.firemud.gamesession.service.GameplayPresence; import net.firedevops.firemud.gamesession.service.GameplayPresenceService; import net.firedevops.firemud.gamesession.service.SessionContextService; @@ -1663,7 +1664,7 @@ private void performLogoutFlow(String sessionId) throws Exception { private void bumpProductionAdmissionPointer( long newGameInstanceId, boolean requiresCharacterSelection) { - var currentPointer = + GameplayAdmissionPointerSnapshot currentPointer = gameplayAdmissionPointerAuthorityService.listPointers().stream() .filter( pointer -> @@ -1672,8 +1673,6 @@ private void bumpProductionAdmissionPointer( && "production".equals(pointer.realmSlug())) .findFirst() .orElseThrow(); - long expectedPointerVersion = currentPointer.pointerVersion(); - long expectedCatalogRevision = currentPointer.catalogRevision(); gameplayAdmissionPointerAuthorityService.upsertPointer( new GameplayAdmissionPointerMutation( "demo", @@ -1689,9 +1688,9 @@ private void bumpProductionAdmissionPointer( "ALLOW_NEW", "integration-test", "cutover-proof", - "req-cutover-" + newGameInstanceId + "-" + expectedPointerVersion, - expectedPointerVersion, - expectedCatalogRevision, + "req-cutover-" + newGameInstanceId + "-" + currentPointer.pointerVersion(), + currentPointer.pointerVersion(), + currentPointer.catalogRevision(), "integration-test-prep-" + newGameInstanceId)); } @@ -1736,6 +1735,12 @@ private void resetAdmissionPointers() { 0L, 0L, null)); + assertThat(gameplayAdmissionPointerAuthorityService.listPointers()) + .filteredOn( + pointer -> + pointer.tenantId() == 22L && pointer.visible() && pointer.publicProductionRealm()) + .extracting(GameplayAdmissionPointerSnapshot::worldSlug) + .containsExactly("demo"); } private static JsonNode json(String payload) { diff --git a/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/repository/GameplayAdmissionPointerEventRepositoryTest.java b/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/repository/GameplayAdmissionPointerEventRepositoryTest.java index 6636c2b259..8ddcdfdd87 100644 --- a/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/repository/GameplayAdmissionPointerEventRepositoryTest.java +++ b/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/repository/GameplayAdmissionPointerEventRepositoryTest.java @@ -6,9 +6,11 @@ import java.sql.Connection; import java.sql.DriverManager; import java.time.Instant; +import java.util.ArrayList; import java.util.List; import java.util.UUID; import net.firedevops.firemud.gamesession.entity.GameplayAdmissionPointerEvent; +import net.firedevops.firemud.gamesession.service.GameplayAdmissionPointerAuthorityService.PointerAuditKey; import org.jooq.DSLContext; import org.jooq.SQLDialect; import org.jooq.impl.DSL; @@ -37,19 +39,117 @@ void savesCatalogRevisionAndStableIdentityAndKeepsUnknownValuesNull() throws Exc repository.save(historical); List events = - repository.findByTenantIdAndWorldSlugAndRealmSlugOrderByOccurredAtDesc( - 9L, "demo", "production"); + repository.findByTenantIdAndWorldSlugAndRealmSlugOrderByIdDesc(9L, "demo", "production"); assertEquals(2, events.size()); - assertEquals(12L, events.get(0).getCatalogRevision()); - assertEquals(realmId, events.get(0).getRealmId()); - assertEquals(namespaceId, events.get(0).getPlayableStateNamespaceId()); - assertNull(events.get(1).getCatalogRevision()); - assertNull(events.get(1).getRealmId()); - assertNull(events.get(1).getPlayableStateNamespaceId()); + assertNull(events.get(0).getCatalogRevision()); + assertNull(events.get(0).getRealmId()); + assertNull(events.get(0).getPlayableStateNamespaceId()); + assertEquals(12L, events.get(1).getCatalogRevision()); + assertEquals(realmId, events.get(1).getRealmId()); + assertEquals(namespaceId, events.get(1).getPlayableStateNamespaceId()); } } + @Test + void findsLatestAuditByIdForExactMixedTenantPointerKeys() throws Exception { + try (Connection connection = + DriverManager.getConnection( + "jdbc:h2:mem:gameplay-pointer-event-latest-batch;MODE=PostgreSQL;DATABASE_TO_LOWER=TRUE;DB_CLOSE_DELAY=-1")) { + DSLContext dsl = DSL.using(connection, SQLDialect.H2); + createSchema(dsl); + GameplayAdmissionPointerEventRepository repository = + new GameplayAdmissionPointerEventRepository(dsl); + + GameplayAdmissionPointerEvent newestTenantNine = event("2026-09-10T00:00:00Z"); + repository.save(newestTenantNine); + GameplayAdmissionPointerEvent tenantTen = event("2026-09-08T00:00:00Z"); + tenantTen.setTenantId(10L); + repository.save(tenantTen); + GameplayAdmissionPointerEvent otherRealm = event("2026-09-07T00:00:00Z"); + otherRealm.setRealmSlug("playtest"); + repository.save(otherRealm); + GameplayAdmissionPointerEvent latestById = event("2026-09-01T00:00:00Z"); + repository.save(latestById); + GameplayAdmissionPointerEvent outsideSelection = event("2026-09-11T00:00:00Z"); + outsideSelection.setTenantId(11L); + repository.save(outsideSelection); + + List latest = + repository.findLatestByPointerKeys( + List.of( + new PointerAuditKey(9L, "demo", "production"), + new PointerAuditKey(10L, "demo", "production"), + new PointerAuditKey(9L, "demo", "playtest"))); + var byKey = + latest.stream() + .collect( + java.util.stream.Collectors.toMap( + audit -> + new PointerAuditKey( + audit.getTenantId(), audit.getWorldSlug(), audit.getRealmSlug()), + GameplayAdmissionPointerEvent::getControlPlaneRequestId)); + + assertEquals(3, latest.size()); + assertEquals( + "request-2026-09-01T00:00:00Z", byKey.get(new PointerAuditKey(9L, "demo", "production"))); + assertEquals( + "request-2026-09-08T00:00:00Z", + byKey.get(new PointerAuditKey(10L, "demo", "production"))); + assertEquals( + "request-2026-09-07T00:00:00Z", byKey.get(new PointerAuditKey(9L, "demo", "playtest"))); + } + } + + @Test + void chunksLargePointerKeySelectionsAndGloballyOrdersUniqueLatestEvents() throws Exception { + try (Connection connection = + DriverManager.getConnection( + "jdbc:h2:mem:gameplay-pointer-event-latest-chunks;MODE=PostgreSQL;DATABASE_TO_LOWER=TRUE;DB_CLOSE_DELAY=-1")) { + DSLContext dsl = DSL.using(connection, SQLDialect.H2); + createSchema(dsl); + GameplayAdmissionPointerEventRepository repository = + new GameplayAdmissionPointerEventRepository(dsl); + + List keys = new ArrayList<>(); + for (int index = 0; index <= 500; index++) { + keys.add(new PointerAuditKey(9L, "world-" + index, "realm")); + } + keys.add(keys.get(0)); + + GameplayAdmissionPointerEvent secondChunkFirstId = + repository.save(eventForKey(keys.get(500), "2026-09-10T00:00:00Z")); + repository.save(eventForKey(keys.get(0), "2026-09-12T00:00:00Z")); + GameplayAdmissionPointerEvent lastKeyInFirstChunk = + repository.save(eventForKey(keys.get(499), "2026-09-11T00:00:00Z")); + GameplayAdmissionPointerEvent latestFirstKey = + repository.save(eventForKey(keys.get(0), "2026-09-01T00:00:00Z")); + GameplayAdmissionPointerEvent unselectedTenant = event("2026-09-13T00:00:00Z"); + unselectedTenant.setTenantId(11L); + unselectedTenant.setWorldSlug("world-0"); + unselectedTenant.setRealmSlug("realm"); + repository.save(unselectedTenant); + + List latest = repository.findLatestByPointerKeys(keys); + + assertEquals(3, latest.size()); + assertEquals( + List.of(secondChunkFirstId.getId(), lastKeyInFirstChunk.getId(), latestFirstKey.getId()), + latest.stream().map(GameplayAdmissionPointerEvent::getId).toList()); + assertEquals( + List.of("world-500", "world-499", "world-0"), + latest.stream().map(GameplayAdmissionPointerEvent::getWorldSlug).toList()); + } + } + + private static GameplayAdmissionPointerEvent eventForKey(PointerAuditKey key, String occurredAt) { + GameplayAdmissionPointerEvent event = event(occurredAt); + event.setTenantId(key.tenantId()); + event.setWorldSlug(key.worldSlug()); + event.setRealmSlug(key.realmSlug()); + return event; + } + private static GameplayAdmissionPointerEvent event(String occurredAt) { GameplayAdmissionPointerEvent event = new GameplayAdmissionPointerEvent(); event.setWorldSlug("demo"); diff --git a/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/repository/GameplayAdmissionPointerRepositoryTest.java b/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/repository/GameplayAdmissionPointerRepositoryTest.java index 00e06dd5b4..a9aa71e28d 100644 --- a/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/repository/GameplayAdmissionPointerRepositoryTest.java +++ b/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/repository/GameplayAdmissionPointerRepositoryTest.java @@ -11,6 +11,7 @@ import java.util.List; import java.util.UUID; import net.firedevops.firemud.gamesession.entity.GameplayAdmissionPointer; +import net.firedevops.firemud.gamesession.entity.GameplayAdmissionPointerEvent; import net.firedevops.firemud.gamesession.service.AdmissionPointerVersionMismatchException; import org.jooq.DSLContext; import org.jooq.SQLDialect; @@ -23,7 +24,7 @@ class GameplayAdmissionPointerRepositoryTest { void tenantScopedListFiltersRowsInTheDatabaseBeforeMapping() throws Exception { try (Connection connection = DriverManager.getConnection( - "jdbc:h2:mem:gameplay-pointer-tenant-list;MODE=PostgreSQL;DATABASE_TO_LOWER=TRUE;DB_CLOSE_DELAY=-1")) { + "jdbc:h2:mem:gameplay-pointer-tenant-list-by-tenant;MODE=PostgreSQL;DATABASE_TO_LOWER=TRUE;DB_CLOSE_DELAY=-1")) { DSLContext dsl = DSL.using(connection, SQLDialect.H2); createSchema(dsl); GameplayAdmissionPointerRepository repository = new GameplayAdmissionPointerRepository(dsl); @@ -85,6 +86,27 @@ void stableRealmAndNamespaceIdentitySurviveRuntimeReplacement() throws Exception } } + @Test + void tenantScopedPointerListExcludesOtherTenants() throws Exception { + try (Connection connection = + DriverManager.getConnection( + "jdbc:h2:mem:gameplay-pointer-tenant-list-in;MODE=PostgreSQL;DATABASE_TO_LOWER=TRUE;DB_CLOSE_DELAY=-1")) { + DSLContext dsl = DSL.using(connection, SQLDialect.H2); + createSchema(dsl); + GameplayAdmissionPointerRepository repository = new GameplayAdmissionPointerRepository(dsl); + repository.save(pointer(7L, 44L, "SHARED", "production")); + repository.save(pointer(8L, 55L, "SHARED", "production")); + + var scoped = repository.findAllByTenantIdInOrderByWorldSlugAscRealmSlugAsc(List.of(8L)); + + assertEquals(1, scoped.size()); + assertEquals(8L, scoped.getFirst().getTenantId()); + assertEquals(2, repository.findAllByOrderByWorldSlugAscRealmSlugAsc().size()); + assertEquals( + List.of(), repository.findAllByTenantIdInOrderByWorldSlugAscRealmSlugAsc(List.of())); + } + } + @Test void repositoryRejectsAttemptToReplaceStableRealmIdentity() throws Exception { try (Connection connection = @@ -175,6 +197,41 @@ void rejectsSecondConcurrentRequestWhenWinnerCommittedTheSameTransition() throws } } + @Test + void pointerAuditOrdersByEventIdWhenPodTimestampMovesBackward() throws Exception { + try (Connection connection = + DriverManager.getConnection( + "jdbc:h2:mem:gameplay-pointer-audit-order;MODE=PostgreSQL;DATABASE_TO_LOWER=TRUE;DB_CLOSE_DELAY=-1")) { + DSLContext dsl = DSL.using(connection, SQLDialect.H2); + createAuditSchema(dsl); + GameplayAdmissionPointerEventRepository repository = + new GameplayAdmissionPointerEventRepository(dsl); + + GameplayAdmissionPointerEvent earlierWrite = pointerEvent("2026-09-29T10:00:00Z"); + GameplayAdmissionPointerEvent firstSaved = repository.save(earlierWrite); + GameplayAdmissionPointerEvent laterWriteWithSkewedClock = + pointerEvent("2026-09-29T09:00:00Z"); + GameplayAdmissionPointerEvent secondSaved = repository.save(laterWriteWithSkewedClock); + GameplayAdmissionPointerEvent otherTenantWrite = pointerEvent("2026-09-29T11:00:00Z"); + otherTenantWrite.setTenantId(8L); + repository.save(otherTenantWrite); + + var audit = + repository.findByTenantIdAndWorldSlugAndRealmSlugOrderByIdDesc(7L, "demo", "production"); + var latest = + repository + .findLatestByTenantIdAndWorldSlugAndRealmSlug(7L, "demo", "production") + .orElseThrow(); + + assertEquals(2, audit.size()); + assertEquals(secondSaved.getId(), audit.getFirst().getId()); + assertEquals(firstSaved.getId(), audit.get(1).getId()); + assertEquals(Instant.parse("2026-09-29T09:00:00Z"), audit.getFirst().getOccurredAt()); + assertEquals(secondSaved.getId(), latest.getId()); + assertEquals(Instant.parse("2026-09-29T09:00:00Z"), latest.getOccurredAt()); + } + } + @Test void h2FixtureEnforcesProductionCatalogAndRealmIdentityConstraints() throws Exception { try (Connection connection = @@ -279,4 +336,55 @@ CONSTRAINT uq_pointer_tenant_runtime UNIQUE (tenant_id, game_instance_id), "CREATE UNIQUE INDEX uq_gameplay_admission_pointer_realm_id " + "ON gameplay_admission_pointer (realm_id)"); } + + private static GameplayAdmissionPointerEvent pointerEvent(String occurredAt) { + GameplayAdmissionPointerEvent event = new GameplayAdmissionPointerEvent(); + event.setWorldSlug("demo"); + event.setRealmSlug("production"); + event.setWorldDisplayName("Demo World"); + event.setRealmDisplayName("Production"); + event.setTenantId(7L); + event.setGameInstanceId(44L); + event.setPointerVersion(1L); + event.setCatalogRevision(1L); + event.setVisible(true); + event.setPublicProductionRealm(true); + event.setRequiresCharacterSelection(false); + event.setStateScope("SHARED"); + event.setCharacterCreationPolicy("ALLOW_NEW"); + event.setActorPrincipal("tester"); + event.setReason("test"); + event.setControlPlaneRequestId(UUID.randomUUID().toString()); + event.setOccurredAt(Instant.parse(occurredAt)); + return event; + } + + private static void createAuditSchema(DSLContext dsl) { + dsl.execute( + """ + CREATE TABLE gameplay_admission_pointer_event ( + id BIGINT GENERATED BY DEFAULT AS IDENTITY PRIMARY KEY, + world_slug VARCHAR(120) NOT NULL, + realm_slug VARCHAR(120) NOT NULL, + world_display_name VARCHAR(200) NOT NULL, + realm_display_name VARCHAR(200) NOT NULL, + tenant_id BIGINT NOT NULL, + game_instance_id BIGINT NOT NULL, + pointer_version BIGINT NOT NULL, + catalog_revision BIGINT, + realm_id UUID, + playable_state_namespace_id UUID, + visible BOOLEAN NOT NULL, + public_production_realm BOOLEAN NOT NULL, + requires_character_selection BOOLEAN NOT NULL, + state_scope VARCHAR(32) NOT NULL, + character_creation_policy VARCHAR(32) NOT NULL, + actor_principal VARCHAR(200) NOT NULL, + reason VARCHAR(500) NOT NULL, + control_plane_request_id VARCHAR(120) NOT NULL, + prepared_version_upgrade_id VARCHAR(64), + occurred_at TIMESTAMP NOT NULL + ) + """); + } } diff --git a/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/service/impl/DatabaseGameplayAdmissionPointerAuthorityServiceTest.java b/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/service/impl/DatabaseGameplayAdmissionPointerAuthorityServiceTest.java index 9432abcfdc..c1a716266d 100644 --- a/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/service/impl/DatabaseGameplayAdmissionPointerAuthorityServiceTest.java +++ b/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/service/impl/DatabaseGameplayAdmissionPointerAuthorityServiceTest.java @@ -47,7 +47,8 @@ void upsertPointerRejectsMismatchedExpectedVersion() { existing.setPointerVersion(3L); existing.setCatalogRevision(4L); existing.setStateScope("SHARED"); - when(pointerRepository.findByTenantIdAndWorldSlugAndRealmSlug(1L, "demo", "production")) + when(pointerRepository.findByTenantIdAndWorldSlugAndRealmSlugForUpdate( + 1L, "demo", "production")) .thenReturn(Optional.of(existing)); assertThrows( @@ -121,8 +122,9 @@ void upsertPointerRejectsUnknownStateScope() { } @Test - void upsertPointerAllowsCreateWhenExpectedVersionIsZero() { - when(pointerRepository.findByTenantIdAndWorldSlugAndRealmSlug(1L, "demo", "production")) + void upsertPointerAllowsCreateWhenExpectedVersionPairIsZero() { + when(pointerRepository.findByTenantIdAndWorldSlugAndRealmSlugForUpdate( + 1L, "demo", "production")) .thenReturn(Optional.empty()); when(pointerRepository.save(any(GameplayAdmissionPointer.class))) .thenAnswer( @@ -160,13 +162,22 @@ void upsertPointerAllowsCreateWhenExpectedVersionIsZero() { verify(pointerRepository).save(pointerCaptor.capture()); assertEquals(1L, pointerCaptor.getValue().getPointerVersion()); assertEquals(1L, snapshot.pointerVersion()); - verify(eventRepository).save(any(GameplayAdmissionPointerEvent.class)); + assertEquals(1L, snapshot.catalogRevision()); + ArgumentCaptor eventCaptor = + ArgumentCaptor.forClass(GameplayAdmissionPointerEvent.class); + verify(eventRepository).save(eventCaptor.capture()); + assertEquals(1L, eventCaptor.getValue().getCatalogRevision()); + assertEquals(pointerCaptor.getValue().getRealmId(), eventCaptor.getValue().getRealmId()); + assertEquals( + pointerCaptor.getValue().getPlayableStateNamespaceId(), + eventCaptor.getValue().getPlayableStateNamespaceId()); } @Test void upsertPointerAdvancesCatalogRevisionWithoutAdvancingPointerVersion() { GameplayAdmissionPointer existing = existingPointer(); - when(pointerRepository.findByTenantIdAndWorldSlugAndRealmSlug(1L, "demo", "production")) + when(pointerRepository.findByTenantIdAndWorldSlugAndRealmSlugForUpdate( + 1L, "demo", "production")) .thenReturn(Optional.of(existing)); when(pointerRepository.updateExisting(any(GameplayAdmissionPointer.class), any(), any())) .thenAnswer(invocation -> invocation.getArgument(0)); @@ -209,7 +220,8 @@ void upsertPointerAdvancesCatalogRevisionWithoutAdvancingPointerVersion() { @Test void upsertPointerRuntimeTargetChangeAdvancesPointerVersionWithoutCatalogRevision() { GameplayAdmissionPointer existing = existingPointer(); - when(pointerRepository.findByTenantIdAndWorldSlugAndRealmSlug(1L, "demo", "production")) + when(pointerRepository.findByTenantIdAndWorldSlugAndRealmSlugForUpdate( + 1L, "demo", "production")) .thenReturn(Optional.of(existing)); when(pointerRepository.updateExisting(any(GameplayAdmissionPointer.class), any(), any())) .thenAnswer(invocation -> invocation.getArgument(0)); @@ -244,7 +256,8 @@ void upsertPointerRuntimeTargetChangeAdvancesPointerVersionWithoutCatalogRevisio @Test void upsertPointerExactNoOpDoesNotAdvanceOrPersistVersions() { GameplayAdmissionPointer existing = existingPointer(); - when(pointerRepository.findByTenantIdAndWorldSlugAndRealmSlug(1L, "demo", "production")) + when(pointerRepository.findByTenantIdAndWorldSlugAndRealmSlugForUpdate( + 1L, "demo", "production")) .thenReturn(Optional.of(existing)); GameplayAdmissionPointerSnapshot snapshot = @@ -270,10 +283,192 @@ void upsertPointerExactNoOpDoesNotAdvanceOrPersistVersions() { assertEquals(1L, snapshot.pointerVersion()); assertEquals(1L, snapshot.catalogRevision()); + verify(pointerRepository) + .findByTenantIdAndWorldSlugAndRealmSlugForUpdate(1L, "demo", "production"); verify(pointerRepository, never()).save(any(GameplayAdmissionPointer.class)); verifyNoInteractions(eventRepository); } + @Test + void upsertPointerRejectsStaleExpectedVersionsForExactNoOp() { + GameplayAdmissionPointer current = existingPointer(); + current.setPointerVersion(2L); + current.setCatalogRevision(2L); + when(pointerRepository.findByTenantIdAndWorldSlugAndRealmSlugForUpdate( + 1L, "demo", "production")) + .thenReturn(Optional.of(current)); + + assertThrows( + AdmissionPointerVersionMismatchException.class, + () -> + service.upsertPointer( + new GameplayAdmissionPointerMutation( + "demo", + "Demo World", + "production", + "Live Realm", + 1L, + 7L, + true, + true, + false, + "SHARED", + "ALLOW_NEW", + "tester", + "stale retry", + "req-stale-no-op", + 1L, + 1L, + null))); + + verify(pointerRepository) + .findByTenantIdAndWorldSlugAndRealmSlugForUpdate(1L, "demo", "production"); + verify(pointerRepository, never()).save(any(GameplayAdmissionPointer.class)); + verifyNoInteractions(eventRepository); + } + + @Test + void upsertPointerRejectsStaleCatalogRevisionEvenWhenPointerVersionMatches() { + GameplayAdmissionPointer existing = existingPointer(); + existing.setCatalogRevision(2L); + when(pointerRepository.findByTenantIdAndWorldSlugAndRealmSlugForUpdate( + 1L, "demo", "production")) + .thenReturn(Optional.of(existing)); + + assertThrows( + AdmissionPointerVersionMismatchException.class, + () -> + service.upsertPointer( + new GameplayAdmissionPointerMutation( + "demo", + "Stale Demo World", + "production", + "Live Realm", + 1L, + 7L, + true, + true, + false, + "SHARED", + "ALLOW_NEW", + "tester", + "stale catalog edit", + "req-stale-catalog", + 1L, + 1L, + null))); + + verify(pointerRepository, never()).save(any(GameplayAdmissionPointer.class)); + verifyNoInteractions(eventRepository); + } + + @Test + void upsertPointerRejectsExistingMutationWithoutExpectedPair() { + GameplayAdmissionPointer existing = existingPointer(); + when(pointerRepository.findByTenantIdAndWorldSlugAndRealmSlugForUpdate( + 1L, "demo", "production")) + .thenReturn(Optional.of(existing)); + + assertThrows( + AdmissionPointerVersionMismatchException.class, + () -> + service.upsertPointer( + new GameplayAdmissionPointerMutation( + "demo", + "Renamed Demo World", + "production", + "Live Realm", + 1L, + 7L, + true, + true, + false, + "SHARED", + "ALLOW_NEW", + "tester", + "missing precondition", + "req-missing-pair", + null, + null, + null))); + + verify(pointerRepository, never()).save(any(GameplayAdmissionPointer.class)); + verifyNoInteractions(eventRepository); + } + + @Test + void listPointerAuditExposesPersistedCatalogRevision() { + GameplayAdmissionPointerEvent event = new GameplayAdmissionPointerEvent(); + event.setWorldSlug("demo"); + event.setRealmSlug("production"); + event.setWorldDisplayName("Renamed Demo World"); + event.setRealmDisplayName("Live Realm"); + event.setTenantId(1L); + event.setGameInstanceId(7L); + event.setPointerVersion(1L); + event.setCatalogRevision(2L); + event.setRealmId(UUID.fromString("11111111-1111-1111-1111-111111111111")); + event.setPlayableStateNamespaceId(UUID.fromString("22222222-2222-2222-2222-222222222222")); + event.setStateScope("SHARED"); + event.setCharacterCreationPolicy("ALLOW_NEW"); + event.setOccurredAt(java.time.Instant.parse("2026-09-29T00:00:00Z")); + when(eventRepository.findByTenantIdAndWorldSlugAndRealmSlugOrderByIdDesc( + 1L, "demo", "production")) + .thenReturn(List.of(event)); + + var auditEntry = service.listPointerAudit(1L, "demo", "production").getFirst(); + assertEquals(2L, auditEntry.catalogRevision()); + assertEquals(event.getRealmId(), auditEntry.realmId()); + assertEquals(event.getPlayableStateNamespaceId(), auditEntry.playableStateNamespaceId()); + } + + @Test + void listPointersForTenantsUsesScopedRepositoryQuery() { + GameplayAdmissionPointer pointer = existingPointer(); + pointer.setTenantId(2L); + when(pointerRepository.findAllByTenantIdInOrderByWorldSlugAscRealmSlugAsc(List.of(2L))) + .thenReturn(List.of(pointer)); + + var snapshots = service.listPointersForTenants(List.of(2L)); + + assertEquals(1, snapshots.size()); + assertEquals(2L, snapshots.getFirst().tenantId()); + verify(pointerRepository).findAllByTenantIdInOrderByWorldSlugAscRealmSlugAsc(List.of(2L)); + verify(pointerRepository, never()).findAllByOrderByWorldSlugAscRealmSlugAsc(); + } + + @Test + void listPointerAuditPreservesPreV7UnknownRevisionAndIdentity() { + GameplayAdmissionPointerEvent historicalEvent = new GameplayAdmissionPointerEvent(); + historicalEvent.setWorldSlug("demo"); + historicalEvent.setRealmSlug("production"); + historicalEvent.setWorldDisplayName("Demo World"); + historicalEvent.setRealmDisplayName("Live Realm"); + historicalEvent.setTenantId(1L); + historicalEvent.setGameInstanceId(7L); + historicalEvent.setPointerVersion(1L); + historicalEvent.setStateScope("SHARED"); + historicalEvent.setCharacterCreationPolicy("ALLOW_NEW"); + historicalEvent.setActorPrincipal("legacy-operator"); + historicalEvent.setReason("retained pre-V7 event"); + historicalEvent.setControlPlaneRequestId("legacy-request"); + historicalEvent.setOccurredAt(java.time.Instant.parse("2026-09-29T00:00:00Z")); + when(eventRepository.findByTenantIdAndWorldSlugAndRealmSlugOrderByIdDesc( + 1L, "demo", "production")) + .thenReturn(List.of(historicalEvent)); + when(eventRepository.findLatestByTenantIdAndWorldSlugAndRealmSlug(1L, "demo", "production")) + .thenReturn(Optional.of(historicalEvent)); + + var auditEntry = service.listPointerAudit(1L, "demo", "production").getFirst(); + var latestEntry = service.findLatestPointerAudit(1L, "demo", "production").orElseThrow(); + assertNull(auditEntry.catalogRevision()); + assertNull(auditEntry.realmId()); + assertNull(auditEntry.playableStateNamespaceId()); + assertNull(latestEntry.catalogRevision()); + assertNull(latestEntry.realmId()); + assertNull(latestEntry.playableStateNamespaceId()); + } + @Test void findPointerByTenantAndRealmSlugDelegatesToRepository() { GameplayAdmissionPointer existing = new GameplayAdmissionPointer(); @@ -303,7 +498,7 @@ void listPointerAuditPreservesCatalogIdentityAndHistoricalAbsence() { populateAuditEvent(current, 3L, 4L, realmId, namespaceId); GameplayAdmissionPointerEvent historical = new GameplayAdmissionPointerEvent(); populateAuditEvent(historical, 2L, null, null, null); - when(eventRepository.findByTenantIdAndWorldSlugAndRealmSlugOrderByOccurredAtDesc( + when(eventRepository.findByTenantIdAndWorldSlugAndRealmSlugOrderByIdDesc( 1L, "demo", "production")) .thenReturn(java.util.List.of(current, historical)); @@ -322,7 +517,8 @@ void listPointerAuditPreservesCatalogIdentityAndHistoricalAbsence() { void catalogPolicyRevisionAdvancesIndependentlyFromPointerVersion() { java.util.concurrent.atomic.AtomicReference currentPointer = new java.util.concurrent.atomic.AtomicReference<>(); - when(pointerRepository.findByTenantIdAndWorldSlugAndRealmSlug(7L, "demo", "production")) + when(pointerRepository.findByTenantIdAndWorldSlugAndRealmSlugForUpdate( + 7L, "demo", "production")) .thenAnswer(invocation -> Optional.ofNullable(currentPointer.get())); when(pointerRepository.save(any(GameplayAdmissionPointer.class))) .thenAnswer( @@ -363,7 +559,8 @@ void catalogPolicyRevisionAdvancesIndependentlyFromPointerVersion() { void concurrentSameTransitionWinnerPreventsDuplicateAuditForStaleExpectedRevisions() { GameplayAdmissionPointer winnerRead = existingPointerForTenant(7L); GameplayAdmissionPointer staleRead = existingPointerForTenant(7L); - when(pointerRepository.findByTenantIdAndWorldSlugAndRealmSlug(7L, "demo", "production")) + when(pointerRepository.findByTenantIdAndWorldSlugAndRealmSlugForUpdate( + 7L, "demo", "production")) .thenReturn(Optional.of(winnerRead), Optional.of(staleRead)); java.util.concurrent.atomic.AtomicReference current = new java.util.concurrent.atomic.AtomicReference<>(existingPointerForTenant(7L)); @@ -410,7 +607,8 @@ void concurrentSameTransitionWinnerPreventsDuplicateAuditForStaleExpectedRevisio void existingPointerMutationRequiresMatchingCatalogRevisionEvenForNoOp() { GameplayAdmissionPointer existing = existingPointer(); existing.setTenantId(7L); - when(pointerRepository.findByTenantIdAndWorldSlugAndRealmSlug(7L, "demo", "production")) + when(pointerRepository.findByTenantIdAndWorldSlugAndRealmSlugForUpdate( + 7L, "demo", "production")) .thenReturn(Optional.of(existing)); assertThrows( @@ -447,7 +645,14 @@ private static GameplayAdmissionPointerMutation pointerMutation( publicProductionRealm, expectedPointerVersion, expectedCatalogRevision, - "catalog-revision-test-" + expectedPointerVersion); + "catalog-revision-test-" + + gameInstanceId + + "-" + + publicProductionRealm + + "-" + + expectedPointerVersion + + "-" + + expectedCatalogRevision); } private static GameplayAdmissionPointerMutation pointerMutation( @@ -514,8 +719,8 @@ private static GameplayAdmissionPointer existingPointer() { pointer.setGameInstanceId(7L); pointer.setPointerVersion(1L); pointer.setCatalogRevision(1L); - pointer.setRealmId(UUID.fromString("3ce19e6a-a63f-46f4-8e25-b105694c79e9")); - pointer.setPlayableStateNamespaceId(UUID.fromString("f673a1e6-648d-4ac3-8f3d-4b7cc4380f2a")); + pointer.setRealmId(UUID.fromString("11111111-1111-1111-1111-111111111111")); + pointer.setPlayableStateNamespaceId(UUID.fromString("22222222-2222-2222-2222-222222222222")); pointer.setVisible(true); pointer.setPublicProductionRealm(true); pointer.setRequiresCharacterSelection(false); diff --git a/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/service/impl/GameSessionAdmissionPointerControlPlaneServiceTest.java b/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/service/impl/GameSessionAdmissionPointerControlPlaneServiceTest.java new file mode 100644 index 0000000000..77b53aa1c5 --- /dev/null +++ b/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/service/impl/GameSessionAdmissionPointerControlPlaneServiceTest.java @@ -0,0 +1,210 @@ +package net.firedevops.firemud.gamesession.service.impl; + +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertThrows; +import static org.mockito.ArgumentMatchers.anyLong; +import static org.mockito.ArgumentMatchers.anyString; +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 java.nio.charset.StandardCharsets; +import java.time.Instant; +import java.util.List; +import java.util.Map; +import java.util.UUID; +import net.firedevops.firemud.gamesession.entity.GameplayAdmissionPointer; +import net.firedevops.firemud.gamesession.entity.GameplayAdmissionPointerEvent; +import net.firedevops.firemud.gamesession.repository.GameplayAdmissionPointerEventRepository; +import net.firedevops.firemud.gamesession.repository.GameplayAdmissionPointerRepository; +import net.firedevops.firemud.gamesession.service.GameplayAdmissionPointerAuditEntry; +import net.firedevops.firemud.gamesession.service.GameplayAdmissionPointerAuthorityService; +import net.firedevops.firemud.gamesession.service.GameplayAdmissionPointerAuthorityService.PointerAuditKey; +import net.firedevops.firemud.gamesession.service.GameplayAdmissionPointerSnapshot; +import org.junit.jupiter.api.Test; + +class GameSessionAdmissionPointerControlPlaneServiceTest { + @Test + void listQueriesTenantScopeBeforeBatchingExactLatestAuditKeys() { + GameplayAdmissionPointerAuthorityService authorityService = + mock(GameplayAdmissionPointerAuthorityService.class); + GameplayAdmissionPointerSnapshot tenantA = pointer(1L, "demo"); + GameplayAdmissionPointerSnapshot tenantB = pointer(2L, "demo"); + PointerAuditKey tenantBKey = new PointerAuditKey(2L, "demo", "production"); + when(authorityService.listPointersForTenants(List.of(2L))) + .thenReturn(List.of(tenantA, tenantB)); + when(authorityService.findLatestPointerAudits(List.of(tenantBKey))) + .thenReturn(Map.of(tenantBKey, audit(tenantB))); + GameSessionAdmissionPointerControlPlaneService controlPlaneService = + new GameSessionAdmissionPointerControlPlaneService(authorityService); + + var response = controlPlaneService.listAdmissionPointers(List.of(2L)); + + assertEquals(1, response.getPointersCount()); + assertEquals("2", response.getPointers(0).getTenantId()); + verify(authorityService).listPointersForTenants(List.of(2L)); + verify(authorityService, never()).listPointers(); + verify(authorityService).findLatestPointerAudits(List.of(tenantBKey)); + verify(authorityService, never()).findLatestPointerAudit(anyLong(), anyString(), anyString()); + } + + @Test + void listBatchesMixedTenantAuditKeysWithSameWorldSlug() { + GameplayAdmissionPointerAuthorityService authorityService = + mock(GameplayAdmissionPointerAuthorityService.class); + GameplayAdmissionPointerSnapshot tenantA = pointer(1L, "demo"); + GameplayAdmissionPointerSnapshot tenantB = pointer(2L, "demo"); + PointerAuditKey tenantAKey = new PointerAuditKey(1L, "demo", "production"); + PointerAuditKey tenantBKey = new PointerAuditKey(2L, "demo", "production"); + when(authorityService.listPointers()).thenReturn(List.of(tenantA, tenantB)); + when(authorityService.findLatestPointerAudits(List.of(tenantAKey, tenantBKey))) + .thenReturn(Map.of(tenantAKey, audit(tenantA), tenantBKey, audit(tenantB))); + GameSessionAdmissionPointerControlPlaneService controlPlaneService = + new GameSessionAdmissionPointerControlPlaneService(authorityService); + + var response = controlPlaneService.listAdmissionPointers(List.of()); + + assertEquals(2, response.getPointersCount()); + assertEquals("1", response.getPointers(0).getTenantId()); + assertEquals("2", response.getPointers(1).getTenantId()); + verify(authorityService).findLatestPointerAudits(List.of(tenantAKey, tenantBKey)); + verify(authorityService, never()).findLatestPointerAudit(anyLong(), anyString(), anyString()); + } + + @Test + void listFailsClosedWhenBatchAuditIsMissingOrDoesNotMatchCurrentPointer() { + GameplayAdmissionPointerAuthorityService authorityService = + mock(GameplayAdmissionPointerAuthorityService.class); + GameplayAdmissionPointerSnapshot currentPointer = pointer(2L, "tenant-b"); + PointerAuditKey key = new PointerAuditKey(2L, "tenant-b", "production"); + when(authorityService.listPointers()).thenReturn(List.of(currentPointer)); + GameSessionAdmissionPointerControlPlaneService controlPlaneService = + new GameSessionAdmissionPointerControlPlaneService(authorityService); + + when(authorityService.findLatestPointerAudits(List.of(key))).thenReturn(Map.of()); + assertThrows( + AdmissionPointerAuditUnavailableException.class, + () -> controlPlaneService.listAdmissionPointers(List.of())); + + when(authorityService.findLatestPointerAudits(List.of(key))) + .thenReturn(Map.of(key, audit(currentPointer, currentPointer.pointerVersion() + 1L))); + assertThrows( + AdmissionPointerAuditUnavailableException.class, + () -> controlPlaneService.listAdmissionPointers(List.of())); + verify(authorityService, never()).findLatestPointerAudit(anyLong(), anyString(), anyString()); + } + + @Test + void listRejectsRetainedPreV7AuditWithUnknownRevisionAndIdentity() { + GameplayAdmissionPointerRepository pointerRepository = + mock(GameplayAdmissionPointerRepository.class); + GameplayAdmissionPointerEventRepository eventRepository = + mock(GameplayAdmissionPointerEventRepository.class); + + UUID realmId = UUID.fromString("11111111-1111-1111-1111-111111111111"); + UUID namespaceId = UUID.fromString("22222222-2222-2222-2222-222222222222"); + GameplayAdmissionPointer currentPointer = new GameplayAdmissionPointer(); + currentPointer.setWorldSlug("demo"); + currentPointer.setWorldDisplayName("Demo World"); + currentPointer.setRealmSlug("production"); + currentPointer.setRealmDisplayName("Live Realm"); + currentPointer.setTenantId(1L); + currentPointer.setGameInstanceId(7L); + currentPointer.setPointerVersion(1L); + currentPointer.setCatalogRevision(1L); + currentPointer.setRealmId(realmId); + currentPointer.setPlayableStateNamespaceId(namespaceId); + currentPointer.setVisible(true); + currentPointer.setPublicProductionRealm(true); + currentPointer.setRequiresCharacterSelection(false); + currentPointer.setStateScope("SHARED"); + currentPointer.setCharacterCreationPolicy("ALLOW_NEW"); + + GameplayAdmissionPointerEvent retainedPreV7Event = new GameplayAdmissionPointerEvent(); + retainedPreV7Event.setWorldSlug("demo"); + retainedPreV7Event.setWorldDisplayName("Demo World"); + retainedPreV7Event.setRealmSlug("production"); + retainedPreV7Event.setRealmDisplayName("Live Realm"); + retainedPreV7Event.setTenantId(1L); + retainedPreV7Event.setGameInstanceId(7L); + retainedPreV7Event.setPointerVersion(1L); + retainedPreV7Event.setVisible(true); + retainedPreV7Event.setPublicProductionRealm(true); + retainedPreV7Event.setRequiresCharacterSelection(false); + retainedPreV7Event.setStateScope("SHARED"); + retainedPreV7Event.setCharacterCreationPolicy("ALLOW_NEW"); + retainedPreV7Event.setActorPrincipal("legacy-operator"); + retainedPreV7Event.setReason("retained pre-V7 event"); + retainedPreV7Event.setControlPlaneRequestId("legacy-request"); + retainedPreV7Event.setOccurredAt(Instant.parse("2026-09-29T00:00:00Z")); + // Pre-V7 history has no evidence for these fields; it must not be upgraded by inference. + + when(pointerRepository.findAllByOrderByWorldSlugAscRealmSlugAsc()) + .thenReturn(List.of(currentPointer)); + when(eventRepository.findLatestByPointerKeys( + List.of(new PointerAuditKey(1L, "demo", "production")))) + .thenReturn(List.of(retainedPreV7Event)); + + DatabaseGameplayAdmissionPointerAuthorityService authorityService = + new DatabaseGameplayAdmissionPointerAuthorityService(pointerRepository, eventRepository); + GameSessionAdmissionPointerControlPlaneService controlPlaneService = + new GameSessionAdmissionPointerControlPlaneService(authorityService); + + assertThrows( + AdmissionPointerAuditUnavailableException.class, + () -> controlPlaneService.listAdmissionPointers(List.of())); + } + + private static GameplayAdmissionPointerSnapshot pointer(long tenantId, String worldSlug) { + UUID realmId = UUID.nameUUIDFromBytes(("realm-" + tenantId).getBytes(StandardCharsets.UTF_8)); + UUID namespaceId = + UUID.nameUUIDFromBytes(("namespace-" + tenantId).getBytes(StandardCharsets.UTF_8)); + return new GameplayAdmissionPointerSnapshot( + worldSlug, + "Tenant World", + "production", + "Live Realm", + tenantId, + tenantId + 10L, + 3L, + true, + true, + false, + "SHARED", + "ALLOW_NEW", + 6L, + realmId, + namespaceId); + } + + private static GameplayAdmissionPointerAuditEntry audit( + GameplayAdmissionPointerSnapshot pointer) { + return audit(pointer, pointer.pointerVersion()); + } + + private static GameplayAdmissionPointerAuditEntry audit( + GameplayAdmissionPointerSnapshot pointer, long pointerVersion) { + return new GameplayAdmissionPointerAuditEntry( + pointer.worldSlug(), + pointer.realmSlug(), + pointer.worldDisplayName(), + pointer.realmDisplayName(), + pointer.tenantId(), + pointer.gameInstanceId(), + pointerVersion, + pointer.catalogRevision(), + pointer.realmId(), + pointer.playableStateNamespaceId(), + pointer.visible(), + pointer.publicProductionRealm(), + pointer.requiresCharacterSelection(), + pointer.stateScope(), + pointer.characterCreationPolicy(), + "tester", + "test audit", + "request-" + pointer.tenantId(), + null, + Instant.parse("2026-09-29T00:00:00Z")); + } +} diff --git a/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/service/impl/GameSessionControlPlaneGrpcServiceTest.java b/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/service/impl/GameSessionControlPlaneGrpcServiceTest.java index e9be425440..6710e33f35 100644 --- a/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/service/impl/GameSessionControlPlaneGrpcServiceTest.java +++ b/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/service/impl/GameSessionControlPlaneGrpcServiceTest.java @@ -47,6 +47,7 @@ import net.firedevops.firemud.gamesession.service.AdmissionPointerVersionMismatchException; import net.firedevops.firemud.gamesession.service.GameplayAdmissionPointerAuditEntry; import net.firedevops.firemud.gamesession.service.GameplayAdmissionPointerAuthorityService; +import net.firedevops.firemud.gamesession.service.GameplayAdmissionPointerAuthorityService.PointerAuditKey; import net.firedevops.firemud.gamesession.service.GameplayAdmissionPointerSnapshot; import net.firedevops.firemud.gamesession.service.InstanceCutoverCompatibilityService; import net.firedevops.firemud.gamesession.service.RemoteFollowupRuntimeService; @@ -597,9 +598,32 @@ public void onNext(GetGameInstanceRuntimeStateResponse value) { assertEquals(1, responseRef.get().getRuntimeState().getCurrentAdmissionPointersCount()); assertEquals( "demo", responseRef.get().getRuntimeState().getCurrentAdmissionPointers(0).getWorldSlug()); + assertEquals( + 12L, + responseRef.get().getRuntimeState().getCurrentAdmissionPointers(0).getCatalogRevision()); + assertEquals( + "11111111-1111-1111-1111-111111111111", + responseRef.get().getRuntimeState().getCurrentAdmissionPointers(0).getRealmId()); + assertEquals( + "22222222-2222-2222-2222-222222222222", + responseRef + .get() + .getRuntimeState() + .getCurrentAdmissionPointers(0) + .getPlayableStateNamespaceId()); assertEquals("region-7", responseRef.get().getRuntimeState().getRegionId()); assertEquals(22L, responseRef.get().getRuntimeState().getRegionEpoch()); assertEquals(17L, responseRef.get().getRuntimeState().getPublication().getVersionId()); + SessionContext.setContext("42", List.of("moderator"), Map.of()); + assertEquals( + "", invokeAdmissionReadProof(service, AdmissionReadProofOperation.RUNTIME_STATE, "1")); + for (String role : List.of("tenantAdmin", "moderator")) { + SessionContext.setContext("42", List.of(), Map.of("1", List.of(role))); + assertEquals( + "", + invokeAdmissionReadProof(service, AdmissionReadProofOperation.RUNTIME_STATE, "1"), + role); + } } @Test @@ -851,7 +875,7 @@ public void onNext(GetGameInstanceRuntimeStateResponse value) { } @Test - void getGameInstanceRuntimeStateClearsSingularRoutingBundleWhenOnlyPointerLacksRuntimeIdentity() { + void getGameInstanceRuntimeStateFailsClosedWhenPointerLacksDurableIdentity() { GameInstanceRepository repository = Mockito.mock(GameInstanceRepository.class); GameplayAdmissionPointerAuthorityService authorityService = Mockito.mock(GameplayAdmissionPointerAuthorityService.class); @@ -915,18 +939,104 @@ public void onNext(GetGameInstanceRuntimeStateResponse value) { }); assertNotNull(responseRef.get()); - assertEquals( - PlayableStateScope.PLAYABLE_STATE_SCOPE_UNSPECIFIED, - responseRef.get().getRuntimeState().getPlayableStateScope()); - assertEquals("", responseRef.get().getRuntimeState().getWorldSlug()); - assertEquals("", responseRef.get().getRuntimeState().getRealmSlug()); - assertEquals(0L, responseRef.get().getRuntimeState().getPointerVersion()); - assertEquals(1, responseRef.get().getRuntimeState().getCurrentAdmissionPointersCount()); - assertEquals( - "demo", responseRef.get().getRuntimeState().getCurrentAdmissionPointers(0).getWorldSlug()); - assertEquals( - "production", - responseRef.get().getRuntimeState().getCurrentAdmissionPointers(0).getRealmSlug()); + assertEquals("ADMISSION_POINTER_AUTHORITY_UNAVAILABLE", responseRef.get().getError().getCode()); + assertFalse(responseRef.get().hasRuntimeState()); + } + + @Test + void getGameInstanceRuntimeStateReturnsAuthorityUnavailableForPersistenceAvailabilityFailures() { + List unavailableFailures = + List.of( + new org.jooq.exception.DataAccessException( + "runtime database unavailable", + new java.sql.SQLException("connection lost", "08006")), + new org.springframework.dao.QueryTimeoutException("runtime query timed out")); + + for (RuntimeException failure : unavailableFailures) { + RuntimeRegionStatusRepository runtimeRepository = + Mockito.mock(RuntimeRegionStatusRepository.class); + Mockito.when(runtimeRepository.findByTenantIdAndRegionId(1L, "region-7")).thenThrow(failure); + SessionContext.setContext("1", List.of("platformAdmin"), Map.of()); + GameSessionControlPlaneGrpcService service = + controlPlaneService( + Mockito.mock(GameInstanceRepository.class), + Mockito.mock(GameplayCommandRepository.class), + runtimeRepository, + Mockito.mock(GameplayAdmissionPointerAuthorityService.class), + Mockito.mock(InstanceCutoverCompatibilityService.class), + Mockito.mock(VersionUpgradePreparationService.class), + Mockito.mock(TickService.class), + new SimpleMeterRegistry()); + + AtomicReference responseRef = new AtomicReference<>(); + service.getGameInstanceRuntimeState( + GetGameInstanceRuntimeStateRequest.newBuilder() + .setTenantId("1") + .setGameInstanceId("7") + .setRegionId("region-7") + .build(), + new NoopObserver<>() { + @Override + public void onNext(GetGameInstanceRuntimeStateResponse value) { + responseRef.set(value); + } + }); + + assertNotNull(responseRef.get()); + assertEquals("AUTHORITY_UNAVAILABLE", responseRef.get().getError().getCode()); + assertEquals( + "Runtime state authority unavailable", responseRef.get().getError().getMessage()); + assertFalse(responseRef.get().hasRuntimeState()); + Mockito.verify(runtimeRepository).findByTenantIdAndRegionId(1L, "region-7"); + } + } + + @Test + void getGameInstanceRuntimeStateKeepsUnexpectedPersistenceFailuresInternal() { + List unexpectedFailures = + List.of( + new IllegalStateException("runtime state mapper failed"), + new org.jooq.exception.DataAccessException( + "runtime integrity failure", + new java.sql.SQLException("unique violation", "23505")), + new org.jooq.exception.DataAccessException( + "runtime query failure", new java.sql.SQLException("malformed query", "42601"))); + + for (RuntimeException failure : unexpectedFailures) { + RuntimeRegionStatusRepository runtimeRepository = + Mockito.mock(RuntimeRegionStatusRepository.class); + Mockito.when(runtimeRepository.findByTenantIdAndRegionId(1L, "region-7")).thenThrow(failure); + SessionContext.setContext("1", List.of("platformAdmin"), Map.of()); + GameSessionControlPlaneGrpcService service = + controlPlaneService( + Mockito.mock(GameInstanceRepository.class), + Mockito.mock(GameplayCommandRepository.class), + runtimeRepository, + Mockito.mock(GameplayAdmissionPointerAuthorityService.class), + Mockito.mock(InstanceCutoverCompatibilityService.class), + Mockito.mock(VersionUpgradePreparationService.class), + Mockito.mock(TickService.class), + new SimpleMeterRegistry()); + + AtomicReference responseRef = new AtomicReference<>(); + service.getGameInstanceRuntimeState( + GetGameInstanceRuntimeStateRequest.newBuilder() + .setTenantId("1") + .setGameInstanceId("7") + .setRegionId("region-7") + .build(), + new NoopObserver<>() { + @Override + public void onNext(GetGameInstanceRuntimeStateResponse value) { + responseRef.set(value); + } + }); + + assertNotNull(responseRef.get()); + assertEquals("INTERNAL", responseRef.get().getError().getCode()); + assertFalse(responseRef.get().hasRuntimeState()); + Mockito.verify(runtimeRepository).findByTenantIdAndRegionId(1L, "region-7"); + } } @Test @@ -1173,7 +1283,7 @@ public void onNext(GetGameSessionPinConvergenceResponse value) { } @Test - void setAdmissionPointerRejectsInitialCreationUntilCatalogIdentityIsSupported() { + void setAdmissionPointerRejectsInitialCreateUntilOwnerContractsAreSupported() { GameInstanceRepository gameInstanceRepository = Mockito.mock(GameInstanceRepository.class); GameplayAdmissionPointerAuthorityService authorityService = Mockito.mock(GameplayAdmissionPointerAuthorityService.class); @@ -1257,8 +1367,135 @@ void setAdmissionPointerCreationRemainsDisabledWhenPointerVersionIsOmitted() { .setStateScope("SHARED") .setCharacterCreationPolicy("ALLOW_NEW") .setActorPrincipal("tester") - .setReason("cutover") + .setReason("create without explicit zero version") + .setControlPlaneRequestId("req-1") + .build(), + new NoopObserver<>() { + @Override + public void onNext(SetAdmissionPointerResponse value) { + responseRef.set(value); + } + }); + + assertEquals("FAILED_PRECONDITION", responseRef.get().getError().getCode()); + assertEquals( + "SetAdmissionPointer is disabled until catalog revision and stable realm/namespace " + + "identity preconditions are supported", + responseRef.get().getError().getMessage()); + Mockito.verifyNoInteractions(authorityService); + Mockito.verifyNoInteractions(gameInstanceRepository); + } + + @Test + void setAdmissionPointerRejectsExistingTargetMetadataEditUntilOwnerContractsAreSupported() { + GameInstanceRepository gameInstanceRepository = Mockito.mock(GameInstanceRepository.class); + GameInstance targetInstance = runningGameInstance(); + targetInstance.setId(7L); + targetInstance.setTenantId(1L); + targetInstance.setVersionId(9L); + targetInstance.setLaunchDescriptorId("ld-9"); + Mockito.when(gameInstanceRepository.findById(7L)).thenReturn(Optional.of(targetInstance)); + GameplayAdmissionPointerAuthorityService authorityService = + Mockito.mock(GameplayAdmissionPointerAuthorityService.class); + Mockito.when(authorityService.findPointer(1L, "demo", "production")) + .thenReturn( + Optional.of( + new GameplayAdmissionPointerSnapshot( + "demo", + "Demo World", + "production", + "Live Realm", + 1L, + 5L, + 2L, + true, + true, + false, + "SHARED", + "ALLOW_NEW"))); + SessionContext.setContext("1", List.of("platformAdmin"), Map.of()); + GameSessionControlPlaneGrpcService service = + controlPlaneService( + gameInstanceRepository, + Mockito.mock(GameplayCommandRepository.class), + Mockito.mock(RuntimeRegionStatusRepository.class), + authorityService, + Mockito.mock(InstanceCutoverCompatibilityService.class), + Mockito.mock(VersionUpgradePreparationService.class), + Mockito.mock(TickService.class), + new SimpleMeterRegistry()); + + AtomicReference responseRef = new AtomicReference<>(); + service.setAdmissionPointer( + SetAdmissionPointerRequest.newBuilder() + .setWorldSlug("demo") + .setWorldDisplayName("Renamed Demo World") + .setRealmSlug("production") + .setRealmDisplayName("Live Realm") + .setTenantId("1") + .setGameInstanceId("5") + .setVisible(true) + .setRequiresCharacterSelection(false) + .setStateScope("SHARED") + .setCharacterCreationPolicy("ALLOW_NEW") + .setActorPrincipal("tester") + .setReason("metadata edit") .setControlPlaneRequestId("req-1") + .setExpectedPointerVersion(2L) + .build(), + new NoopObserver<>() { + @Override + public void onNext(SetAdmissionPointerResponse value) { + responseRef.set(value); + } + }); + + assertEquals("FAILED_PRECONDITION", responseRef.get().getError().getCode()); + assertEquals( + "SetAdmissionPointer is disabled until catalog revision and stable realm/namespace " + + "identity preconditions are supported", + responseRef.get().getError().getMessage()); + Mockito.verify(authorityService, Mockito.never()).upsertPointer(Mockito.any()); + Mockito.verify(authorityService, Mockito.never()).listPointerAudit(1L, "demo", "production"); + Mockito.verifyNoInteractions(gameInstanceRepository); + } + + @Test + void setAdmissionPointerRejectsExistingTargetMoveUntilOwnerContractsAreSupported() { + GameInstanceRepository gameInstanceRepository = Mockito.mock(GameInstanceRepository.class); + GameplayAdmissionPointerAuthorityService authorityService = + Mockito.mock(GameplayAdmissionPointerAuthorityService.class); + SessionContext.setContext("1", List.of("platformAdmin"), Map.of()); + GameSessionControlPlaneGrpcService service = + controlPlaneService( + gameInstanceRepository, + Mockito.mock(GameplayCommandRepository.class), + Mockito.mock(RuntimeRegionStatusRepository.class), + authorityService, + Mockito.mock(InstanceCutoverCompatibilityService.class), + Mockito.mock(VersionUpgradePreparationService.class), + Mockito.mock(TickService.class), + new SimpleMeterRegistry()); + + AtomicReference responseRef = new AtomicReference<>(); + service.setAdmissionPointer( + SetAdmissionPointerRequest.newBuilder() + .setWorldSlug("demo") + .setWorldDisplayName("Demo World") + .setRealmSlug("production") + .setRealmDisplayName("Live Realm") + .setTenantId("1") + .setGameInstanceId("7") + .setVisible(true) + .setRequiresCharacterSelection(false) + .setStateScope("SHARED") + .setCharacterCreationPolicy("ALLOW_NEW") + .setActorPrincipal("tester") + .setReason("target move") + .setControlPlaneRequestId("req-2") + .setExpectedPointerVersion(2L) + .setExpectedCatalogRevision(1L) + .setPreparedVersionUpgradeId("pvu-1") .build(), new NoopObserver<>() { @Override @@ -1287,6 +1524,26 @@ void setAdmissionPointerRejectsUpdateRequestWhileIdentityGateIsClosed() { }); VersionUpgradePreparationService versionUpgradePreparationService = Mockito.mock(VersionUpgradePreparationService.class); + Mockito.when(versionUpgradePreparationService.getPreparedVersionUpgrade(1L, "pvu-1")) + .thenReturn( + new net.firedevops.firemud.gamesession.dto.PreparedVersionUpgradeDto( + "pvu-1", + "prep-req-1", + 1L, + 5L, + 7L, + 9L, + "ld-9", + "remap-1", + "COMPATIBLE", + List.of(), + List.of("WORLD", "ENTITY"), + Instant.parse("2026-04-16T00:00:00Z"), + List.of(), + null, + null, + null, + null)); SessionContext.setContext("1", List.of("platformAdmin"), Map.of()); GameSessionControlPlaneGrpcService service = controlPlaneService( @@ -1316,6 +1573,7 @@ void setAdmissionPointerRejectsUpdateRequestWhileIdentityGateIsClosed() { .setReason("cutover") .setControlPlaneRequestId("req-2") .setExpectedPointerVersion(2L) + .setExpectedCatalogRevision(1L) .setPreparedVersionUpgradeId("pvu-1") .build(), new NoopObserver<>() { @@ -1370,6 +1628,7 @@ void setAdmissionPointerRejectsZeroGameInstanceId() { .setReason("cutover") .setControlPlaneRequestId("req-1") .setExpectedPointerVersion(2L) + .setExpectedCatalogRevision(1L) .build(), new NoopObserver<>() { @Override @@ -1387,7 +1646,7 @@ public void onNext(SetAdmissionPointerResponse value) { } @Test - void executePreparedVersionCutoverFailsClosedUntilCatalogRevisionIsSupported() { + void executePreparedVersionCutoverFailsClosedBeforeAuthorityMutation() { GameInstanceRepository gameInstanceRepository = Mockito.mock(GameInstanceRepository.class); GameplayAdmissionPointerAuthorityService authorityService = Mockito.mock(GameplayAdmissionPointerAuthorityService.class); @@ -1417,6 +1676,7 @@ void executePreparedVersionCutoverFailsClosedUntilCatalogRevisionIsSupported() { .setReason("cutover") .setControlPlaneRequestId("req-1") .setExpectedPointerVersion(2L) + .setExpectedCatalogRevision(1L) .build(), new NoopObserver<>() { @Override @@ -1427,13 +1687,123 @@ public void onNext(ExecutePreparedVersionCutoverResponse value) { assertEquals("FAILED_PRECONDITION", responseRef.get().getError().getCode()); assertEquals( - "prepared cutover is temporarily disabled until catalog revision preconditions are supported", + "prepared cutover is temporarily disabled until catalog revision preconditions, " + + "World hold binding, source drain, and durable execution contracts are supported", responseRef.get().getError().getMessage()); Mockito.verifyNoInteractions(authorityService); Mockito.verifyNoInteractions(versionUpgradePreparationService); Mockito.verifyNoInteractions(gameInstanceRepository); } + @Test + void executePreparedVersionCutoverDoesNotMarkPreparedExecutionWhenDisabled() { + GameplayAdmissionPointerAuthorityService authorityService = + Mockito.mock(GameplayAdmissionPointerAuthorityService.class); + Mockito.when(authorityService.findPointer(1L, "demo", "production")) + .thenReturn( + Optional.of( + new GameplayAdmissionPointerSnapshot( + "demo", + "Demo World", + "production", + "Live Realm", + 1L, + 7L, + 3L, + true, + true, + false, + "SHARED", + "ALLOW_NEW", + 1L))); + Mockito.when(authorityService.listPointerAudit(1L, "demo", "production")) + .thenReturn( + List.of( + new GameplayAdmissionPointerAuditEntry( + "demo", + "production", + "Demo World", + "Live Realm", + 1L, + 7L, + 3L, + 1L, + UUID.fromString("11111111-1111-1111-1111-111111111111"), + UUID.fromString("22222222-2222-2222-2222-222222222222"), + true, + true, + false, + "SHARED", + "ALLOW_NEW", + "tester", + "cutover", + "req-1", + "pvu-1", + Instant.parse("2026-04-16T00:00:00Z")))); + VersionUpgradePreparationService versionUpgradePreparationService = + Mockito.mock(VersionUpgradePreparationService.class); + Mockito.when(versionUpgradePreparationService.getPreparedVersionUpgrade(1L, "pvu-1")) + .thenReturn( + new net.firedevops.firemud.gamesession.dto.PreparedVersionUpgradeDto( + "pvu-1", + "prep-req-1", + 1L, + 5L, + 7L, + 9L, + "ld-9", + "remap-1", + "COMPATIBLE", + List.of(), + List.of("WORLD", "ENTITY"), + Instant.parse("2026-04-16T00:00:00Z"), + List.of(), + 7L, + 3L, + Instant.parse("2026-04-16T00:00:01Z"), + "req-1")); + SessionContext.setContext("1", List.of("platformAdmin"), Map.of()); + GameSessionControlPlaneGrpcService service = + controlPlaneService( + Mockito.mock(GameInstanceRepository.class), + Mockito.mock(GameplayCommandRepository.class), + Mockito.mock(RuntimeRegionStatusRepository.class), + authorityService, + Mockito.mock(InstanceCutoverCompatibilityService.class), + versionUpgradePreparationService, + Mockito.mock(TickService.class), + new SimpleMeterRegistry()); + + AtomicReference responseRef = new AtomicReference<>(); + service.executePreparedVersionCutover( + ExecutePreparedVersionCutoverRequest.newBuilder() + .setWorldSlug("demo") + .setRealmSlug("production") + .setTenantId("1") + .setTargetGameInstanceId("7") + .setPreparedVersionUpgradeId("pvu-1") + .setActorPrincipal("tester") + .setReason("cutover") + .setControlPlaneRequestId("req-1") + .setExpectedPointerVersion(2L) + .setExpectedCatalogRevision(1L) + .build(), + new NoopObserver<>() { + @Override + public void onNext(ExecutePreparedVersionCutoverResponse value) { + responseRef.set(value); + } + }); + + assertEquals("FAILED_PRECONDITION", responseRef.get().getError().getCode()); + assertEquals( + "prepared cutover is temporarily disabled until catalog revision preconditions, " + + "World hold binding, source drain, and durable execution contracts are supported", + responseRef.get().getError().getMessage()); + Mockito.verifyNoInteractions(authorityService); + Mockito.verifyNoInteractions(versionUpgradePreparationService); + } + @Test void executePreparedVersionCutoverMapsTruePointerVersionMismatchSeparately() { GameSessionAdmissionPointerControlPlaneService admissionPointerControlPlaneService = @@ -1455,45 +1825,378 @@ void executePreparedVersionCutoverMapsTruePointerVersionMismatchSeparately() { null, new SimpleMeterRegistry()); - AtomicReference responseRef = new AtomicReference<>(); - service.executePreparedVersionCutover( - ExecutePreparedVersionCutoverRequest.newBuilder() - .setWorldSlug("demo") - .setRealmSlug("production") - .setTenantId("1") - .setTargetGameInstanceId("7") - .setPreparedVersionUpgradeId("pvu-1") - .setActorPrincipal("tester") - .setReason("cutover") - .setControlPlaneRequestId("req-1") - .setExpectedPointerVersion(2L) - .build(), + AtomicReference responseRef = new AtomicReference<>(); + service.executePreparedVersionCutover( + ExecutePreparedVersionCutoverRequest.newBuilder() + .setWorldSlug("demo") + .setRealmSlug("production") + .setTenantId("1") + .setTargetGameInstanceId("7") + .setPreparedVersionUpgradeId("pvu-1") + .setActorPrincipal("tester") + .setReason("cutover") + .setControlPlaneRequestId("req-1") + .setExpectedPointerVersion(2L) + .setExpectedCatalogRevision(1L) + .build(), + new NoopObserver<>() { + @Override + public void onNext(ExecutePreparedVersionCutoverResponse value) { + responseRef.set(value); + } + }); + + assertEquals("POINTER_VERSION_MISMATCH", responseRef.get().getError().getCode()); + assertEquals("pointer version changed", responseRef.get().getError().getMessage()); + Mockito.verify(admissionPointerControlPlaneService) + .executePreparedVersionCutover( + Mockito.eq(1L), + Mockito.eq(7L), + Mockito.any(ExecutePreparedVersionCutoverRequest.class)); + Mockito.verifyNoMoreInteractions(admissionPointerControlPlaneService); + } + + @Test + void listAdmissionPointersRequiresAdminCaller() { + SessionContext.setContext("1", List.of("player"), Map.of()); + GameSessionControlPlaneGrpcService service = + controlPlaneService( + Mockito.mock(GameInstanceRepository.class), + Mockito.mock(GameplayCommandRepository.class), + Mockito.mock(RuntimeRegionStatusRepository.class), + Mockito.mock(GameplayAdmissionPointerAuthorityService.class), + Mockito.mock(InstanceCutoverCompatibilityService.class), + Mockito.mock(VersionUpgradePreparationService.class), + Mockito.mock(TickService.class), + new SimpleMeterRegistry()); + + AtomicReference responseRef = new AtomicReference<>(); + service.listAdmissionPointers( + ListAdmissionPointersRequest.getDefaultInstance(), + new NoopObserver<>() { + @Override + public void onNext(ListAdmissionPointersResponse value) { + responseRef.set(value); + } + }); + + assertEquals("PERMISSION_DENIED", responseRef.get().getError().getCode()); + } + + @Test + void listAdmissionPointersUsesCurrentSnapshotForIdentityAndLatestAuditForMetadata() { + GameplayAdmissionPointerAuthorityService authorityService = + Mockito.mock(GameplayAdmissionPointerAuthorityService.class); + GameplayAdmissionPointerSnapshot currentPointer = + new GameplayAdmissionPointerSnapshot( + "demo", + "Demo World", + "production", + "Live Realm", + 1L, + 7L, + 3L, + true, + true, + false, + "SHARED", + "ALLOW_NEW", + 8L, + UUID.fromString("3ce19e6a-a63f-46f4-8e25-b105694c79e9"), + UUID.fromString("f673a1e6-648d-4ac3-8f3d-4b7cc4380f2a")); + Mockito.when(authorityService.listPointers()).thenReturn(List.of(currentPointer)); + stubLatestPointerAudit( + authorityService, currentPointer, scopedAdmissionPointerAudit(currentPointer)); + SessionContext.setContext("1", List.of("platformAdmin"), Map.of()); + GameSessionControlPlaneGrpcService service = + controlPlaneService( + Mockito.mock(GameInstanceRepository.class), + Mockito.mock(GameplayCommandRepository.class), + Mockito.mock(RuntimeRegionStatusRepository.class), + authorityService, + Mockito.mock(InstanceCutoverCompatibilityService.class), + Mockito.mock(VersionUpgradePreparationService.class), + Mockito.mock(TickService.class), + new SimpleMeterRegistry()); + + AtomicReference responseRef = new AtomicReference<>(); + service.listAdmissionPointers( + ListAdmissionPointersRequest.getDefaultInstance(), + new NoopObserver<>() { + @Override + public void onNext(ListAdmissionPointersResponse value) { + responseRef.set(value); + } + }); + + assertNotNull(responseRef.get()); + assertEquals("", responseRef.get().getError().getCode()); + assertEquals(1, responseRef.get().getPointersCount()); + assertEquals("Demo World", responseRef.get().getPointers(0).getWorldDisplayName()); + assertEquals("Live Realm", responseRef.get().getPointers(0).getRealmDisplayName()); + assertEquals("7", responseRef.get().getPointers(0).getGameInstanceId()); + assertEquals(3L, responseRef.get().getPointers(0).getPointerVersion()); + assertEquals("SHARED", responseRef.get().getPointers(0).getStateScope()); + assertEquals("ALLOW_NEW", responseRef.get().getPointers(0).getCharacterCreationPolicy()); + assertEquals(8L, responseRef.get().getPointers(0).getCatalogRevision()); + assertEquals( + "3ce19e6a-a63f-46f4-8e25-b105694c79e9", responseRef.get().getPointers(0).getRealmId()); + assertEquals( + "f673a1e6-648d-4ac3-8f3d-4b7cc4380f2a", + responseRef.get().getPointers(0).getPlayableStateNamespaceId()); + assertEquals("tester", responseRef.get().getPointers(0).getActorPrincipal()); + assertEquals("test audit", responseRef.get().getPointers(0).getReason()); + assertEquals("request-1", responseRef.get().getPointers(0).getControlPlaneRequestId()); + assertEquals("", responseRef.get().getPointers(0).getPreparedVersionUpgradeId()); + Mockito.verify(authorityService).listPointers(); + Mockito.verify(authorityService, Mockito.never()).listPointersForTenants(Mockito.anyList()); + } + + @Test + void listAdmissionPointersAllowsScopedCallerOnlyForRequestedTenantBeforeAuditValidation() { + SessionContext.setContext("7", List.of(), Map.of("2", List.of("tenantAdmin"))); + GameplayAdmissionPointerAuthorityService authorityService = + Mockito.mock(GameplayAdmissionPointerAuthorityService.class); + GameplayAdmissionPointerSnapshot requestedPointer = scopedAdmissionPointer(2L, "tenant-b"); + Mockito.when(authorityService.listPointersForTenants(List.of(2L))) + .thenReturn(List.of(requestedPointer)); + stubLatestPointerAudit( + authorityService, requestedPointer, scopedAdmissionPointerAudit(requestedPointer)); + GameSessionControlPlaneGrpcService service = + admissionPointerControlPlaneService(authorityService); + + AtomicReference responseRef = new AtomicReference<>(); + service.listAdmissionPointers( + ListAdmissionPointersRequest.newBuilder().addTenantIds("2").build(), + new NoopObserver<>() { + @Override + public void onNext(ListAdmissionPointersResponse value) { + responseRef.set(value); + } + }); + + assertEquals("", responseRef.get().getError().getCode()); + assertEquals(1, responseRef.get().getPointersCount()); + assertEquals("2", responseRef.get().getPointers(0).getTenantId()); + Mockito.verify(authorityService).listPointersForTenants(List.of(2L)); + Mockito.verify(authorityService, Mockito.never()).listPointers(); + Mockito.verify(authorityService).findLatestPointerAudits(List.of(auditKey(requestedPointer))); + Mockito.verify(authorityService, Mockito.never()) + .findLatestPointerAudit(Mockito.anyLong(), Mockito.anyString(), Mockito.anyString()); + } + + @Test + void listAdmissionPointersDeduplicatesTenantIdsBeforeDispatch() { + SessionContext.setContext("7", List.of(), Map.of("2", List.of("tenantAdmin"))); + GameplayAdmissionPointerAuthorityService authorityService = + Mockito.mock(GameplayAdmissionPointerAuthorityService.class); + GameplayAdmissionPointerSnapshot requestedPointer = scopedAdmissionPointer(2L, "tenant-b"); + Mockito.when(authorityService.listPointersForTenants(List.of(2L))) + .thenReturn(List.of(requestedPointer)); + stubLatestPointerAudit( + authorityService, requestedPointer, scopedAdmissionPointerAudit(requestedPointer)); + GameSessionControlPlaneGrpcService service = + admissionPointerControlPlaneService(authorityService); + AtomicReference responseRef = new AtomicReference<>(); + + service.listAdmissionPointers( + ListAdmissionPointersRequest.newBuilder().addTenantIds("2").addTenantIds("2").build(), + new NoopObserver<>() { + @Override + public void onNext(ListAdmissionPointersResponse value) { + responseRef.set(value); + } + }); + + assertEquals("", responseRef.get().getError().getCode()); + assertEquals(1, responseRef.get().getPointersCount()); + Mockito.verify(authorityService).listPointersForTenants(List.of(2L)); + Mockito.verify(authorityService).findLatestPointerAudits(List.of(auditKey(requestedPointer))); + } + + @Test + void listAdmissionPointersRejectsScopedCallerRequestingAnotherTenant() { + SessionContext.setContext("7", List.of(), Map.of("2", List.of("moderator"))); + GameplayAdmissionPointerAuthorityService authorityService = + Mockito.mock(GameplayAdmissionPointerAuthorityService.class); + GameSessionControlPlaneGrpcService service = + admissionPointerControlPlaneService(authorityService); + AtomicReference responseRef = new AtomicReference<>(); + + service.listAdmissionPointers( + ListAdmissionPointersRequest.newBuilder().addTenantIds("1").build(), + new NoopObserver<>() { + @Override + public void onNext(ListAdmissionPointersResponse value) { + responseRef.set(value); + } + }); + + assertEquals("PERMISSION_DENIED", responseRef.get().getError().getCode()); + Mockito.verifyNoInteractions(authorityService); + } + + @Test + void listAdmissionPointersRejectsUnauthorizedTenantEvenWhenDuplicated() { + SessionContext.setContext("7", List.of(), Map.of("2", List.of("tenantAdmin"))); + GameplayAdmissionPointerAuthorityService authorityService = + Mockito.mock(GameplayAdmissionPointerAuthorityService.class); + GameSessionControlPlaneGrpcService service = + admissionPointerControlPlaneService(authorityService); + AtomicReference responseRef = new AtomicReference<>(); + + service.listAdmissionPointers( + ListAdmissionPointersRequest.newBuilder().addTenantIds("1").addTenantIds("1").build(), + new NoopObserver<>() { + @Override + public void onNext(ListAdmissionPointersResponse value) { + responseRef.set(value); + } + }); + + assertEquals("PERMISSION_DENIED", responseRef.get().getError().getCode()); + Mockito.verifyNoInteractions(authorityService); + } + + @Test + void listAdmissionPointersRejectsScopedCallerUsingEmptyAllTenantRequest() { + SessionContext.setContext("7", List.of(), Map.of("2", List.of("tenantAdmin"))); + GameplayAdmissionPointerAuthorityService authorityService = + Mockito.mock(GameplayAdmissionPointerAuthorityService.class); + GameSessionControlPlaneGrpcService service = + admissionPointerControlPlaneService(authorityService); + AtomicReference responseRef = new AtomicReference<>(); + + service.listAdmissionPointers( + ListAdmissionPointersRequest.getDefaultInstance(), + new NoopObserver<>() { + @Override + public void onNext(ListAdmissionPointersResponse value) { + responseRef.set(value); + } + }); + + assertEquals("PERMISSION_DENIED", responseRef.get().getError().getCode()); + Mockito.verifyNoInteractions(authorityService); + } + + @Test + void listAdmissionPointersRejectsMissingCallerContext() { + GameplayAdmissionPointerAuthorityService authorityService = + Mockito.mock(GameplayAdmissionPointerAuthorityService.class); + GameSessionControlPlaneGrpcService service = + admissionPointerControlPlaneService(authorityService); + AtomicReference responseRef = new AtomicReference<>(); + + service.listAdmissionPointers( + ListAdmissionPointersRequest.newBuilder().addTenantIds("2").build(), + new NoopObserver<>() { + @Override + public void onNext(ListAdmissionPointersResponse value) { + responseRef.set(value); + } + }); + + assertEquals("PERMISSION_DENIED", responseRef.get().getError().getCode()); + Mockito.verifyNoInteractions(authorityService); + } + + @Test + void listAdmissionPointersRejectsNonPositiveTenantScopeBeforeAuthorityLookup() { + SessionContext.setContext("7", List.of("platformAdmin"), Map.of()); + GameplayAdmissionPointerAuthorityService authorityService = + Mockito.mock(GameplayAdmissionPointerAuthorityService.class); + GameSessionControlPlaneGrpcService service = + admissionPointerControlPlaneService(authorityService); + AtomicReference responseRef = new AtomicReference<>(); + + service.listAdmissionPointers( + ListAdmissionPointersRequest.newBuilder().addTenantIds("0").build(), + new NoopObserver<>() { + @Override + public void onNext(ListAdmissionPointersResponse value) { + responseRef.set(value); + } + }); + + assertEquals("INVALID_ARGUMENT", responseRef.get().getError().getCode()); + Mockito.verifyNoInteractions(authorityService); + } + + @Test + void listAdmissionPointersRejectsMalformedTenantScopeBeforeAuthorityLookup() { + SessionContext.setContext("7", List.of("platformAdmin"), Map.of()); + GameplayAdmissionPointerAuthorityService authorityService = + Mockito.mock(GameplayAdmissionPointerAuthorityService.class); + GameSessionControlPlaneGrpcService service = + admissionPointerControlPlaneService(authorityService); + AtomicReference responseRef = new AtomicReference<>(); + + for (String tenantId : + List.of( + "", + " ", + "not-a-number", + "-1", + "9223372036854775808", + "550e8400-e29b-41d4-a716-446655440000")) { + responseRef.set(null); + service.listAdmissionPointers( + ListAdmissionPointersRequest.newBuilder().addTenantIds(tenantId).build(), + new NoopObserver<>() { + @Override + public void onNext(ListAdmissionPointersResponse value) { + responseRef.set(value); + } + }); + + assertNotNull(responseRef.get()); + assertEquals("INVALID_ARGUMENT", responseRef.get().getError().getCode()); + } + + Mockito.verifyNoInteractions(authorityService); + } + + @Test + void listAdmissionPointersFailsClosedForMissingAuditInRequestedTenant() { + SessionContext.setContext("7", List.of(), Map.of("2", List.of("tenantAdmin"))); + GameplayAdmissionPointerAuthorityService authorityService = + Mockito.mock(GameplayAdmissionPointerAuthorityService.class); + GameplayAdmissionPointerSnapshot requestedPointer = scopedAdmissionPointer(2L, "tenant-b"); + Mockito.when(authorityService.listPointersForTenants(List.of(2L))) + .thenReturn(List.of(requestedPointer)); + stubMissingLatestPointerAudit(authorityService, requestedPointer); + GameSessionControlPlaneGrpcService service = + admissionPointerControlPlaneService(authorityService); + AtomicReference responseRef = new AtomicReference<>(); + + service.listAdmissionPointers( + ListAdmissionPointersRequest.newBuilder().addTenantIds("2").build(), new NoopObserver<>() { @Override - public void onNext(ExecutePreparedVersionCutoverResponse value) { + public void onNext(ListAdmissionPointersResponse value) { responseRef.set(value); } }); - assertEquals("POINTER_VERSION_MISMATCH", responseRef.get().getError().getCode()); - assertEquals("pointer version changed", responseRef.get().getError().getMessage()); - Mockito.verify(admissionPointerControlPlaneService) - .executePreparedVersionCutover( - Mockito.eq(1L), - Mockito.eq(7L), - Mockito.any(ExecutePreparedVersionCutoverRequest.class)); - Mockito.verifyNoMoreInteractions(admissionPointerControlPlaneService); + assertEquals("AUTHORITY_UNAVAILABLE", responseRef.get().getError().getCode()); + assertEquals(0, responseRef.get().getPointersCount()); } @Test - void listAdmissionPointersRequiresAdminCaller() { - SessionContext.setContext("1", List.of("player"), Map.of()); + void listAdmissionPointersFailsClosedWhenCurrentPointerHasNoAuditHistory() { + GameplayAdmissionPointerAuthorityService authorityService = + Mockito.mock(GameplayAdmissionPointerAuthorityService.class); + GameplayAdmissionPointerSnapshot currentPointer = scopedAdmissionPointer(1L, "demo"); + Mockito.when(authorityService.listPointers()).thenReturn(List.of(currentPointer)); + stubMissingLatestPointerAudit(authorityService, currentPointer); + SessionContext.setContext("1", List.of("platformAdmin"), Map.of()); GameSessionControlPlaneGrpcService service = controlPlaneService( Mockito.mock(GameInstanceRepository.class), Mockito.mock(GameplayCommandRepository.class), Mockito.mock(RuntimeRegionStatusRepository.class), - Mockito.mock(GameplayAdmissionPointerAuthorityService.class), + authorityService, Mockito.mock(InstanceCutoverCompatibilityService.class), Mockito.mock(VersionUpgradePreparationService.class), Mockito.mock(TickService.class), @@ -1509,13 +2212,16 @@ public void onNext(ListAdmissionPointersResponse value) { } }); - assertEquals("PERMISSION_DENIED", responseRef.get().getError().getCode()); + assertEquals("AUTHORITY_UNAVAILABLE", responseRef.get().getError().getCode()); + assertEquals(0, responseRef.get().getPointersCount()); + Mockito.verify(authorityService).findLatestPointerAudits(List.of(auditKey(currentPointer))); } @Test - void listAdmissionPointersUsesCurrentSnapshotForIdentityAndLatestAuditForMetadata() { + void listAdmissionPointersFailsClosedWhenLatestAuditHasNoCatalogRevision() { GameplayAdmissionPointerAuthorityService authorityService = Mockito.mock(GameplayAdmissionPointerAuthorityService.class); + PointerAuditKey auditKey = new PointerAuditKey(1L, "demo", "production"); Mockito.when(authorityService.listPointers()) .thenReturn( List.of( @@ -1532,31 +2238,32 @@ void listAdmissionPointersUsesCurrentSnapshotForIdentityAndLatestAuditForMetadat false, "SHARED", "ALLOW_NEW", - 8L, - java.util.UUID.fromString("3ce19e6a-a63f-46f4-8e25-b105694c79e9"), - java.util.UUID.fromString("f673a1e6-648d-4ac3-8f3d-4b7cc4380f2a")))); - Mockito.when(authorityService.listPointerAudit(1L, "demo", "production")) + 6L, + UUID.fromString("11111111-1111-1111-1111-111111111111"), + UUID.fromString("22222222-2222-2222-2222-222222222222")))); + Mockito.when(authorityService.findLatestPointerAudits(List.of(auditKey))) .thenReturn( - List.of( + Map.of( + auditKey, new GameplayAdmissionPointerAuditEntry( "demo", "production", - "Historical World Name", - "Historical Realm Name", + "Demo World", + "Live Realm", 1L, - 6L, - 2L, + 7L, + 3L, + null, + UUID.fromString("11111111-1111-1111-1111-111111111111"), + UUID.fromString("22222222-2222-2222-2222-222222222222"), true, - false, true, - "ISOLATED", - "DISALLOW", + false, + "SHARED", + "ALLOW_NEW", "tester", - "cutover", + "legacy event", "req-1", - "pvu-1", - null, - null, null, Instant.parse("2026-04-15T00:00:00Z")))); SessionContext.setContext("1", List.of("platformAdmin"), Map.of()); @@ -1581,30 +2288,15 @@ public void onNext(ListAdmissionPointersResponse value) { } }); - assertNotNull(responseRef.get()); - assertEquals(1, responseRef.get().getPointersCount()); - assertEquals("Demo World", responseRef.get().getPointers(0).getWorldDisplayName()); - assertEquals("Live Realm", responseRef.get().getPointers(0).getRealmDisplayName()); - assertEquals("7", responseRef.get().getPointers(0).getGameInstanceId()); - assertEquals(3L, responseRef.get().getPointers(0).getPointerVersion()); - assertEquals("SHARED", responseRef.get().getPointers(0).getStateScope()); - assertEquals("ALLOW_NEW", responseRef.get().getPointers(0).getCharacterCreationPolicy()); - assertEquals(8L, responseRef.get().getPointers(0).getCatalogRevision()); - assertEquals( - "3ce19e6a-a63f-46f4-8e25-b105694c79e9", responseRef.get().getPointers(0).getRealmId()); - assertEquals( - "f673a1e6-648d-4ac3-8f3d-4b7cc4380f2a", - responseRef.get().getPointers(0).getPlayableStateNamespaceId()); - assertEquals("tester", responseRef.get().getPointers(0).getActorPrincipal()); - assertEquals("cutover", responseRef.get().getPointers(0).getReason()); - assertEquals("req-1", responseRef.get().getPointers(0).getControlPlaneRequestId()); - assertEquals("pvu-1", responseRef.get().getPointers(0).getPreparedVersionUpgradeId()); + assertEquals("AUTHORITY_UNAVAILABLE", responseRef.get().getError().getCode()); + assertEquals(0, responseRef.get().getPointersCount()); } @Test - void listAdmissionPointersFailsClosedWhenCurrentPointerHasNoAuditHistory() { + void listAdmissionPointersFailsClosedWhenLatestAuditDoesNotMatchCurrentPointer() { GameplayAdmissionPointerAuthorityService authorityService = Mockito.mock(GameplayAdmissionPointerAuthorityService.class); + PointerAuditKey auditKey = new PointerAuditKey(1L, "demo", "production"); Mockito.when(authorityService.listPointers()) .thenReturn( List.of( @@ -1620,8 +2312,35 @@ void listAdmissionPointersFailsClosedWhenCurrentPointerHasNoAuditHistory() { true, false, "SHARED", - "ALLOW_NEW"))); - Mockito.when(authorityService.listPointerAudit(1L, "demo", "production")).thenReturn(List.of()); + "ALLOW_NEW", + 6L, + UUID.fromString("11111111-1111-1111-1111-111111111111"), + UUID.fromString("22222222-2222-2222-2222-222222222222")))); + Mockito.when(authorityService.findLatestPointerAudits(List.of(auditKey))) + .thenReturn( + Map.of( + auditKey, + new GameplayAdmissionPointerAuditEntry( + "demo", + "production", + "Demo World", + "Live Realm", + 1L, + 6L, + 2L, + 5L, + UUID.fromString("11111111-1111-1111-1111-111111111111"), + UUID.fromString("22222222-2222-2222-2222-222222222222"), + true, + true, + false, + "SHARED", + "ALLOW_NEW", + "tester", + "historical event", + "req-0", + null, + Instant.parse("2026-04-14T00:00:00Z")))); SessionContext.setContext("1", List.of("platformAdmin"), Map.of()); GameSessionControlPlaneGrpcService service = controlPlaneService( @@ -1649,9 +2368,10 @@ public void onNext(ListAdmissionPointersResponse value) { } @Test - void listAdmissionPointersReturnsInternalForUnrelatedIllegalStateFailure() { + void listAdmissionPointersExposesDurableIdentityFromAuditEntry() { GameplayAdmissionPointerAuthorityService authorityService = Mockito.mock(GameplayAdmissionPointerAuthorityService.class); + PointerAuditKey auditKey = new PointerAuditKey(1L, "demo", "production"); Mockito.when(authorityService.listPointers()) .thenReturn( List.of( @@ -1667,9 +2387,35 @@ void listAdmissionPointersReturnsInternalForUnrelatedIllegalStateFailure() { true, false, "SHARED", - "ALLOW_NEW"))); - Mockito.when(authorityService.listPointerAudit(1L, "demo", "production")) - .thenThrow(new IllegalStateException("audit store failed")); + "ALLOW_NEW", + 6L, + UUID.fromString("11111111-1111-1111-1111-111111111111"), + UUID.fromString("22222222-2222-2222-2222-222222222222")))); + Mockito.when(authorityService.findLatestPointerAudits(List.of(auditKey))) + .thenReturn( + Map.of( + auditKey, + new GameplayAdmissionPointerAuditEntry( + "demo", + "production", + "Demo World", + "Live Realm", + 1L, + 7L, + 3L, + 6L, + UUID.fromString("11111111-1111-1111-1111-111111111111"), + UUID.fromString("22222222-2222-2222-2222-222222222222"), + true, + true, + false, + "SHARED", + "ALLOW_NEW", + "tester", + "cutover", + "req-1", + null, + Instant.parse("2026-04-15T00:00:00Z")))); SessionContext.setContext("1", List.of("platformAdmin"), Map.of()); GameSessionControlPlaneGrpcService service = controlPlaneService( @@ -1692,8 +2438,120 @@ public void onNext(ListAdmissionPointersResponse value) { } }); - assertEquals("INTERNAL", responseRef.get().getError().getCode()); - assertEquals(0, responseRef.get().getPointersCount()); + assertEquals( + "11111111-1111-1111-1111-111111111111", responseRef.get().getPointers(0).getRealmId()); + assertEquals( + "22222222-2222-2222-2222-222222222222", + responseRef.get().getPointers(0).getPlayableStateNamespaceId()); + assertEquals(6L, responseRef.get().getPointers(0).getCatalogRevision()); + Mockito.verify(authorityService).listPointers(); + Mockito.verify(authorityService, Mockito.never()).listPointersForTenants(Mockito.anyList()); + Mockito.verify(authorityService).findLatestPointerAudits(List.of(auditKey)); + } + + @Test + void listAdmissionPointersReturnsAuthorityUnavailableForDatabaseShutdownStates() { + for (String sqlState : List.of("08006", "57P01", "57P02", "57P03")) { + GameplayAdmissionPointerAuthorityService authorityService = + Mockito.mock(GameplayAdmissionPointerAuthorityService.class); + GameplayAdmissionPointerSnapshot currentPointer = scopedAdmissionPointer(1L, "demo"); + Mockito.when(authorityService.listPointers()).thenReturn(List.of(currentPointer)); + Mockito.when(authorityService.findLatestPointerAudits(List.of(auditKey(currentPointer)))) + .thenThrow( + new org.jooq.exception.DataAccessException( + "audit database unavailable", + new java.sql.SQLException("database unavailable", sqlState))); + SessionContext.setContext("1", List.of("platformAdmin"), Map.of()); + GameSessionControlPlaneGrpcService service = + admissionPointerControlPlaneService(authorityService); + + AtomicReference responseRef = new AtomicReference<>(); + service.listAdmissionPointers( + ListAdmissionPointersRequest.getDefaultInstance(), + new NoopObserver<>() { + @Override + public void onNext(ListAdmissionPointersResponse value) { + responseRef.set(value); + } + }); + + assertNotNull(responseRef.get(), sqlState); + assertEquals("AUTHORITY_UNAVAILABLE", responseRef.get().getError().getCode(), sqlState); + assertEquals(0, responseRef.get().getPointersCount(), sqlState); + } + } + + @Test + void listAdmissionPointersKeepsUnexpectedFailuresInternal() { + List unexpectedFailures = + List.of( + new IllegalStateException("audit mapper failed"), + new org.jooq.exception.DataAccessException( + "integrity failure", new java.sql.SQLException("unique violation", "23505")), + new org.jooq.exception.DataAccessException( + "query failure", new java.sql.SQLException("malformed query", "42601"))); + + for (RuntimeException failure : unexpectedFailures) { + GameplayAdmissionPointerAuthorityService authorityService = + Mockito.mock(GameplayAdmissionPointerAuthorityService.class); + GameplayAdmissionPointerSnapshot currentPointer = scopedAdmissionPointer(1L, "demo"); + Mockito.when(authorityService.listPointers()).thenReturn(List.of(currentPointer)); + Mockito.when(authorityService.findLatestPointerAudits(List.of(auditKey(currentPointer)))) + .thenThrow(failure); + SessionContext.setContext("1", List.of("platformAdmin"), Map.of()); + GameSessionControlPlaneGrpcService service = + admissionPointerControlPlaneService(authorityService); + + AtomicReference responseRef = new AtomicReference<>(); + service.listAdmissionPointers( + ListAdmissionPointersRequest.getDefaultInstance(), + new NoopObserver<>() { + @Override + public void onNext(ListAdmissionPointersResponse value) { + responseRef.set(value); + } + }); + + assertNotNull(responseRef.get()); + assertEquals("INTERNAL", responseRef.get().getError().getCode()); + assertEquals(0, responseRef.get().getPointersCount()); + } + } + + @Test + void listAdmissionPointerAuditReturnsAuthorityUnavailableForTimeoutAndResourceFailures() { + List unavailableFailures = + List.of( + new org.springframework.dao.QueryTimeoutException("audit query timed out"), + new org.springframework.dao.TransientDataAccessResourceException( + "audit connection unavailable")); + + for (RuntimeException failure : unavailableFailures) { + GameplayAdmissionPointerAuthorityService authorityService = + Mockito.mock(GameplayAdmissionPointerAuthorityService.class); + Mockito.when(authorityService.listPointerAudit(1L, "demo", "production")).thenThrow(failure); + SessionContext.setContext("1", List.of("platformAdmin"), Map.of()); + GameSessionControlPlaneGrpcService service = + admissionPointerControlPlaneService(authorityService); + + AtomicReference responseRef = new AtomicReference<>(); + service.listAdmissionPointerAudit( + ListAdmissionPointerAuditRequest.newBuilder() + .setTenantId("1") + .setWorldSlug("demo") + .setRealmSlug("production") + .build(), + new NoopObserver<>() { + @Override + public void onNext(ListAdmissionPointerAuditResponse value) { + responseRef.set(value); + } + }); + + assertNotNull(responseRef.get()); + assertEquals("AUTHORITY_UNAVAILABLE", responseRef.get().getError().getCode()); + assertEquals(0, responseRef.get().getAuditCount()); + } } @Test @@ -1711,6 +2569,9 @@ void listAdmissionPointerAuditReturnsEntriesForAdminCaller() { 1L, 7L, 3L, + 2L, + UUID.fromString("11111111-1111-1111-1111-111111111111"), + UUID.fromString("22222222-2222-2222-2222-222222222222"), true, true, false, @@ -1720,9 +2581,6 @@ void listAdmissionPointerAuditReturnsEntriesForAdminCaller() { "cutover", "req-1", "pvu-1", - 4L, - java.util.UUID.fromString("3ce19e6a-a63f-46f4-8e25-b105694c79e9"), - java.util.UUID.fromString("f673a1e6-648d-4ac3-8f3d-4b7cc4380f2a"), Instant.parse("2026-04-15T00:00:00Z")), new GameplayAdmissionPointerAuditEntry( "demo", @@ -1732,6 +2590,9 @@ void listAdmissionPointerAuditReturnsEntriesForAdminCaller() { 1L, 6L, 2L, + null, + null, + null, true, true, false, @@ -1741,9 +2602,6 @@ void listAdmissionPointerAuditReturnsEntriesForAdminCaller() { "previous", "req-0", null, - null, - null, - null, Instant.parse("2026-04-14T00:00:00Z")))); SessionContext.setContext("1", List.of("platformAdmin"), Map.of()); GameSessionControlPlaneGrpcService service = @@ -1775,16 +2633,23 @@ public void onNext(ListAdmissionPointerAuditResponse value) { assertEquals(2, responseRef.get().getAuditCount()); assertEquals("demo", responseRef.get().getAudit(0).getWorldSlug()); assertEquals(3L, responseRef.get().getAudit(0).getPointerVersion()); - assertEquals(4L, responseRef.get().getAudit(0).getCatalogRevision()); + assertEquals(2L, responseRef.get().getAudit(0).getCatalogRevision()); assertEquals( - "3ce19e6a-a63f-46f4-8e25-b105694c79e9", responseRef.get().getAudit(0).getRealmId()); + "11111111-1111-1111-1111-111111111111", responseRef.get().getAudit(0).getRealmId()); assertEquals( - "f673a1e6-648d-4ac3-8f3d-4b7cc4380f2a", + "22222222-2222-2222-2222-222222222222", responseRef.get().getAudit(0).getPlayableStateNamespaceId()); - assertEquals(false, responseRef.get().getAudit(1).hasCatalogRevision()); - assertEquals("", responseRef.get().getAudit(1).getRealmId()); - assertEquals("", responseRef.get().getAudit(1).getPlayableStateNamespaceId()); - Mockito.verify(authorityService).listPointerAudit(1L, "demo", "production"); + assertFalse(responseRef.get().getAudit(1).hasCatalogRevision()); + assertTrue(responseRef.get().getAudit(1).getRealmId().isEmpty()); + assertTrue(responseRef.get().getAudit(1).getPlayableStateNamespaceId().isEmpty()); + SessionContext.setContext("42", List.of("moderator"), Map.of()); + assertEquals("", invokeAdmissionReadProof(service, AdmissionReadProofOperation.AUDIT, "1")); + for (String role : List.of("tenantAdmin", "moderator")) { + SessionContext.setContext("42", List.of(), Map.of("1", List.of(role))); + assertEquals( + "", invokeAdmissionReadProof(service, AdmissionReadProofOperation.AUDIT, "1"), role); + } + Mockito.verify(authorityService, Mockito.times(4)).listPointerAudit(1L, "demo", "production"); Mockito.verify(authorityService, Mockito.never()).listPointers(); } @@ -1908,6 +2773,45 @@ public void onNext(ListAdmissionPointerAuditResponse value) { Mockito.verify(authorityService, Mockito.never()).listPointers(); } + @Test + void scopedAdmissionReadProofReceiversRejectOtherTenantBasicRoleAndAbsentContextBeforeReads() { + for (AdmissionCallerContext callerContext : AdmissionCallerContext.values()) { + AdmissionReadProofFixture fixture = admissionReadProofFixture(); + switch (callerContext) { + case OTHER_TENANT -> + SessionContext.setContext("42", List.of(), Map.of("1", List.of("tenantAdmin"))); + case BASIC_ROLE -> SessionContext.setContext("42", List.of("player"), Map.of()); + case ABSENT -> SessionContext.clear(); + } + + for (AdmissionReadProofOperation operation : AdmissionReadProofOperation.values()) { + assertEquals( + "PERMISSION_DENIED", + invokeAdmissionReadProof(fixture.service(), operation, "2"), + callerContext + " " + operation); + } + + verifyNoAdmissionReadInteractions(fixture); + } + } + + @Test + void scopedAdmissionReadProofReceiversKeepTenantParseErrorsBeforeAuthorization() { + AdmissionReadProofFixture fixture = admissionReadProofFixture(); + + for (String invalidTenantId : List.of("not-a-number", "0", "-1", "9223372036854775808")) { + SessionContext.clear(); + for (AdmissionReadProofOperation operation : AdmissionReadProofOperation.values()) { + assertEquals( + "INVALID_ARGUMENT", + invokeAdmissionReadProof(fixture.service(), operation, invalidTenantId), + invalidTenantId + " " + operation); + } + } + + verifyNoAdmissionReadInteractions(fixture); + } + @Test void getGameplayCommandStatusReturnsLedgerRecordForAdminCaller() { GameplayCommand command = new GameplayCommand(); @@ -8204,6 +9108,16 @@ public void onNext(ValidateInstanceCutoverCompatibilityResponse value) { responseRef.get().getResult()); assertEquals("remap-1", responseRef.get().getRemapSetId()); assertEquals(2, responseRef.get().getParticipantResultsCount()); + SessionContext.setContext("42", List.of("moderator"), Map.of()); + assertEquals( + "", invokeAdmissionReadProof(service, AdmissionReadProofOperation.COMPATIBILITY, "1")); + for (String role : List.of("tenantAdmin", "moderator")) { + SessionContext.setContext("42", List.of(), Map.of("1", List.of(role))); + assertEquals( + "", + invokeAdmissionReadProof(service, AdmissionReadProofOperation.COMPATIBILITY, "1"), + role); + } } @Test @@ -8316,6 +9230,82 @@ public void onNext(GetPreparedVersionUpgradeResponse value) { assertEquals("pvu-req-1", responseRef.get().getPreparation().getControlPlaneRequestId()); assertEquals("55", responseRef.get().getPreparation().getExecutedTargetGameInstanceId()); assertEquals(4L, responseRef.get().getPreparation().getExecutedPointerVersion()); + SessionContext.setContext("42", List.of("moderator"), Map.of()); + assertEquals( + "", + invokeAdmissionReadProof( + service, AdmissionReadProofOperation.PREPARED_VERSION, "1", "pvu-1")); + for (String role : List.of("tenantAdmin", "moderator")) { + SessionContext.setContext("42", List.of(), Map.of("1", List.of(role))); + assertEquals( + "", + invokeAdmissionReadProof( + service, AdmissionReadProofOperation.PREPARED_VERSION, "1", "pvu-1"), + role); + } + } + + @Test + void getPreparedVersionUpgradeMapsRecognizedPersistenceAvailabilityFailures() { + List unavailableFailures = + List.of( + new org.jooq.exception.DataAccessException( + "prepared proof database unavailable", + new java.sql.SQLException("connection lost", "08006")), + new RuntimeException( + "wrapped prepared proof timeout", + new org.springframework.dao.QueryTimeoutException("query timed out"))); + + for (RuntimeException failure : unavailableFailures) { + AdmissionReadProofFixture fixture = admissionReadProofFixture(); + Mockito.when(fixture.preparationService().getPreparedVersionUpgrade(1L, "pvu-1")) + .thenThrow(failure); + SessionContext.setContext("42", List.of(), Map.of("1", List.of("tenantAdmin"))); + AtomicReference responseRef = new AtomicReference<>(); + fixture + .service() + .getPreparedVersionUpgrade( + GetPreparedVersionUpgradeRequest.newBuilder() + .setTenantId("1") + .setPreparationId("pvu-1") + .build(), + new NoopObserver<>() { + @Override + public void onNext(GetPreparedVersionUpgradeResponse value) { + responseRef.set(value); + } + }); + + assertEquals("AUTHORITY_UNAVAILABLE", responseRef.get().getError().getCode()); + assertEquals( + "Prepared version upgrade authority unavailable", + responseRef.get().getError().getMessage()); + } + } + + @Test + void getPreparedVersionUpgradeKeepsUnexpectedPersistenceFailuresInternal() { + List unexpectedFailures = + List.of( + new IllegalStateException("prepared proof mapper failed"), + new org.jooq.exception.DataAccessException( + "prepared proof integrity failure", + new java.sql.SQLException("unique violation", "23505")), + new org.jooq.exception.DataAccessException( + "prepared proof query failure", + new java.sql.SQLException("malformed query", "42601"))); + + for (RuntimeException failure : unexpectedFailures) { + AdmissionReadProofFixture fixture = admissionReadProofFixture(); + Mockito.when(fixture.preparationService().getPreparedVersionUpgrade(1L, "pvu-1")) + .thenThrow(failure); + SessionContext.setContext("42", List.of(), Map.of("1", List.of("tenantAdmin"))); + + assertEquals( + "INTERNAL", + invokeAdmissionReadProof( + fixture.service(), AdmissionReadProofOperation.PREPARED_VERSION, "1", "pvu-1")); + } } private static GameSessionControlPlaneGrpcService newService(GameInstanceRepository repository) { @@ -9553,6 +10543,84 @@ private static GameSessionControlPlaneGrpcService remoteControlPlaneService( new GameSessionProperties()); } + private static GameSessionControlPlaneGrpcService admissionPointerControlPlaneService( + GameplayAdmissionPointerAuthorityService authorityService) { + return controlPlaneService( + Mockito.mock(GameInstanceRepository.class), + Mockito.mock(GameplayCommandRepository.class), + Mockito.mock(RuntimeRegionStatusRepository.class), + authorityService, + Mockito.mock(InstanceCutoverCompatibilityService.class), + Mockito.mock(VersionUpgradePreparationService.class), + Mockito.mock(TickService.class), + new SimpleMeterRegistry()); + } + + private static GameplayAdmissionPointerSnapshot scopedAdmissionPointer( + long tenantId, String worldSlug) { + return new GameplayAdmissionPointerSnapshot( + worldSlug, + "Tenant World", + "production", + "Live Realm", + tenantId, + tenantId + 10L, + 3L, + true, + true, + false, + "SHARED", + "ALLOW_NEW", + 6L, + UUID.fromString("11111111-1111-1111-1111-111111111111"), + UUID.fromString("22222222-2222-2222-2222-222222222222")); + } + + private static PointerAuditKey auditKey(GameplayAdmissionPointerSnapshot pointer) { + return new PointerAuditKey(pointer.tenantId(), pointer.worldSlug(), pointer.realmSlug()); + } + + private static void stubLatestPointerAudit( + GameplayAdmissionPointerAuthorityService authorityService, + GameplayAdmissionPointerSnapshot pointer, + GameplayAdmissionPointerAuditEntry audit) { + PointerAuditKey key = auditKey(pointer); + Mockito.when(authorityService.findLatestPointerAudits(List.of(key))) + .thenReturn(Map.of(key, audit)); + } + + private static void stubMissingLatestPointerAudit( + GameplayAdmissionPointerAuthorityService authorityService, + GameplayAdmissionPointerSnapshot pointer) { + Mockito.when(authorityService.findLatestPointerAudits(List.of(auditKey(pointer)))) + .thenReturn(Map.of()); + } + + private static GameplayAdmissionPointerAuditEntry scopedAdmissionPointerAudit( + GameplayAdmissionPointerSnapshot pointer) { + return new GameplayAdmissionPointerAuditEntry( + pointer.worldSlug(), + pointer.realmSlug(), + pointer.worldDisplayName(), + pointer.realmDisplayName(), + pointer.tenantId(), + pointer.gameInstanceId(), + pointer.pointerVersion(), + pointer.catalogRevision(), + pointer.realmId(), + pointer.playableStateNamespaceId(), + pointer.visible(), + pointer.publicProductionRealm(), + pointer.requiresCharacterSelection(), + pointer.stateScope(), + pointer.characterCreationPolicy(), + "tester", + "test audit", + "request-" + pointer.tenantId(), + null, + Instant.parse("2026-09-29T00:00:00Z")); + } + private static GameInstance runningGameInstance() { GameInstance instance = new GameInstance(); instance.setStatus("RUNNING"); @@ -9568,6 +10636,147 @@ private static GameInstance runningPinnedGameInstance() { return instance; } + private static AdmissionReadProofFixture admissionReadProofFixture() { + GameInstanceRepository gameInstanceRepository = Mockito.mock(GameInstanceRepository.class); + RuntimeRegionStatusRepository runtimeRegionStatusRepository = + Mockito.mock(RuntimeRegionStatusRepository.class); + GameplayAdmissionPointerAuthorityService pointerAuthority = + Mockito.mock(GameplayAdmissionPointerAuthorityService.class); + InstanceCutoverCompatibilityService compatibilityService = + Mockito.mock(InstanceCutoverCompatibilityService.class); + VersionUpgradePreparationService preparationService = + Mockito.mock(VersionUpgradePreparationService.class); + GameSessionControlPlaneGrpcService service = + controlPlaneService( + gameInstanceRepository, + Mockito.mock(GameplayCommandRepository.class), + runtimeRegionStatusRepository, + pointerAuthority, + compatibilityService, + preparationService, + Mockito.mock(GameDesignClient.class), + BuiltInTextCommandAliasResolver.unsupported(), + Mockito.mock(TickService.class), + new SimpleMeterRegistry()); + return new AdmissionReadProofFixture( + service, + gameInstanceRepository, + runtimeRegionStatusRepository, + pointerAuthority, + compatibilityService, + preparationService); + } + + private static String invokeAdmissionReadProof( + GameSessionControlPlaneGrpcService service, + AdmissionReadProofOperation operation, + String tenantId) { + return invokeAdmissionReadProof(service, operation, tenantId, "pvu-2"); + } + + private static String invokeAdmissionReadProof( + GameSessionControlPlaneGrpcService service, + AdmissionReadProofOperation operation, + String tenantId, + String preparationId) { + return switch (operation) { + case AUDIT -> { + AtomicReference response = new AtomicReference<>(); + service.listAdmissionPointerAudit( + ListAdmissionPointerAuditRequest.newBuilder() + .setTenantId(tenantId) + .setWorldSlug("demo") + .setRealmSlug("production") + .build(), + capturingObserver(response)); + assertNotNull(response.get()); + yield response.get().getError().getCode(); + } + case RUNTIME_STATE -> { + AtomicReference response = new AtomicReference<>(); + service.getGameInstanceRuntimeState( + GetGameInstanceRuntimeStateRequest.newBuilder() + .setTenantId(tenantId) + .setGameInstanceId("7") + .build(), + capturingObserver(response)); + assertNotNull(response.get()); + yield response.get().getError().getCode(); + } + case COMPATIBILITY -> { + AtomicReference response = + new AtomicReference<>(); + service.validateInstanceCutoverCompatibility( + ValidateInstanceCutoverCompatibilityRequest.newBuilder() + .setTenantId(tenantId) + .setSourceGameInstanceId("7") + .setTargetVersionId("9") + .build(), + capturingObserver(response)); + assertNotNull(response.get()); + yield response.get().getError().getCode(); + } + case PREPARED_VERSION -> { + AtomicReference response = new AtomicReference<>(); + service.getPreparedVersionUpgrade( + GetPreparedVersionUpgradeRequest.newBuilder() + .setTenantId(tenantId) + .setPreparationId(preparationId) + .build(), + capturingObserver(response)); + assertNotNull(response.get()); + yield response.get().getError().getCode(); + } + }; + } + + private static void verifyNoAdmissionReadInteractions(AdmissionReadProofFixture fixture) { + Mockito.verifyNoInteractions( + fixture.gameInstanceRepository(), + fixture.runtimeRegionStatusRepository(), + fixture.pointerAuthority(), + fixture.compatibilityService(), + fixture.preparationService()); + } + + private static StreamObserver capturingObserver(AtomicReference response) { + return new StreamObserver<>() { + @Override + public void onNext(T value) { + response.set(value); + } + + @Override + public void onError(Throwable throwable) { + fail(throwable); + } + + @Override + public void onCompleted() {} + }; + } + + private enum AdmissionReadProofOperation { + AUDIT, + RUNTIME_STATE, + COMPATIBILITY, + PREPARED_VERSION + } + + private enum AdmissionCallerContext { + OTHER_TENANT, + BASIC_ROLE, + ABSENT + } + + private record AdmissionReadProofFixture( + GameSessionControlPlaneGrpcService service, + GameInstanceRepository gameInstanceRepository, + RuntimeRegionStatusRepository runtimeRegionStatusRepository, + GameplayAdmissionPointerAuthorityService pointerAuthority, + InstanceCutoverCompatibilityService compatibilityService, + VersionUpgradePreparationService preparationService) {} + private static void stubLockedGameInstance( GameInstanceRepository repository, GameInstance instance) { Mockito.when(repository.findByTenantIdAndGameInstanceIdForUpdate(1L, 7L)) diff --git a/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/service/impl/GameSessionGrpcServiceTest.java b/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/service/impl/GameSessionGrpcServiceTest.java index e2498b7385..1db89fc77a 100644 --- a/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/service/impl/GameSessionGrpcServiceTest.java +++ b/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/service/impl/GameSessionGrpcServiceTest.java @@ -1196,6 +1196,69 @@ public void onCompleted() {} assertFalse(pointerResponse.get().hasAdmissionPointer()); } + @Test + void unknownNamedWorldReturnsInvalidArgument() { + GameplayAdmissionPointerAuthorityService pointerAuthorityService = + Mockito.mock(GameplayAdmissionPointerAuthorityService.class); + Mockito.when(pointerAuthorityService.listPointers()).thenReturn(List.of()); + GameSessionGrpcService service = + newService( + Mockito.mock(PingService.class), + Mockito.mock(GameInstanceService.class), + Mockito.mock(FeatureFlagService.class), + Mockito.mock(TextCommandInterpreter.class), + Mockito.mock(GameInstanceRepository.class), + pointerAuthorityService, + new GameplayWorldCatalog(pointerAuthorityService), + Mockito.mock(TickService.class), + new SimpleMeterRegistry(), + Mockito.mock(IpConnectionLimiter.class)); + + ListGameplayRealmsResponse response = listGameplayRealms(service, "unknown-world"); + + assertEquals("INVALID_ARGUMENT", response.getError().getCode()); + assertEquals(0, response.getRealmsCount()); + } + + @Test + void malformedWorldSelectorRemainsInvalidArgument() { + GameplayAdmissionPointerAuthorityService pointerAuthorityService = + Mockito.mock(GameplayAdmissionPointerAuthorityService.class); + GameSessionGrpcService service = + newService( + Mockito.mock(PingService.class), + Mockito.mock(GameInstanceService.class), + Mockito.mock(FeatureFlagService.class), + Mockito.mock(TextCommandInterpreter.class), + Mockito.mock(GameInstanceRepository.class), + pointerAuthorityService, + new GameplayWorldCatalog(pointerAuthorityService), + Mockito.mock(TickService.class), + new SimpleMeterRegistry(), + Mockito.mock(IpConnectionLimiter.class)); + + ListGameplayRealmsResponse response = listGameplayRealms(service, "not a world"); + + assertEquals("INVALID_ARGUMENT", response.getError().getCode()); + assertEquals(0, response.getRealmsCount()); + } + + @Test + void listGameplayRealmsTrimsWorldSelectorBeforeAuthorityResolution() { + GameplayAdmissionPointerAuthorityService pointerAuthorityService = + Mockito.mock(GameplayAdmissionPointerAuthorityService.class); + Mockito.when(pointerAuthorityService.listPointers()) + .thenReturn(List.of(authorityPointer("alpha", "live", 7L, 44L, true, true))); + GameSessionGrpcService service = catalogService(pointerAuthorityService); + + ListGameplayRealmsResponse response = listGameplayRealms(service, " alpha "); + + assertEquals("", response.getError().getCode()); + assertEquals(1, response.getRealmsCount()); + assertEquals("live", response.getRealms(0).getRealmSlug()); + Mockito.verify(pointerAuthorityService).listPointers(); + } + @Test void listGameplayRealmsMapsUnexpectedDependencyFailureToInternalAndCompletes() { GameplayAdmissionPointerAuthorityService pointerAuthorityService = diff --git a/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/service/impl/GameSessionRuntimeControlPlaneReadServiceTest.java b/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/service/impl/GameSessionRuntimeControlPlaneReadServiceTest.java index 89cf63c43b..202fe14169 100644 --- a/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/service/impl/GameSessionRuntimeControlPlaneReadServiceTest.java +++ b/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/service/impl/GameSessionRuntimeControlPlaneReadServiceTest.java @@ -194,6 +194,26 @@ void runtimeReadFailsClosedWhenAdmissionPointerCatalogRevisionIsMissing() { error.getMessage()); } + @Test + void runtimeReadFailsClosedWhenAdmissionPointerTenantIdIsZero() { + assertRuntimeReadFailsClosedForAdmissionPointerIdentity(0L, 7L); + } + + @Test + void runtimeReadFailsClosedWhenAdmissionPointerTenantIdIsNegative() { + assertRuntimeReadFailsClosedForAdmissionPointerIdentity(-1L, 7L); + } + + @Test + void runtimeReadFailsClosedWhenAdmissionPointerGameInstanceIdIsZero() { + assertRuntimeReadFailsClosedForAdmissionPointerIdentity(1L, 0L); + } + + @Test + void runtimeReadFailsClosedWhenAdmissionPointerGameInstanceIdIsNegative() { + assertRuntimeReadFailsClosedForAdmissionPointerIdentity(1L, -1L); + } + @Test void runtimeReadOmitsPublicationForUnpinnedInstanceWithoutCallingGameDesign() { WorldManagementClient world = mock(WorldManagementClient.class); @@ -573,6 +593,49 @@ private GameSessionRuntimeControlPlaneReadService service(WorldManagementClient return service(world, "RUNNING"); } + private void assertRuntimeReadFailsClosedForAdmissionPointerIdentity( + long pointerTenantId, long pointerGameInstanceId) { + WorldManagementClient world = mock(WorldManagementClient.class); + when(world.getWorldInstanceLifecycle(1L, 7L)) + .thenReturn( + worldLifecycle( + 1L, 7L, 3L, WorldInstanceLifecycleStatus.WORLD_INSTANCE_LIFECYCLE_STATUS_ACTIVE)); + GameplayAdmissionPointerAuthorityService authority = + mock(GameplayAdmissionPointerAuthorityService.class); + when(authority.listByRuntimeTarget(1L, 7L)) + .thenReturn( + List.of( + new GameplayAdmissionPointerSnapshot( + "demo", + "Demo World", + "production", + "Production", + pointerTenantId, + pointerGameInstanceId, + 11L, + true, + true, + true, + "SHARED", + "CREATE_ALLOWED", + 12L, + UUID.fromString("11111111-1111-1111-1111-111111111111"), + UUID.fromString("22222222-2222-2222-2222-222222222222")))); + GameSessionRuntimeControlPlaneReadService service = + service(world, "RUNNING", null, null, null, null, authority); + + GameSessionRuntimeControlPlaneReadService.RuntimeStateException error = + assertThrows( + GameSessionRuntimeControlPlaneReadService.RuntimeStateException.class, + () -> service.getGameInstanceRuntimeState(1L, runtimeRequest())); + + assertEquals("ADMISSION_POINTER_AUTHORITY_UNAVAILABLE", error.code()); + assertEquals( + "ADMISSION_POINTER_AUTHORITY_UNAVAILABLE: current admission pointer durable identity or catalog revision is unavailable", + error.getMessage()); + verify(authority).listByRuntimeTarget(1L, 7L); + } + private GameSessionRuntimeControlPlaneReadService service( WorldManagementClient world, String status) { return service(world, status, null, null); diff --git a/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/support/MutableDefaultDemoCatalogTest.java b/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/support/MutableDefaultDemoCatalogTest.java index 39e395baa0..6999999c1e 100644 --- a/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/support/MutableDefaultDemoCatalogTest.java +++ b/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/support/MutableDefaultDemoCatalogTest.java @@ -5,11 +5,13 @@ import java.util.ArrayList; import java.util.List; +import java.util.Map; 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.GameplayAdmissionPointerAuthorityService.PointerAuditKey; import net.firedevops.firemud.gamesession.service.GameplayAdmissionPointerMutation; import net.firedevops.firemud.gamesession.service.GameplayAdmissionPointerSnapshot; import net.firedevops.firemud.gamesession.support.TestGameplayWorldCatalogs; @@ -165,6 +167,11 @@ public List listPointers() { return List.copyOf(pointers); } + @Override + public List listPointersForTenants(List tenantIds) { + return pointers.stream().filter(pointer -> tenantIds.contains(pointer.tenantId())).toList(); + } + @Override public List listPointersByTenant(long tenantId) { return pointers.stream().filter(pointer -> pointer.tenantId() == tenantId).toList(); @@ -200,5 +207,17 @@ public List listPointerAudit( long tenantId, String worldSlug, String realmSlug) { return List.of(); } + + @Override + public Optional findLatestPointerAudit( + long tenantId, String worldSlug, String realmSlug) { + return Optional.empty(); + } + + @Override + public Map findLatestPointerAudits( + List keys) { + return Map.of(); + } } } diff --git a/services/game-session-service/src/testFixtures/java/net/firedevops/firemud/gamesession/testsupport/GameplayLoadScenarios.java b/services/game-session-service/src/testFixtures/java/net/firedevops/firemud/gamesession/testsupport/GameplayLoadScenarios.java index a167165a0f..cd9a886fa2 100644 --- a/services/game-session-service/src/testFixtures/java/net/firedevops/firemud/gamesession/testsupport/GameplayLoadScenarios.java +++ b/services/game-session-service/src/testFixtures/java/net/firedevops/firemud/gamesession/testsupport/GameplayLoadScenarios.java @@ -63,8 +63,8 @@ public static List seedPlayers( GameplayCrossServiceStack.SYNTHETIC_LOAD_ACTOR, "Seed per-player load-test admission pointer", "load-test:" + accountId, - null, - null, + 0L, + 0L, null)); long sessionId = firstAccountId + 10_000L + i + 1; String email = "player" + (i + 1) + "@example.com"; diff --git a/services/logging-admin-service/src/main/java/net/firedevops/firemud/loggingadmin/client/GameSessionControlPlaneClient.java b/services/logging-admin-service/src/main/java/net/firedevops/firemud/loggingadmin/client/GameSessionControlPlaneClient.java index 0cd3158367..2d76ae0c4b 100644 --- a/services/logging-admin-service/src/main/java/net/firedevops/firemud/loggingadmin/client/GameSessionControlPlaneClient.java +++ b/services/logging-admin-service/src/main/java/net/firedevops/firemud/loggingadmin/client/GameSessionControlPlaneClient.java @@ -2,6 +2,7 @@ import jakarta.annotation.PostConstruct; import java.io.IOException; +import java.util.List; import javax.net.ssl.SSLException; import net.firedevops.firemud.common.config.ServiceEndpointsProperties; import net.firedevops.firemud.common.grpc.AbstractReloadingBlockingGrpcClient; @@ -83,8 +84,13 @@ protected GameSessionControlPlaneServiceGrpc.GameSessionControlPlaneServiceBlock GameSessionControlPlaneServiceGrpc.newBlockingStub(channel).withCompression("gzip")); } - public ListAdmissionPointersResponse listAdmissionPointers() { - return stub().listAdmissionPointers(ListAdmissionPointersRequest.getDefaultInstance()); + public ListAdmissionPointersResponse listAdmissionPointers(List tenantIds) { + return stub() + .listAdmissionPointers( + ListAdmissionPointersRequest.newBuilder() + .addAllTenantIds( + tenantIds.stream().map(tenantId -> Long.toString(tenantId)).toList()) + .build()); } public ListAdmissionPointerAuditResponse listAdmissionPointerAudit( diff --git a/services/logging-admin-service/src/main/java/net/firedevops/firemud/loggingadmin/dto/AdmissionPointerDto.java b/services/logging-admin-service/src/main/java/net/firedevops/firemud/loggingadmin/dto/AdmissionPointerDto.java index d19975bd8c..1c78b32457 100644 --- a/services/logging-admin-service/src/main/java/net/firedevops/firemud/loggingadmin/dto/AdmissionPointerDto.java +++ b/services/logging-admin-service/src/main/java/net/firedevops/firemud/loggingadmin/dto/AdmissionPointerDto.java @@ -1,6 +1,7 @@ package net.firedevops.firemud.loggingadmin.dto; import java.time.Instant; +import java.util.UUID; public record AdmissionPointerDto( String worldSlug, @@ -10,6 +11,9 @@ public record AdmissionPointerDto( Long tenantId, Long gameInstanceId, long pointerVersion, + Long catalogRevision, + UUID realmId, + UUID playableStateNamespaceId, boolean visible, boolean publicProductionRealm, boolean requiresCharacterSelection, diff --git a/services/logging-admin-service/src/main/java/net/firedevops/firemud/loggingadmin/dto/ExecutePreparedVersionCutoverRequest.java b/services/logging-admin-service/src/main/java/net/firedevops/firemud/loggingadmin/dto/ExecutePreparedVersionCutoverRequest.java index 641163510d..d8f8e3aa41 100644 --- a/services/logging-admin-service/src/main/java/net/firedevops/firemud/loggingadmin/dto/ExecutePreparedVersionCutoverRequest.java +++ b/services/logging-admin-service/src/main/java/net/firedevops/firemud/loggingadmin/dto/ExecutePreparedVersionCutoverRequest.java @@ -13,4 +13,5 @@ public record ExecutePreparedVersionCutoverRequest( @NotBlank @Size(max = 64) String preparedVersionUpgradeId, @Size(max = 255) String reason, @Size(max = 128) String controlPlaneRequestId, - Long expectedPointerVersion) {} + @NotNull @Positive Long expectedPointerVersion, + @NotNull @Positive Long expectedCatalogRevision) {} diff --git a/services/logging-admin-service/src/main/java/net/firedevops/firemud/loggingadmin/dto/SetAdmissionPointerRequest.java b/services/logging-admin-service/src/main/java/net/firedevops/firemud/loggingadmin/dto/SetAdmissionPointerRequest.java index f27f22ac12..c35cc2eba8 100644 --- a/services/logging-admin-service/src/main/java/net/firedevops/firemud/loggingadmin/dto/SetAdmissionPointerRequest.java +++ b/services/logging-admin-service/src/main/java/net/firedevops/firemud/loggingadmin/dto/SetAdmissionPointerRequest.java @@ -3,6 +3,7 @@ import jakarta.validation.constraints.NotBlank; import jakarta.validation.constraints.NotNull; import jakarta.validation.constraints.Positive; +import jakarta.validation.constraints.PositiveOrZero; import jakarta.validation.constraints.Size; public record SetAdmissionPointerRequest( @@ -19,5 +20,6 @@ public record SetAdmissionPointerRequest( @NotBlank @Size(max = 50) String characterCreationPolicy, @Size(max = 255) String reason, @Size(max = 128) String controlPlaneRequestId, - Long expectedPointerVersion, + @NotNull @PositiveOrZero Long expectedPointerVersion, + @NotNull @PositiveOrZero Long expectedCatalogRevision, @Size(max = 64) String preparedVersionUpgradeId) {} diff --git a/services/logging-admin-service/src/main/java/net/firedevops/firemud/loggingadmin/service/impl/AdmissionPointerServiceImpl.java b/services/logging-admin-service/src/main/java/net/firedevops/firemud/loggingadmin/service/impl/AdmissionPointerServiceImpl.java index 89196cd3f5..0816ee7720 100644 --- a/services/logging-admin-service/src/main/java/net/firedevops/firemud/loggingadmin/service/impl/AdmissionPointerServiceImpl.java +++ b/services/logging-admin-service/src/main/java/net/firedevops/firemud/loggingadmin/service/impl/AdmissionPointerServiceImpl.java @@ -4,6 +4,7 @@ import io.micrometer.core.annotation.Timed; import java.time.Instant; import java.util.List; +import java.util.Objects; import java.util.UUID; import net.firedevops.firemud.common.LoggingUtil; import net.firedevops.firemud.common.security.SessionContext; @@ -49,7 +50,14 @@ public AdmissionPointerServiceImpl(GameSessionControlPlaneClient gameSessionCont @Override @Timed(value = "loggingadmin.admissionPointer.list") public List listPointers() { - ListAdmissionPointersResponse response = gameSessionControlPlaneClient.listAdmissionPointers(); + boolean globalRead = SessionContext.hasGlobalPrivilegedRole(); + List tenantIds = globalRead ? List.of() : accessibleTenantIds(); + if (!globalRead && tenantIds.isEmpty()) { + return List.of(); + } + + ListAdmissionPointersResponse response = + gameSessionControlPlaneClient.listAdmissionPointers(tenantIds); requireNoError(response.getError()); return response.getPointersList().stream() .filter(this::hasTenantAccess) @@ -99,6 +107,9 @@ public AdmissionPointerDto setPointer(SetAdmissionPointerRequest request) { if (request.expectedPointerVersion() != null) { builder.setExpectedPointerVersion(request.expectedPointerVersion()); } + if (request.expectedCatalogRevision() != null) { + builder.setExpectedCatalogRevision(request.expectedCatalogRevision()); + } if (request.preparedVersionUpgradeId() != null && !request.preparedVersionUpgradeId().isBlank()) { builder.setPreparedVersionUpgradeId(request.preparedVersionUpgradeId()); @@ -137,6 +148,9 @@ public AdmissionPointerDto executePreparedVersionCutover( if (request.expectedPointerVersion() != null) { builder.setExpectedPointerVersion(request.expectedPointerVersion()); } + if (request.expectedCatalogRevision() != null) { + builder.setExpectedCatalogRevision(request.expectedCatalogRevision()); + } ExecutePreparedVersionCutoverResponse response = gameSessionControlPlaneClient.executePreparedVersionCutover(builder.build()); requireNoError(response.getError()); @@ -236,6 +250,25 @@ private boolean hasTenantAccess(AdmissionPointerControlPlaneEntry entry) { return SessionContext.hasTenantAccess(parseLong(entry.getTenantId(), "tenant_id")); } + private List accessibleTenantIds() { + return SessionContext.getScopedRolesMap().keySet().stream() + .map(this::parsePositiveCanonicalTenantId) + .filter(Objects::nonNull) + .filter(SessionContext::hasTenantAccess) + .distinct() + .sorted() + .toList(); + } + + private Long parsePositiveCanonicalTenantId(String value) { + try { + long tenantId = Long.parseLong(value); + return tenantId > 0L && Long.toString(tenantId).equals(value) ? tenantId : null; + } catch (NumberFormatException ex) { + return null; + } + } + private AdmissionPointerDto toDto(AdmissionPointerControlPlaneEntry entry) { return new AdmissionPointerDto( entry.getWorldSlug(), @@ -245,6 +278,9 @@ private AdmissionPointerDto toDto(AdmissionPointerControlPlaneEntry entry) { parseLong(entry.getTenantId(), "tenant_id"), parseLong(entry.getGameInstanceId(), "game_instance_id"), entry.getPointerVersion(), + entry.hasCatalogRevision() ? entry.getCatalogRevision() : null, + parseOptionalUuid(entry.getRealmId(), "realm_id"), + parseOptionalUuid(entry.getPlayableStateNamespaceId(), "playable_state_namespace_id"), entry.getVisible(), entry.getPublicProductionRealm(), entry.getRequiresCharacterSelection(), @@ -257,6 +293,18 @@ private AdmissionPointerDto toDto(AdmissionPointerControlPlaneEntry entry) { entry.getOccurredAtMs() <= 0 ? null : Instant.ofEpochMilli(entry.getOccurredAtMs())); } + private UUID parseOptionalUuid(String value, String fieldName) { + if (value == null || value.isBlank()) { + return null; + } + try { + return UUID.fromString(value); + } catch (IllegalArgumentException ex) { + throw new ResponseStatusException( + HttpStatus.INTERNAL_SERVER_ERROR, fieldName + " from Game Session must be a UUID", ex); + } + } + private PreparedVersionUpgradeDto toDto(PreparedVersionUpgrade preparation) { return new PreparedVersionUpgradeDto( preparation.getPreparationId(), @@ -368,6 +416,8 @@ private void requireNoError(ErrorDetail error) { switch (error.getCode()) { case "INVALID_ARGUMENT" -> HttpStatus.BAD_REQUEST; case "PERMISSION_DENIED" -> HttpStatus.FORBIDDEN; + case "AUTHORITY_UNAVAILABLE", "ADMISSION_POINTER_AUTHORITY_UNAVAILABLE" -> + HttpStatus.SERVICE_UNAVAILABLE; case "POINTER_VERSION_MISMATCH" -> HttpStatus.CONFLICT; case "CUTOVER_PREPARATION_INVALID" -> HttpStatus.CONFLICT; case "NOT_FOUND" -> HttpStatus.NOT_FOUND; diff --git a/services/logging-admin-service/src/main/java/net/firedevops/firemud/loggingadmin/service/impl/LoggingAdminGrpcService.java b/services/logging-admin-service/src/main/java/net/firedevops/firemud/loggingadmin/service/impl/LoggingAdminGrpcService.java index a6f731da0c..7372b2d659 100644 --- a/services/logging-admin-service/src/main/java/net/firedevops/firemud/loggingadmin/service/impl/LoggingAdminGrpcService.java +++ b/services/logging-admin-service/src/main/java/net/firedevops/firemud/loggingadmin/service/impl/LoggingAdminGrpcService.java @@ -27,9 +27,6 @@ public class LoggingAdminGrpcService extends LoggingAdminServiceGrpc.LoggingAdmi "Moderation actions are unavailable until the shared mutation gate is implemented"; private static final String FEATURE_FLAG_TOGGLE_UNAVAILABLE_MESSAGE = "Feature-flag toggles are unavailable until the shared mutation gate is implemented"; - private static final String ACCOUNT_AUDIT_RECEIVER_UNAVAILABLE_MESSAGE = - "Account audit receipt receiver is unavailable until the immutable receipt contract is " - + "implemented"; private static final Set MODERATION_POLICY_CALLERS = Set.of("game-session-service", "social-groups-service"); @@ -177,40 +174,10 @@ public void queryLogs( @Timed(value = "loggingadminGrpc.createLogEvent") public void createLogEvent( CreateLogEventRequest request, StreamObserver responseObserver) { - try { - AdminRoleGuard.requireAdminRole(); - GrpcAppErrors.error( - meterRegistry, - logger, - "CreateLogEvent", - "UNAVAILABLE", - ACCOUNT_AUDIT_RECEIVER_UNAVAILABLE_MESSAGE); - } catch (AdminAuthorizationException ex) { - CreateLogEventResponse response = - CreateLogEventResponse.newBuilder() - .setError( - GrpcAppErrors.error( - meterRegistry, - logger, - "CreateLogEvent", - "PERMISSION_DENIED", - ex.getMessage())) - .build(); - responseObserver.onNext(response); - responseObserver.onCompleted(); - return; - } catch (Exception ex) { - CreateLogEventResponse response = - CreateLogEventResponse.newBuilder() - .setError(GrpcAppErrors.internal(meterRegistry, logger, "CreateLogEvent", ex)) - .build(); - responseObserver.onNext(response); - responseObserver.onCompleted(); - return; - } responseObserver.onError( Status.UNAVAILABLE - .withDescription(ACCOUNT_AUDIT_RECEIVER_UNAVAILABLE_MESSAGE) + .withDescription( + "Typed account audit receipt receiver is unavailable in this service revision") .asRuntimeException()); } diff --git a/services/logging-admin-service/src/main/resources/openapi.yaml b/services/logging-admin-service/src/main/resources/openapi.yaml index 301a5cc89e..08d306c559 100644 --- a/services/logging-admin-service/src/main/resources/openapi.yaml +++ b/services/logging-admin-service/src/main/resources/openapi.yaml @@ -1238,10 +1238,25 @@ components: type: string tenantId: type: integer + format: int64 gameInstanceId: type: integer + format: int64 pointerVersion: type: integer + format: int64 + catalogRevision: + type: integer + format: int64 + nullable: true + realmId: + type: string + format: uuid + nullable: true + playableStateNamespaceId: + type: string + format: uuid + nullable: true visible: type: boolean publicProductionRealm: @@ -1659,6 +1674,13 @@ paths: get: summary: List visible gameplay admission pointers operationId: listAdmissionPointers + description: >- + Tenant-scoped callers receive pointers only for their authorized tenant + scopes. Global platform administrators and moderators receive the + all-tenant list. Each current pointer in the selected scope must have a + latest audit row matching its catalog revision, realm ID, and playable-state + namespace. Missing or incomplete current authority in that scope returns + 503. Historical audit reads preserve unknown legacy identity fields. responses: '200': description: Admission pointer list @@ -1675,6 +1697,12 @@ paths: $ref: '#/components/schemas/AdmissionPointerDto' error: $ref: '#/components/schemas/ErrorDetail' + '503': + description: Current admission-pointer authority or matching audit evidence is unavailable + content: + application/json: + schema: + $ref: '#/components/schemas/ApiResponseError' /admission-pointers/{tenantId}/{worldSlug}/{realmSlug}/audit: get: summary: Read admission-pointer audit history @@ -1712,6 +1740,12 @@ paths: $ref: '#/components/schemas/AdmissionPointerDto' error: $ref: '#/components/schemas/ErrorDetail' + '503': + description: Admission-pointer audit authority is unavailable + content: + application/json: + schema: + $ref: '#/components/schemas/ApiResponseError' /admission-pointers/runtime-state/{tenantId}/{gameInstanceId}: get: summary: Read canonical current runtime state @@ -1743,6 +1777,12 @@ paths: $ref: '#/components/schemas/GameInstanceRuntimeStateDto' error: $ref: '#/components/schemas/ErrorDetail' + '503': + description: Current admission-pointer authority or required pointer identity is unavailable + content: + application/json: + schema: + $ref: '#/components/schemas/ApiResponseError' /admission-pointers/version-upgrades/{tenantId}/{preparationId}: get: summary: Read a prepared version-upgrade proof (live read) @@ -1772,6 +1812,12 @@ paths: $ref: '#/components/schemas/PreparedVersionUpgradeDto' error: $ref: '#/components/schemas/ErrorDetail' + '503': + description: Prepared version-upgrade proof authority is unavailable + content: + application/json: + schema: + $ref: '#/components/schemas/ApiResponseError' /admission-pointers/version-upgrades/{tenantId}/{sourceGameInstanceId}/compatibility/{targetVersionId}: get: summary: Read version cutover compatibility for one source instance and target version diff --git a/services/logging-admin-service/src/test/java/unit/net/firedevops/firemud/loggingadmin/client/GameSessionControlPlaneClientTest.java b/services/logging-admin-service/src/test/java/unit/net/firedevops/firemud/loggingadmin/client/GameSessionControlPlaneClientTest.java new file mode 100644 index 0000000000..7834e15fe6 --- /dev/null +++ b/services/logging-admin-service/src/test/java/unit/net/firedevops/firemud/loggingadmin/client/GameSessionControlPlaneClientTest.java @@ -0,0 +1,85 @@ +package net.firedevops.firemud.loggingadmin.client; + +import static org.assertj.core.api.Assertions.assertThat; +import static org.mockito.ArgumentMatchers.any; +import static org.mockito.Mockito.mock; +import static org.mockito.Mockito.verify; +import static org.mockito.Mockito.when; + +import io.grpc.ManagedChannel; +import java.util.List; +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.gamesession.v1.GameSessionControlPlaneServiceGrpc; +import net.firedevops.firemud.gamesession.v1.ListAdmissionPointersRequest; +import net.firedevops.firemud.gamesession.v1.ListAdmissionPointersResponse; +import org.junit.jupiter.api.Test; +import org.mockito.ArgumentCaptor; + +class GameSessionControlPlaneClientTest { + + @Test + void listAdmissionPointersSendsTenantIdsAsDecimalStrings() throws Exception { + ServiceEndpointsProperties endpoints = new ServiceEndpointsProperties(); + CommonGrpcClientProperties grpc = new CommonGrpcClientProperties(); + grpc.setPlaintext(true); + ManagedChannel channel = mock(ManagedChannel.class); + GrpcChannelFactory channelFactory = + new GrpcChannelFactory() { + @Override + public ManagedChannel buildChannel( + String target, + int defaultPort, + CommonGrpcClientProperties properties, + boolean keepAlive) { + return channel; + } + }; + GameSessionControlPlaneServiceGrpc.GameSessionControlPlaneServiceBlockingStub stub = + mock(GameSessionControlPlaneServiceGrpc.GameSessionControlPlaneServiceBlockingStub.class); + when(stub.listAdmissionPointers(any(ListAdmissionPointersRequest.class))) + .thenReturn(ListAdmissionPointersResponse.getDefaultInstance()); + TestGameSessionControlPlaneClient client = + new TestGameSessionControlPlaneClient(endpoints, grpc, channelFactory, stub); + + try { + client.initialize(); + client.listAdmissionPointers(List.of(2L, Long.MAX_VALUE)); + + ArgumentCaptor requestCaptor = + ArgumentCaptor.forClass(ListAdmissionPointersRequest.class); + verify(stub).listAdmissionPointers(requestCaptor.capture()); + assertThat(requestCaptor.getValue().getTenantIdsList()) + .containsExactly("2", Long.toString(Long.MAX_VALUE)); + } finally { + client.close(); + } + } + + private static final class TestGameSessionControlPlaneClient + extends GameSessionControlPlaneClient { + private final GameSessionControlPlaneServiceGrpc.GameSessionControlPlaneServiceBlockingStub + stub; + + private TestGameSessionControlPlaneClient( + ServiceEndpointsProperties endpoints, + CommonGrpcClientProperties tlsProps, + GrpcChannelFactory channelFactory, + GameSessionControlPlaneServiceGrpc.GameSessionControlPlaneServiceBlockingStub stub) { + super(endpoints, tlsProps, channelFactory, BlockingGrpcStubCustomizer.noop()); + this.stub = stub; + } + + private void initialize() throws Exception { + initReloadingClient(); + } + + @Override + protected GameSessionControlPlaneServiceGrpc.GameSessionControlPlaneServiceBlockingStub + buildStub(ManagedChannel channel) { + return applyStubCustomizer(stub); + } + } +} diff --git a/services/logging-admin-service/src/test/java/unit/net/firedevops/firemud/loggingadmin/controller/AdmissionPointerControllerTest.java b/services/logging-admin-service/src/test/java/unit/net/firedevops/firemud/loggingadmin/controller/AdmissionPointerControllerTest.java index d5d03bc7ec..ce2a806be5 100644 --- a/services/logging-admin-service/src/test/java/unit/net/firedevops/firemud/loggingadmin/controller/AdmissionPointerControllerTest.java +++ b/services/logging-admin-service/src/test/java/unit/net/firedevops/firemud/loggingadmin/controller/AdmissionPointerControllerTest.java @@ -1,5 +1,7 @@ package net.firedevops.firemud.loggingadmin.controller; +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertNotNull; import static org.mockito.Mockito.verifyNoInteractions; import static org.mockito.Mockito.when; import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.get; @@ -9,6 +11,7 @@ import java.time.Instant; import java.util.List; import java.util.Map; +import java.util.UUID; import net.firedevops.firemud.common.GlobalExceptionHandler; import net.firedevops.firemud.common.config.CommonSecurityAutoConfiguration; import net.firedevops.firemud.common.config.CommonSecurityServletAutoConfiguration; @@ -28,6 +31,8 @@ import org.springframework.http.HttpHeaders; import org.springframework.test.context.bean.override.mockito.MockitoBean; import org.springframework.test.web.servlet.MockMvc; +import org.springframework.web.server.ResponseStatusException; +import org.yaml.snakeyaml.Yaml; @WebMvcTest(AdmissionPointerController.class) @AutoConfigureMockMvc(addFilters = false) @@ -61,6 +66,9 @@ void listPointersReturnsVisibleEntries() throws Exception { 2L, 7L, 3L, + 5L, + UUID.fromString("11111111-1111-1111-1111-111111111111"), + UUID.fromString("22222222-2222-2222-2222-222222222222"), true, true, false, @@ -77,7 +85,73 @@ void listPointersReturnsVisibleEntries() throws Exception { .perform(get("/admission-pointers").header(HttpHeaders.AUTHORIZATION, "Bearer " + token)) .andExpect(status().isOk()) .andExpect(jsonPath("$.data[0].worldSlug").value("demo")) - .andExpect(jsonPath("$.data[0].tenantId").value(2)); + .andExpect(jsonPath("$.data[0].tenantId").value(2)) + .andExpect(jsonPath("$.data[0].catalogRevision").value(5)) + .andExpect(jsonPath("$.data[0].realmId").value("11111111-1111-1111-1111-111111111111")) + .andExpect( + jsonPath("$.data[0].playableStateNamespaceId") + .value("22222222-2222-2222-2222-222222222222")); + } + + @Test + void listPointersMapsUnavailableCurrentAuthorityToServiceUnavailable() throws Exception { + when(admissionPointerService.listPointers()) + .thenThrow( + new ResponseStatusException( + org.springframework.http.HttpStatus.SERVICE_UNAVAILABLE, + "current pointer authority unavailable")); + String token = jwtUtil.generateToken("user", Map.of("globalRoles", List.of("platformAdmin"))); + + mockMvc + .perform(get("/admission-pointers").header(HttpHeaders.AUTHORIZATION, "Bearer " + token)) + .andExpect(status().isServiceUnavailable()) + .andExpect(jsonPath("$.error.code").value("SERVICE_UNAVAILABLE")) + .andExpect(jsonPath("$.error.message").value("current pointer authority unavailable")); + } + + @Test + void openApiDocumentsAdmissionPointerReadContracts() throws Exception { + Map document; + try (var input = getClass().getResourceAsStream("/openapi.yaml")) { + assertNotNull(input); + document = new Yaml().load(input); + } + + Map paths = (Map) document.get("paths"); + for (String path : + List.of( + "/admission-pointers", + "/admission-pointers/{tenantId}/{worldSlug}/{realmSlug}/audit", + "/admission-pointers/runtime-state/{tenantId}/{gameInstanceId}", + "/admission-pointers/version-upgrades/{tenantId}/{preparationId}")) { + Map admissionPointers = (Map) paths.get(path); + Map getOperation = (Map) admissionPointers.get("get"); + Map responses = (Map) getOperation.get("responses"); + Map success = (Map) responses.get("200"); + Map unavailable = (Map) responses.get("503"); + assertNotNull(unavailable, path + " must document the unavailable response"); + Map successContent = (Map) success.get("content"); + Map unavailableContent = (Map) unavailable.get("content"); + Map successJson = (Map) successContent.get("application/json"); + Map unavailableJson = (Map) unavailableContent.get("application/json"); + Map successSchema = (Map) successJson.get("schema"); + Map unavailableSchema = (Map) unavailableJson.get("schema"); + + assertEquals("#/components/schemas/ApiResponseError", unavailableSchema.get("$ref")); + assertEquals("object", successSchema.get("type")); + } + + Map components = (Map) document.get("components"); + Map schemas = (Map) components.get("schemas"); + Map pointer = (Map) schemas.get("AdmissionPointerDto"); + Map properties = (Map) pointer.get("properties"); + for (String field : + List.of("tenantId", "gameInstanceId", "pointerVersion", "catalogRevision")) { + Map fieldSchema = (Map) properties.get(field); + assertEquals("integer", fieldSchema.get("type")); + assertEquals("int64", fieldSchema.get("format")); + } + assertEquals(true, ((Map) properties.get("catalogRevision")).get("nullable")); } @Test @@ -93,6 +167,9 @@ void auditReturnsEntries() throws Exception { 2L, 7L, 3L, + 5L, + UUID.fromString("11111111-1111-1111-1111-111111111111"), + UUID.fromString("22222222-2222-2222-2222-222222222222"), true, true, false, @@ -111,7 +188,32 @@ void auditReturnsEntries() throws Exception { get("/admission-pointers/2/demo/production/audit") .header(HttpHeaders.AUTHORIZATION, "Bearer " + token)) .andExpect(status().isOk()) - .andExpect(jsonPath("$.data[0].pointerVersion").value(3)); + .andExpect(jsonPath("$.data[0].pointerVersion").value(3)) + .andExpect(jsonPath("$.data[0].catalogRevision").value(5)) + .andExpect(jsonPath("$.data[0].realmId").value("11111111-1111-1111-1111-111111111111")) + .andExpect( + jsonPath("$.data[0].playableStateNamespaceId") + .value("22222222-2222-2222-2222-222222222222")); + } + + @Test + void auditMapsUnavailableAuthorityToServiceUnavailable() throws Exception { + when(admissionPointerService.listPointerAudit(2L, "demo", "production")) + .thenThrow( + new ResponseStatusException( + org.springframework.http.HttpStatus.SERVICE_UNAVAILABLE, + "admission-pointer audit authority unavailable")); + SessionContext.setContext("user", List.of("platformAdmin"), Map.of()); + String token = jwtUtil.generateToken("user", Map.of("globalRoles", List.of("platformAdmin"))); + + mockMvc + .perform( + get("/admission-pointers/2/demo/production/audit") + .header(HttpHeaders.AUTHORIZATION, "Bearer " + token)) + .andExpect(status().isServiceUnavailable()) + .andExpect(jsonPath("$.error.code").value("SERVICE_UNAVAILABLE")) + .andExpect( + jsonPath("$.error.message").value("admission-pointer audit authority unavailable")); } @Test @@ -160,6 +262,27 @@ void getRuntimeStateReturnsCanonicalRuntimeState() throws Exception { .andExpect(jsonPath("$.data.currentAdmissionPointers[0].realmSlug").value("production")); } + @Test + void getPreparedVersionUpgradeMapsUnavailableAuthorityToServiceUnavailable() throws Exception { + when(admissionPointerService.getPreparedVersionUpgrade(2L, "pvu-1")) + .thenThrow( + new ResponseStatusException( + org.springframework.http.HttpStatus.SERVICE_UNAVAILABLE, + "prepared version-upgrade proof authority unavailable")); + SessionContext.setContext("user", List.of("platformAdmin"), Map.of()); + String token = jwtUtil.generateToken("user", Map.of("globalRoles", List.of("platformAdmin"))); + + mockMvc + .perform( + get("/admission-pointers/version-upgrades/2/pvu-1") + .header(HttpHeaders.AUTHORIZATION, "Bearer " + token)) + .andExpect(status().isServiceUnavailable()) + .andExpect(jsonPath("$.error.code").value("SERVICE_UNAVAILABLE")) + .andExpect( + jsonPath("$.error.message") + .value("prepared version-upgrade proof authority unavailable")); + } + @Test void getRuntimeStateRejectsCrossTenantScopedAdmin() throws Exception { SessionContext.setContext("user", List.of(), Map.of("8", List.of("tenantAdmin"))); @@ -304,6 +427,9 @@ private GameInstanceRuntimeStateDto runtimeStateDto() { 2L, 7L, 11L, + 7L, + UUID.fromString("11111111-1111-1111-1111-111111111111"), + UUID.fromString("22222222-2222-2222-2222-222222222222"), true, true, false, diff --git a/services/logging-admin-service/src/test/java/unit/net/firedevops/firemud/loggingadmin/service/impl/AdmissionPointerServiceImplTest.java b/services/logging-admin-service/src/test/java/unit/net/firedevops/firemud/loggingadmin/service/impl/AdmissionPointerServiceImplTest.java index 07d93f5312..1da50d55ab 100644 --- a/services/logging-admin-service/src/test/java/unit/net/firedevops/firemud/loggingadmin/service/impl/AdmissionPointerServiceImplTest.java +++ b/services/logging-admin-service/src/test/java/unit/net/firedevops/firemud/loggingadmin/service/impl/AdmissionPointerServiceImplTest.java @@ -1,6 +1,7 @@ package net.firedevops.firemud.loggingadmin.service.impl; 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.Mockito.verify; @@ -59,8 +60,15 @@ void clear() { @Test void listPointersFiltersToAccessibleTenant() { - SessionContext.setContext("7", List.of(), Map.of("2", List.of("tenantAdmin"))); - when(gameSessionControlPlaneClient.listAdmissionPointers()) + SessionContext.setContext( + "7", + List.of(), + Map.of( + "2", List.of("tenantAdmin"), + "02", List.of("tenantAdmin"), + "0", List.of("tenantAdmin"), + "-3", List.of("moderator"))); + when(gameSessionControlPlaneClient.listAdmissionPointers(List.of(2L))) .thenReturn( ListAdmissionPointersResponse.newBuilder() .addPointers(pointerEntry("demo", "production", 2L, 7L, 3L)) @@ -72,6 +80,102 @@ void listPointersFiltersToAccessibleTenant() { assertEquals(1, result.size()); assertEquals("demo", result.get(0).worldSlug()); assertEquals(2L, result.get(0).tenantId()); + verify(gameSessionControlPlaneClient).listAdmissionPointers(List.of(2L)); + } + + @Test + void listPointersReturnsEmptyWithoutDispatchWhenNoAccessibleTenantScopeExists() { + List result = service.listPointers(); + + assertEquals(List.of(), result); + verifyNoInteractions(gameSessionControlPlaneClient); + } + + @Test + void globalListPointersUsesAllTenantRequest() { + SessionContext.setContext("7", List.of("platformAdmin"), Map.of()); + when(gameSessionControlPlaneClient.listAdmissionPointers(List.of())) + .thenReturn( + ListAdmissionPointersResponse.newBuilder() + .addPointers(pointerEntry("demo", "production", 2L, 7L, 3L)) + .addPointers(pointerEntry("sandbox", "preview", 8L, 11L, 1L)) + .build()); + + List result = service.listPointers(); + + assertEquals(2, result.size()); + verify(gameSessionControlPlaneClient).listAdmissionPointers(List.of()); + } + + @Test + void listPointersRejectsMalformedRealmIdAsUpstreamFailure() { + SessionContext.setContext("7", List.of("platformAdmin"), Map.of()); + AdmissionPointerControlPlaneEntry entry = + pointerEntry("demo", "production", 2L, 7L, 3L).toBuilder().setRealmId("invalid").build(); + when(gameSessionControlPlaneClient.listAdmissionPointers(List.of())) + .thenReturn(ListAdmissionPointersResponse.newBuilder().addPointers(entry).build()); + + ResponseStatusException ex = + assertThrows(ResponseStatusException.class, () -> service.listPointers()); + + assertEquals(500, ex.getStatusCode().value()); + assertEquals("realm_id from Game Session must be a UUID", ex.getReason()); + assertEquals(IllegalArgumentException.class, ex.getCause().getClass()); + } + + @Test + void listPointersRejectsMalformedPlayableStateNamespaceIdAsUpstreamFailure() { + SessionContext.setContext("7", List.of("platformAdmin"), Map.of()); + AdmissionPointerControlPlaneEntry entry = + pointerEntry("demo", "production", 2L, 7L, 3L).toBuilder() + .setPlayableStateNamespaceId("invalid") + .build(); + when(gameSessionControlPlaneClient.listAdmissionPointers(List.of())) + .thenReturn(ListAdmissionPointersResponse.newBuilder().addPointers(entry).build()); + + ResponseStatusException ex = + assertThrows(ResponseStatusException.class, () -> service.listPointers()); + + assertEquals(500, ex.getStatusCode().value()); + assertEquals("playable_state_namespace_id from Game Session must be a UUID", ex.getReason()); + assertEquals(IllegalArgumentException.class, ex.getCause().getClass()); + } + + @Test + void listPointersMapsBlankOptionalIdentityFieldsToNull() { + SessionContext.setContext("7", List.of("platformAdmin"), Map.of()); + AdmissionPointerControlPlaneEntry entry = + pointerEntry("demo", "production", 2L, 7L, 3L).toBuilder() + .setRealmId(" ") + .setPlayableStateNamespaceId("") + .build(); + when(gameSessionControlPlaneClient.listAdmissionPointers(List.of())) + .thenReturn(ListAdmissionPointersResponse.newBuilder().addPointers(entry).build()); + + AdmissionPointerDto result = service.listPointers().getFirst(); + + assertNull(result.realmId()); + assertNull(result.playableStateNamespaceId()); + } + + @Test + void listPointersMapsUnavailableAuthorityToServiceUnavailable() { + SessionContext.setContext("7", List.of("platformAdmin"), Map.of()); + when(gameSessionControlPlaneClient.listAdmissionPointers(List.of())) + .thenReturn( + ListAdmissionPointersResponse.newBuilder() + .setError( + ErrorDetail.newBuilder() + .setCode("AUTHORITY_UNAVAILABLE") + .setMessage("current pointer authority unavailable") + .build()) + .build()); + + ResponseStatusException ex = + assertThrows(ResponseStatusException.class, () -> service.listPointers()); + + assertEquals(503, ex.getStatusCode().value()); + assertEquals("current pointer authority unavailable", ex.getReason()); } @Test @@ -96,6 +200,56 @@ void listPointerAuditUsesCanonicalTenantKey() { assertEquals(1, result.size()); assertEquals(2L, result.get(0).tenantId()); + assertEquals( + java.util.UUID.fromString("11111111-1111-1111-1111-111111111111"), result.get(0).realmId()); + assertEquals( + java.util.UUID.fromString("22222222-2222-2222-2222-222222222222"), + result.get(0).playableStateNamespaceId()); + } + + @Test + void listPointerAuditMapsAdmissionPointerAuthorityUnavailableToServiceUnavailable() { + SessionContext.setContext("7", List.of(), Map.of("2", List.of("tenantAdmin"))); + when(gameSessionControlPlaneClient.listAdmissionPointerAudit(2L, "sandbox", "preview")) + .thenReturn( + ListAdmissionPointerAuditResponse.newBuilder() + .setError( + ErrorDetail.newBuilder() + .setCode("ADMISSION_POINTER_AUTHORITY_UNAVAILABLE") + .setMessage("current admission pointer authority unavailable") + .build()) + .build()); + + ResponseStatusException ex = + assertThrows( + ResponseStatusException.class, + () -> service.listPointerAudit(2L, "sandbox", "preview")); + + assertEquals(503, ex.getStatusCode().value()); + assertEquals("current admission pointer authority unavailable", ex.getReason()); + } + + @Test + void listPointerAuditLeavesHistoricalIdentityAbsent() { + SessionContext.setContext("7", List.of(), Map.of("2", List.of("tenantAdmin"))); + when(gameSessionControlPlaneClient.listAdmissionPointerAudit(2L, "sandbox", "preview")) + .thenReturn( + ListAdmissionPointerAuditResponse.newBuilder() + .addAudit( + AdmissionPointerControlPlaneEntry.newBuilder() + .setWorldSlug("sandbox") + .setRealmSlug("preview") + .setTenantId("2") + .setGameInstanceId("11") + .setPointerVersion(4L) + .setCatalogRevision(4L) + .build()) + .build()); + + AdmissionPointerDto result = service.listPointerAudit(2L, "sandbox", "preview").getFirst(); + + assertNull(result.realmId()); + assertNull(result.playableStateNamespaceId()); } @Test @@ -141,15 +295,18 @@ void setPointerUsesSessionAccountIdAsActorPrincipal() { "cutover", "req-1", 3L, + 4L, "pvu-1")); assertEquals(4L, result.pointerVersion()); + assertEquals(4L, result.catalogRevision()); verify(gameSessionControlPlaneClient) .setAdmissionPointer( org.mockito.ArgumentMatchers.argThat( request -> request.getActorPrincipal().equals("42") && request.getExpectedPointerVersion() == 3L + && request.getExpectedCatalogRevision() == 4L && request.getPreparedVersionUpgradeId().equals("pvu-1"))); } @@ -186,6 +343,7 @@ void setPointerMapsVersionMismatchToConflict() { "cutover", "req-1", 3L, + 4L, "pvu-1"))); assertEquals(409, ex.getStatusCode().value()); @@ -215,6 +373,7 @@ void setPointerRejectsMalformedCurrentAccountClaimBeforeMutation() { "cutover", "req-1", 3L, + 4L, "pvu-1"))); assertEquals(400, ex.getStatusCode().value()); @@ -233,16 +392,18 @@ void executePreparedVersionCutoverUsesSessionAccountIdAsActorPrincipal() { AdmissionPointerDto result = service.executePreparedVersionCutover( new ExecutePreparedVersionCutoverRequest( - "demo", "production", 2L, 7L, "pvu-1", "cutover", "req-1", 3L)); + "demo", "production", 2L, 7L, "pvu-1", "cutover", "req-1", 3L, 4L)); assertEquals(4L, result.pointerVersion()); + assertEquals(4L, result.catalogRevision()); verify(gameSessionControlPlaneClient) .executePreparedVersionCutover( org.mockito.ArgumentMatchers.argThat( request -> request.getActorPrincipal().equals("42") && request.getPreparedVersionUpgradeId().equals("pvu-1") - && request.getExpectedPointerVersion() == 3L)); + && request.getExpectedPointerVersion() == 3L + && request.getExpectedCatalogRevision() == 4L)); } @Test @@ -297,6 +458,12 @@ void getRuntimeStateReturnsCanonicalRuntimeState() { assertEquals(7L, result.gameInstanceId()); assertEquals("demo", result.worldSlug()); assertEquals("production", result.currentAdmissionPointers().getFirst().realmSlug()); + assertEquals( + java.util.UUID.fromString("11111111-1111-1111-1111-111111111111"), + result.currentAdmissionPointers().getFirst().realmId()); + assertEquals( + java.util.UUID.fromString("22222222-2222-2222-2222-222222222222"), + result.currentAdmissionPointers().getFirst().playableStateNamespaceId()); assertEquals("VERSION_LIFECYCLE_STATE_PUBLISHED", result.publication().publicationState()); } @@ -370,6 +537,33 @@ void getPreparedVersionUpgradeRequiresAccessibleTenant() { ResponseStatusException.class, () -> service.getPreparedVersionUpgrade(8L, "pvu-1")); } + @Test + void getPreparedVersionUpgradeMapsUnavailableAuthorityToServiceUnavailable() { + SessionContext.setContext("7", List.of(), Map.of("2", List.of("tenantAdmin"))); + when(gameSessionControlPlaneClient.getPreparedVersionUpgrade(any())) + .thenReturn( + GetPreparedVersionUpgradeResponse.newBuilder() + .setError( + ErrorDetail.newBuilder() + .setCode("AUTHORITY_UNAVAILABLE") + .setMessage("prepared version-upgrade proof authority unavailable") + .build()) + .build()); + + ResponseStatusException ex = + assertThrows( + ResponseStatusException.class, () -> service.getPreparedVersionUpgrade(2L, "pvu-1")); + + assertEquals(503, ex.getStatusCode().value()); + assertEquals("prepared version-upgrade proof authority unavailable", ex.getReason()); + verify(gameSessionControlPlaneClient) + .getPreparedVersionUpgrade( + org.mockito.ArgumentMatchers.argThat( + request -> + request.getTenantId().equals("2") + && request.getPreparationId().equals("pvu-1"))); + } + @Test void validateInstanceCutoverCompatibilityReturnsCanonicalControlPlaneProof() { SessionContext.setContext("42", List.of("platformAdmin"), Map.of()); @@ -410,6 +604,9 @@ private AdmissionPointerControlPlaneEntry pointerEntry( .setTenantId(Long.toString(tenantId)) .setGameInstanceId(Long.toString(gameInstanceId)) .setPointerVersion(pointerVersion) + .setCatalogRevision(pointerVersion) + .setRealmId("11111111-1111-1111-1111-111111111111") + .setPlayableStateNamespaceId("22222222-2222-2222-2222-222222222222") .setVisible(true) .setRequiresCharacterSelection(false) .setStateScope("SHARED") diff --git a/services/logging-admin-service/src/test/java/unit/net/firedevops/firemud/loggingadmin/service/impl/LoggingAdminGrpcServiceAuthTest.java b/services/logging-admin-service/src/test/java/unit/net/firedevops/firemud/loggingadmin/service/impl/LoggingAdminGrpcServiceAuthTest.java index 5bd6364051..4efe39ac9f 100644 --- a/services/logging-admin-service/src/test/java/unit/net/firedevops/firemud/loggingadmin/service/impl/LoggingAdminGrpcServiceAuthTest.java +++ b/services/logging-admin-service/src/test/java/unit/net/firedevops/firemud/loggingadmin/service/impl/LoggingAdminGrpcServiceAuthTest.java @@ -3,15 +3,16 @@ import static org.junit.jupiter.api.Assertions.assertEquals; import static org.junit.jupiter.api.Assertions.assertFalse; import static org.junit.jupiter.api.Assertions.assertNotNull; +import static org.junit.jupiter.api.Assertions.assertNull; import static org.junit.jupiter.api.Assertions.assertTrue; import static org.mockito.Mockito.verify; import static org.mockito.Mockito.verifyNoInteractions; import static org.mockito.Mockito.when; +import com.google.protobuf.ByteString; +import com.google.protobuf.Timestamp; import io.grpc.Status; import io.grpc.stub.StreamObserver; -import io.micrometer.core.instrument.Counter; -import io.micrometer.core.instrument.MeterRegistry; import io.micrometer.core.instrument.simple.SimpleMeterRegistry; import java.util.List; import java.util.Map; @@ -73,94 +74,19 @@ public void onCompleted() {} } @Test - void createLogEventReturnsUnavailableWithoutDispatchingUntilReceiptReceiverExists() { + void createLogEventReturnsUnavailableForTypedRequestWithoutDispatch() { SessionContext.setContext("1", List.of("platformAdmin"), Map.of()); LogEventService logEventService = Mockito.mock(LogEventService.class); - ModerationService moderationService = Mockito.mock(ModerationService.class); - SimpleMeterRegistry meterRegistry = new SimpleMeterRegistry(); - LoggingAdminGrpcService service = - new LoggingAdminGrpcService( - Mockito.mock(LogQueryService.class), logEventService, moderationService, meterRegistry); - - AtomicReference error = new AtomicReference<>(); - java.util.concurrent.atomic.AtomicBoolean receivedResponse = - new java.util.concurrent.atomic.AtomicBoolean(); - java.util.concurrent.atomic.AtomicBoolean completed = - new java.util.concurrent.atomic.AtomicBoolean(); - service.createLogEvent( - CreateLogEventRequest.newBuilder().setTenantId("1").build(), - new StreamObserver<>() { - @Override - public void onNext(CreateLogEventResponse value) { - receivedResponse.set(true); - } - - @Override - public void onError(Throwable t) { - error.set(t); - } - - @Override - public void onCompleted() { - completed.set(true); - } - }); - - assertNotNull(error.get()); - assertEquals(Status.Code.UNAVAILABLE, Status.fromThrowable(error.get()).getCode()); - String description = Status.fromThrowable(error.get()).getDescription(); - assertEquals( - "Account audit receipt receiver is unavailable until the immutable receipt contract is " - + "implemented", - description); - assertTrue(description.length() <= 128); - assertFalse(receivedResponse.get()); - assertFalse(completed.get()); - assertEquals(1.0, meterRegistry.counter("grpc.app_error", "code", "UNAVAILABLE").count()); - verifyNoInteractions(logEventService, moderationService); + assertCreateLogEventUnavailable(validCreateLogEventRequest(), logEventService); } @Test - void createLogEventMapsUnexpectedFailureToSanitizedInternalAndCompletes() { - SessionContext.setContext("1", List.of("platformAdmin"), Map.of()); + void createLogEventFailsClosedBeforeTypedRequestValidation() { LogEventService logEventService = Mockito.mock(LogEventService.class); - ModerationService moderationService = Mockito.mock(ModerationService.class); - MeterRegistry meterRegistry = Mockito.mock(MeterRegistry.class); - Counter internalErrorCounter = Mockito.mock(Counter.class); - when(meterRegistry.counter("grpc.app_error", "code", "UNAVAILABLE")) - .thenThrow(new IllegalStateException("sensitive meter-registry diagnostic")); - when(meterRegistry.counter("grpc.app_error", "code", "INTERNAL")) - .thenReturn(internalErrorCounter); - LoggingAdminGrpcService service = - new LoggingAdminGrpcService( - Mockito.mock(LogQueryService.class), logEventService, moderationService, meterRegistry); - - AtomicReference ref = new AtomicReference<>(); - java.util.concurrent.atomic.AtomicBoolean completed = - new java.util.concurrent.atomic.AtomicBoolean(); - service.createLogEvent( - CreateLogEventRequest.newBuilder().setTenantId("1").build(), - new StreamObserver<>() { - @Override - public void onNext(CreateLogEventResponse value) { - ref.set(value); - } - - @Override - public void onError(Throwable t) {} - - @Override - public void onCompleted() { - completed.set(true); - } - }); + CreateLogEventRequest unsupportedDigestVersion = + validCreateLogEventRequest().toBuilder().setPayloadDigestVersion(2).build(); - assertNotNull(ref.get()); - assertEquals("INTERNAL", ref.get().getError().getCode()); - assertEquals("Internal error", ref.get().getError().getMessage()); - assertFalse(ref.get().getError().getMessage().contains("sensitive")); - assertTrue(completed.get()); - verifyNoInteractions(logEventService, moderationService); + assertCreateLogEventUnavailable(unsupportedDigestVersion, logEventService); } @Test @@ -301,39 +227,6 @@ public void onCompleted() {} verifyNoInteractions(logQueryService); } - @Test - void createLogEventRejectsUnauthorizedCallerBeforeUnavailableResponse() { - SessionContext.setContext("1", List.of("player"), Map.of()); - LogEventService logEventService = Mockito.mock(LogEventService.class); - LoggingAdminGrpcService service = - new LoggingAdminGrpcService( - Mockito.mock(LogQueryService.class), - logEventService, - Mockito.mock(ModerationService.class), - new SimpleMeterRegistry()); - - AtomicReference ref = new AtomicReference<>(); - service.createLogEvent( - CreateLogEventRequest.newBuilder().setTenantId("1").build(), - new StreamObserver<>() { - @Override - public void onNext(CreateLogEventResponse value) { - ref.set(value); - } - - @Override - public void onError(Throwable t) {} - - @Override - public void onCompleted() {} - }); - - assertNotNull(ref.get()); - assertEquals("PERMISSION_DENIED", ref.get().getError().getCode()); - assertEquals("Admin role required", ref.get().getError().getMessage()); - verifyNoInteractions(logEventService); - } - @Test void applyModerationActionRejectsZeroSessionIdBeforeDispatch() { SessionContext.setContext("1", List.of("platformAdmin"), Map.of()); @@ -678,4 +571,65 @@ public void onCompleted() {} assertEquals("PERMISSION_DENIED", ref.get().getError().getCode()); verifyNoInteractions(moderationService); } + + private static void assertCreateLogEventUnavailable( + CreateLogEventRequest request, LogEventService logEventService) { + ModerationService moderationService = Mockito.mock(ModerationService.class); + LoggingAdminGrpcService service = + new LoggingAdminGrpcService( + Mockito.mock(LogQueryService.class), + logEventService, + moderationService, + new SimpleMeterRegistry()); + + AtomicReference response = new AtomicReference<>(); + AtomicReference error = new AtomicReference<>(); + java.util.concurrent.atomic.AtomicBoolean completed = + new java.util.concurrent.atomic.AtomicBoolean(); + service.createLogEvent( + request, + new StreamObserver<>() { + @Override + public void onNext(CreateLogEventResponse value) { + response.set(value); + } + + @Override + public void onError(Throwable throwable) { + error.set(throwable); + } + + @Override + public void onCompleted() { + completed.set(true); + } + }); + + assertNull(response.get()); + assertNotNull(error.get()); + assertEquals(Status.Code.UNAVAILABLE, Status.fromThrowable(error.get()).getCode()); + String description = Status.fromThrowable(error.get()).getDescription(); + assertEquals( + "Typed account audit receipt receiver is unavailable in this service revision", + description); + assertTrue(description.length() <= 128); + assertFalse(completed.get()); + verifyNoInteractions(logEventService, moderationService); + } + + private static CreateLogEventRequest validCreateLogEventRequest() { + ByteString payload = ByteString.copyFromUtf8("{}"); + return CreateLogEventRequest.newBuilder() + .setScope( + net.firedevops.firemud.loggingadmin.v1.AccountAuditScope.ACCOUNT_AUDIT_SCOPE_PLATFORM) + .setAuditEventId("d2719d4f-3b2a-4f64-a994-0f9ccdfdd2b3") + .setProducerService("account-service") + .setEventType("ACCOUNT_REGISTERED") + .setOccurredAt(Timestamp.newBuilder().setSeconds(1).build()) + .setSchemaVersion(1) + .setPayload(payload) + .setPayloadDigestVersion(1) + .setPayloadDigest("sha256:44136fa355b3678a1146ad16f7e8649e94fb4fc21fe77e8310c060f61caaff8a") + .build(); + } }