diff --git a/design/architecture/microservices/game-session-service/runtime-and-data.md b/design/architecture/microservices/game-session-service/runtime-and-data.md index c446f74d01..073661d170 100644 --- a/design/architecture/microservices/game-session-service/runtime-and-data.md +++ b/design/architecture/microservices/game-session-service/runtime-and-data.md @@ -10,7 +10,7 @@ The service runtime model assumes replaceable workers, not authoritative in-proc The sections below define the target-state runtime contract. Current implementation and proof status is: -- Game Session V11 adds nullable `gameplay_command.account_uuid` storage and repository round-trip mapping alongside the retained numeric `account_id`. Historical commands remain without an inferred UUID, and no producer or session carrier supplies or consumes this field yet. The focused migration and repository PostgreSQL cases are present but skip locally while Docker is disabled; Account UUID ownership remains in [Account Runtime and Data](../account-service/runtime-and-data.md) under [ADR 0020](../../decisions/adr-0020-scoped-domain-and-operational-identifiers.md). +- Game Session V11 adds nullable `gameplay_command.account_uuid` storage and repository round-trip mapping alongside the retained numeric `account_id`. Historical commands remain without an inferred UUID, and no producer or session carrier supplies or consumes this field yet; opaque internal carrier preparation and its retained-record/proof limits are tracked in [Player Access and Session](../../../project-management/implementation-tracking/player-access-and-session.md#current-status). The focused migration and repository PostgreSQL cases are present but skip locally while Docker is disabled; Account UUID ownership remains in [Account Runtime and Data](../account-service/runtime-and-data.md) under [ADR 0020](../../decisions/adr-0020-scoped-domain-and-operational-identifiers.md). - The current effective-settings HTTP read is admitted by the service-wide `PRIVILEGED` role requirement, whose shared classifier accepts any global privileged role or any tenant-scoped `tenantAdmin`/`moderator` claim. `EffectiveSettingsController` then trusts query tenant/game selectors and session ids: it can synthesize a requested tenant scope without binding it to the caller's scoped role, or resolve a persisted session without checking that its tenant is authorized by the caller. The current controller/integration tests do not prove denial of a tenant-A caller reading tenant-B settings. - **Target effective-settings boundary:** keep this as a read-only operator surface but make authorization route-aware. Bind a tenant-scoped role to the exact target tenant and require persisted session tenant ownership/equality; allow a global `platformAdmin` branch to select a tenant only with current operator authorization, target-tenant generation, and `privileged_control`. Reject ambiguous/missing target authority, tenant/session mismatches, and unavailable owner/session evidence before invoking any resolver. The negative proof must cover scoped cross-tenant synthetic and persisted-session reads and the global branch without privileged control. diff --git a/design/project-management/implementation-tracking/player-access-and-session.md b/design/project-management/implementation-tracking/player-access-and-session.md index 7225438ac3..d758ce8d00 100644 --- a/design/project-management/implementation-tracking/player-access-and-session.md +++ b/design/project-management/implementation-tracking/player-access-and-session.md @@ -6,7 +6,9 @@ This is a non-normative implementation tracker for player access and session. Ca ## Current Status -The storage-only UUID prerequisite now persists Account-owned immutable UUID identity with provenance at Account, and adds nullable Account UUID evidence to the Game Session command ledger while preserving retained numeric Account IDs. It does not activate UUID authentication outputs, JWTs, session context, `PLAY`, Entity Management, or any producer/consumer carrier. The focused PostgreSQL migration and repository cases are present but were skipped locally because Docker is disabled; `AA-1.1` and `AA-2.1` remain `partial` / `drift-found`, with no runtime-proof upgrade. See [Account Runtime and Data](../../architecture/microservices/account-service/runtime-and-data.md), [Game Session Runtime and Data](../../architecture/microservices/game-session-service/runtime-and-data.md), and [ADR 0020](../../architecture/decisions/adr-0020-scoped-domain-and-operational-identifiers.md). +The storage-only UUID prerequisite now persists Account-owned immutable UUID identity with provenance at Account, and adds nullable Account UUID evidence to the Game Session command ledger while preserving retained numeric Account IDs. Internal carrier types are prepared separately as recorded below, but no producer or consumer supplies or consumes canonical Account UUID values; UUID authentication outputs, JWTs, `PLAY`, and Entity Management remain unactivated. The focused PostgreSQL migration and repository cases are present but were skipped locally because Docker is disabled; `AA-1.1` and `AA-2.1` remain `partial` / `drift-found`, with no runtime-proof upgrade. See [Account Runtime and Data](../../architecture/microservices/account-service/runtime-and-data.md), [Game Session Runtime and Data](../../architecture/microservices/game-session-service/runtime-and-data.md), and [ADR 0020](../../architecture/decisions/adr-0020-scoped-domain-and-operational-identifiers.md). + +Internal Account-carrier typing is prepared in Game Session, while current producers, JWT claims/parsers, and numeric-only collaborators remain unchanged. This does not activate canonical Account UUID authentication or Entity roster/entry behavior and does not backfill historical command UUIDs; canonical identity/namespace targets remain [ADR 0020](../../architecture/decisions/adr-0020-scoped-domain-and-operational-identifiers.md), [ADR 0122](../../architecture/decisions/adr-0122-stable-playable-state-namespaces-for-runtime-replacement.md), and [ADR 0140](../../architecture/decisions/adr-0140-realm-authored-controllable-actor-entry.md). Focused unit proof covers fail-closed first-party retained-context lookup, unreadable presence lookup without index pruning, and bounded pre-mutation rejection of unreadable or wrong-type presence values for removal, AFK/activity updates, and registration. `RedisSessionContextService` mutation reads still expose raw `SerializationException`; mocked tests show unreadable session-alias reads abort before writes/deletes, but mixed-binary behavior, same-session-ID reauthentication/recovery, live Redis/runtime, and fresh-image proof remain unproved. #2898 is not fixed by this preparation. Implemented seams currently span Account, Common Security, TCP Proxy, Gateway, Game Session, and the gameplay runtime services, including account-first tenantless bootstrap, global-only registration, the Account-local explicit public-production JOIN writer and durable audit outbox/producer retry path, tenant-bound discovery/admission, shared Telnet/WebSocket text handling, and bounded Gateway-bridge continuity. Logging & Admin receipt persistence/readback is separate #2848 work and is not included in this Account core. The Account `POST /auth/bootstrap/join` controller/operation exists locally, while the current Gateway guard still blocks external exposure; Game Session text JOIN dispatch remains with #2898 and direct text-client end-to-end proof is unclaimed. Current `PLAY` and connect-token issuance remain partial; Account-owned membership and realm-grant authorities remain separately modeled and read. JOIN's durable `PENDING`/unknown-database-outcome recovery seam remains unresolved under the Overseer decision and is owned by #2848; PostgreSQL runtime proof is not claimed. The membership-authority-generation reread, namespace-aware binding enforcement, resume-window enforcement, exactly-one-prompt proof, and first-party post-logout replay suppression remain incomplete. Generic paths distinguish fresh entry, resume, takeover, and logout; current per-instance binding remains drift against the namespace-aware takeover contract. The current TCP Proxy keeps bounded ordered input in connection-local memory while an edge bridge is rebindable; that buffer is delivered only on the same retained connection and is never durable replay of input, bytes, or frames. Account lifecycle, Stripe hosting-billing follow-through, entitlement enforcement, safety restriction/appeal workflows, generic prompt login, and full control-plane revocation/logout remain partial. Focused automated proofs cover principal implemented paths; manual end-to-end QA and broader continuity/validation follow-ups remain. Canonical target behavior is linked below rather than restated in this tracker. @@ -36,7 +38,7 @@ These links add decision provenance only; they do not upgrade player-access or s | `AA-1.3` Authentication, recovery, security policy, and account data rights | `partial` | `drift-found` | [Authentication and authorization](../../architecture/system-architecture-authentication.md); [Security](../../architecture/system-architecture-security.md); [Account runtime and data](../../architecture/microservices/account-service/runtime-and-data.md); [Moderation Policies](../../architecture/microservices/logging-admin-service/moderation-policies.md); [Session behavior](../../architecture/system-architecture-session-behavior.md); [ADR 0034](../../architecture/decisions/adr-0034-layered-abuse-controls-without-attacker-triggered-account-locks.md); [ADR 0035](../../architecture/decisions/adr-0035-single-record-issued-token-registry.md); [ADR 0141](../../architecture/decisions/adr-0141-fixed-safety-restriction-categories-and-independent-lifecycles.md); [ADR 0142](../../architecture/decisions/adr-0142-bounded-moderation-appeal-cases.md) | [AuthController.java](../../../services/account-service/src/main/java/net/firedevops/firemud/accountservice/controller/AuthController.java); [AccountController.java](../../../services/account-service/src/main/java/net/firedevops/firemud/accountservice/controller/AccountController.java); [AccountServiceImpl.java](../../../services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/impl/AccountServiceImpl.java); [SessionServiceImpl.java](../../../services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/session/SessionServiceImpl.java); [JwksController.java](../../../services/account-service/src/main/java/net/firedevops/firemud/accountservice/controller/JwksController.java); [application-prod.yml](../../../services/account-service/src/main/resources/application-prod.yml) | [AuthControllerTest.java](../../../services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/controller/AuthControllerTest.java); [AccountServiceImplTest.java](../../../services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/service/impl/AccountServiceImplTest.java); [JwksControllerTest.java](../../../services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/controller/JwksControllerTest.java); [AuthTokenInterceptorTest.java](../../../services/common-security/src/test/java/unit/net/firedevops/firemud/common/security/AuthTokenInterceptorTest.java) | [Shared Runtime](./shared-runtime-contracts-and-persistence.md); [Platform Operations](./platform-operations-and-delivery.md) | Public password-reset, username-recovery, and email-verification initiation use normalized email selectors and return the same neutral HTTP success for known and unknown addresses, including when known-account post-commit SMTP errors are caught and logged; unknown addresses create no token or delivery attempt. However, SMTP delivery remains synchronous after commit and is a timing oracle; durable asynchronous delivery is absent, and focused service tests prove exception containment only, not timing resistance or durable delivery. Public verification accepts no numeric account selector. The login-factor `PUT` now fails closed with `501 NOT_IMPLEMENTED` because Account has no recent ordinary reauthentication evidence mechanism; implementing that Account-owned proof and enabling the mutation remain open under ADR 0045. Separate `account_security_lock` and `platform_access_ban` lifecycles, monotonic revisions/generation effects, recovery isolation, complete bounded moderation appeal handoff, `/auth/logout` and `/auth/logout-all` revocation authority, TOTP, trusted source context, Account-owned graduated login throttles, and fail-closed limiter-outage behavior remain absent. Current token issuance still writes scope-duplicated account/tenant keys and downstream validators do not enforce the one-record issued-token registry from ADR 0035. `AUTH_ACCOUNT_LOCKED` remains reserved, while the current Game Session command limiter performs a Redis operation per command contrary to ADR 0034. Current `DeleteAccount` also deletes payment/subscription rows after its precondition, contrary to retention design. Recovery token consumption and reset-driven revocation remain incomplete; export and JWKS foundations are live. | | `AA-1.4` Commerce, subscriptions, purchases, donations, and platform fees | `partial` | `audited` | [Subscription management](../../architecture/microservices/account-service/subscription-management.md); [Stripe integration](../../architecture/microservices/account-service/stripe-integration.md); [Account runtime/data](../../architecture/microservices/account-service/runtime-and-data.md); [ADR 0143](../../architecture/decisions/adr-0143-stripe-v1-hosting-billing-and-deferred-creator-monetization.md) | [PaymentServiceImpl.java](../../../services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/impl/PaymentServiceImpl.java); [PurchaseWorkflowServiceImpl.java](../../../services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/impl/PurchaseWorkflowServiceImpl.java); [PaymentTransaction.java](../../../services/account-service/src/main/java/net/firedevops/firemud/accountservice/entity/PaymentTransaction.java); [Subscription.java](../../../services/account-service/src/main/java/net/firedevops/firemud/accountservice/entity/Subscription.java); [payment_service.proto](../../../protos/account/v1/payment_service.proto); [V2__payment_tables.sql](../../../services/account-service/src/main/resources/db/migration/V2__payment_tables.sql); [application.yml](../../../services/account-service/src/main/resources/application.yml) | [PaymentServiceImplTest.java](../../../services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/service/impl/PaymentServiceImplTest.java); [PaymentGrpcServiceTest.java](../../../services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/service/impl/PaymentGrpcServiceTest.java); [PurchaseWorkflowServiceImplTest.java](../../../services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/service/impl/PurchaseWorkflowServiceImplTest.java) | [Shared Runtime](./shared-runtime-contracts-and-persistence.md) | Incomplete subscription creation now fails closed before mutation instead of persisting a caller-selected locally active entitlement row. The target caller-bound billing-owner, stable request/digest, instrument, outbox, provider lifecycle/reconciliation, billing-safe owner transfer/deletion guards, and complete subscription-to-entitlement follow-through remain absent. Before first subscription creation can be enabled, Account must define the authoritative initial billing-owner source and consent/assignment workflow with a version/generation fence; no such source is selected, and caller-supplied account ID, tenant role, Creator Party, or payment-instrument ownership must not be inferred as that authority. The generic `CreatePaymentIntent`, `CreateDonation`, and `RefundPayment` RPCs fail closed with `FAILED_PRECONDITION` before `PaymentService` or provider invocation; the generic service/provider substrate remains unsupported. Creator/player purchases, donations, fees/shares, payouts, and settlement are deferred and not supported by current code. | | `AA-1.5` Entitlements, quotas, and hosting eligibility | `partial` | `drift-found` | [Subscription management](../../architecture/microservices/account-service/subscription-management.md); [Multi-tenancy](../../architecture/system-architecture-multi-tenancy.md); [Versioning and runtime](../../architecture/system-architecture-versioning-runtime.md); [ADR 0028](../../architecture/decisions/adr-0028-differentiated-entitlement-freshness.md) | [AccountServiceImpl.java](../../../services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/impl/AccountServiceImpl.java); [RuntimeEntitlementsDto.java](../../../services/account-service/src/main/java/net/firedevops/firemud/accountservice/dto/RuntimeEntitlementsDto.java); [Subscription.java](../../../services/account-service/src/main/java/net/firedevops/firemud/accountservice/entity/Subscription.java); [account_service.proto](../../../protos/account/v1/account_service.proto); [application.yml](../../../services/account-service/src/main/resources/application.yml) | [AccountServiceImplTest.java](../../../services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/service/impl/AccountServiceImplTest.java); [AccountGrpcServiceTest.java](../../../services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/service/impl/AccountGrpcServiceTest.java); [PublicBootstrapRoutesProdProfileTest.java](../../../services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/controller/PublicBootstrapRoutesProdProfileTest.java) | [Realm Routing](./realm-routing-and-playable-state.md); [Game Authoring](./game-authoring-publishing-and-activation.md) | The producer returns retryable `ENTITLEMENT_UNAVAILABLE` for zero or multiple tenant subscription rows and projects status only from exactly one explicit row; gRPC carries the unavailable outcome in its error field and HTTP bootstrap routes map it to 503. Focused Account proofs cover zero rows, conflicting active/canceled rows, gRPC classification, and connect-token retry after recovery without caching an unavailable receipt. Explicit free/trial row creation and authoritative current-row selection/constraint/history remain absent. The runtime response still lacks committed status and the full explicit entitlement/freshness evidence; its row-ID-derived version/sequence and newly stamped evaluation time, quotas, real sequencing/source freshness, caching/events, strict new-commitment enforcement, five-minute continuity, and instance lifecycle enforcement remain open. The target handoff between fresh connect-token reissuance and eligible exact-binding entitlement-only reconnect continuity is unresolved: token expiry can block that continuity before Account's resume lease, and no fallback reissuance path is authorized pending owner decision. Current `past_due` handling remains gameplay-available and public-join-eligible only when the sole explicit row is `past_due`. | -| `AA-2.1` Gameplay login, character selection, and session binding | `partial` | `drift-found` | [Authentication and authorization](../../architecture/system-architecture-authentication.md); [Game Session protocols](../../architecture/microservices/game-session-service/protocols.md); [Game Session runtime and data](../../architecture/microservices/game-session-service/runtime-and-data.md); [Session behavior](../../architecture/system-architecture-session-behavior.md); [ADR 0025](../../architecture/decisions/adr-0025-explicit-open-enrollment-membership.md); [ADR 0140](../../architecture/decisions/adr-0140-realm-authored-controllable-actor-entry.md); [ADR 0020](../../architecture/decisions/adr-0020-scoped-domain-and-operational-identifiers.md) | [LoginCommandHandler.java](../../../services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/command/text/LoginCommandHandler.java); [PlayCommandHandler.java](../../../services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/command/text/PlayCommandHandler.java); [SessionContext.java](../../../services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/service/SessionContext.java); [GameplayCommandRepository.java](../../../services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/repository/GameplayCommandRepository.java); [V11__gameplay_command_account_uuid.sql](../../../services/game-session-service/src/main/resources/db/migration/V11__gameplay_command_account_uuid.sql); [account_service.proto](../../../protos/account/v1/account_service.proto); [game_session_service.proto](../../../protos/game-session/v1/game_session_service.proto) | [LoginCommandHandlerTest.java](../../../services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/command/text/LoginCommandHandlerTest.java); [PlayCommandHandlerTest.java](../../../services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/command/text/PlayCommandHandlerTest.java); [GameSessionLoginIntegrationTest.java](../../../services/game-session-service/src/test/java/integration/net/firedevops/firemud/gamesession/GameSessionLoginIntegrationTest.java); [GameplayCommandRepositoryIntegrationTest.java](../../../services/game-session-service/src/test/java/integration/net/firedevops/firemud/gamesession/repository/GameplayCommandRepositoryIntegrationTest.java); [GameplayCommandAccountUuidMigrationIntegrationTest.java](../../../services/game-session-service/src/test/java/integration/net/firedevops/firemud/gamesession/repository/GameplayCommandAccountUuidMigrationIntegrationTest.java) | [Realm Routing](./realm-routing-and-playable-state.md); [Player Experience](./player-experience-commands-and-communication.md) | Basic global login, account-first bootstrap, and `PLAY` exist with focused proof for current public-production admission behavior. V11 adds nullable Account UUID evidence to the Game Session command ledger and repository round-trip mapping while preserving retained numeric Account IDs; focused repository and migration PostgreSQL cases are present but skipped locally because Docker is disabled. No producer or session carrier supplies or consumes this field, and UUID storage does not activate UUID authentication, JWTs, session context, or `PLAY`. Credential and email-OTP `LOGIN` do not require tenant selection or current membership; the transport bootstrap tenant remains local routing context rather than Account authentication authority. Game Session preserves authenticated player account identity independently of game-instance control-plane owner metadata; LOGIN does not require the player to own the instance. Reauthentication as a different account clears the prior gameplay presence, character, runtime route, playable scope, and connect scope before replacing authenticated context; a same-account/same-tenant relogin may preserve its candidate binding for fresh admission checks, while a tenant switch clears the prior gameplay presence before saving the new context. Text `PLAY` performs Account membership/entitlement evaluation before strict persisted actor selection; focused service proof covers the Game Session-to-Entity peer allowlist. Connect-token issuance requires existing membership but does not yet validate the applicable non-public grant. Account's local `JoinPublicProductionMembership` writer is implemented, but Game Session text `JOIN`/`Join & Play` dispatch remains unimplemented under #2898 and external exposure of the Account bootstrap route remains blocked. The strict ADR 0025 commit fence and membership-authority-generation reread at issuance remain incomplete; unknown-outcome recovery and Logging receipt receiver/readback remain #2848 work. Exact-final-head PostgreSQL runtime proof and direct text-client end-to-end proof are unclaimed. Generic prompt-mode login, deployment/mTLS, and fresh-image proof for the focused `PLAY` changes also remain incomplete. | +| `AA-2.1` Gameplay login, character selection, and session binding | `partial` | `drift-found` | [Authentication and authorization](../../architecture/system-architecture-authentication.md); [Game Session protocols](../../architecture/microservices/game-session-service/protocols.md); [Game Session runtime and data](../../architecture/microservices/game-session-service/runtime-and-data.md); [Session behavior](../../architecture/system-architecture-session-behavior.md); [ADR 0025](../../architecture/decisions/adr-0025-explicit-open-enrollment-membership.md); [ADR 0140](../../architecture/decisions/adr-0140-realm-authored-controllable-actor-entry.md); [ADR 0020](../../architecture/decisions/adr-0020-scoped-domain-and-operational-identifiers.md) | [LoginCommandHandler.java](../../../services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/command/text/LoginCommandHandler.java); [PlayCommandHandler.java](../../../services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/command/text/PlayCommandHandler.java); [SessionContext.java](../../../services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/service/SessionContext.java); [FirstPartyConnectContext.java](../../../services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/service/FirstPartyConnectContext.java); [GameplayPresence.java](../../../services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/service/GameplayPresence.java); [AccountPresenceSnapshot.java](../../../services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/service/AccountPresenceSnapshot.java); [AccountRecentPresenceState.java](../../../services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/service/AccountRecentPresenceState.java); [RedisSessionContextService.java](../../../services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/service/impl/RedisSessionContextService.java); [RedisFirstPartyConnectContextRegistry.java](../../../services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/service/impl/RedisFirstPartyConnectContextRegistry.java); [GameplayCommandRepository.java](../../../services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/repository/GameplayCommandRepository.java); [V11__gameplay_command_account_uuid.sql](../../../services/game-session-service/src/main/resources/db/migration/V11__gameplay_command_account_uuid.sql); [account_service.proto](../../../protos/account/v1/account_service.proto); [game_session_service.proto](../../../protos/game-session/v1/game_session_service.proto) | [LoginCommandHandlerTest.java](../../../services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/command/text/LoginCommandHandlerTest.java); [PlayCommandHandlerTest.java](../../../services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/command/text/PlayCommandHandlerTest.java); [RedisSessionContextServiceTest.java](../../../services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/service/impl/RedisSessionContextServiceTest.java); [RedisFirstPartyConnectContextRegistryTest.java](../../../services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/service/impl/RedisFirstPartyConnectContextRegistryTest.java); [GameSessionLoginIntegrationTest.java](../../../services/game-session-service/src/test/java/integration/net/firedevops/firemud/gamesession/GameSessionLoginIntegrationTest.java); [GameplayCommandRepositoryIntegrationTest.java](../../../services/game-session-service/src/test/java/integration/net/firedevops/firemud/gamesession/repository/GameplayCommandRepositoryIntegrationTest.java); [GameplayCommandAccountUuidMigrationIntegrationTest.java](../../../services/game-session-service/src/test/java/integration/net/firedevops/firemud/gamesession/repository/GameplayCommandAccountUuidMigrationIntegrationTest.java) | [Realm Routing](./realm-routing-and-playable-state.md); [Player Experience](./player-experience-commands-and-communication.md) | Basic global login, account-first bootstrap, and `PLAY` exist with focused proof for current public-production admission behavior. V11 adds nullable Account UUID evidence to the Game Session command ledger and repository round-trip mapping while preserving retained numeric Account IDs; focused repository and migration PostgreSQL cases are present but skipped locally because Docker is disabled. Internal Account-carrier typing is prepared across session, first-party, and presence records, while current numeric Account/JWT producers and numeric-only collaborators remain unchanged. Canonical Account UUID issuance and Entity roster/`PLAY` activation are absent; historical command `account_uuid` remains null without backfill, preserving numeric command evidence. Focused tests cover fail-closed first-party retained-context lookup, unreadable presence lookup without pruning, and bounded pre-mutation rejection of unreadable/wrong-type presence values for removal, AFK/activity updates, and registration. `RedisSessionContextService` mutation reads still expose raw `SerializationException`; mocked tests cover an unreadable session alias aborting before writes/deletes. Mixed-binary behavior, same-session-ID reauthentication/recovery, live Redis/runtime, and fresh-image proof remain unproved. Credential and email-OTP `LOGIN` do not require tenant selection or current membership; the transport bootstrap tenant remains local routing context rather than Account authentication authority. Game Session preserves authenticated player account identity independently of game-instance control-plane owner metadata; LOGIN does not require the player to own the instance. Reauthentication as a different account clears the prior gameplay presence, character, runtime route, playable scope, and connect scope before replacing authenticated context; a same-account/same-tenant relogin may preserve its candidate binding for fresh admission checks, while a tenant switch clears the prior gameplay presence before saving the new context. Text `PLAY` performs Account membership/entitlement evaluation before strict persisted actor selection; focused service proof covers the Game Session-to-Entity peer allowlist. Connect-token issuance requires existing membership but does not yet validate the applicable non-public grant. Account's local `JoinPublicProductionMembership` writer is implemented, but Game Session text `JOIN`/`Join & Play` dispatch remains unimplemented under #2898 and external exposure of the Account bootstrap route remains blocked. The strict ADR 0025 commit fence and membership-authority-generation reread at issuance remain incomplete; unknown-outcome recovery and Logging receipt receiver/readback remain #2848 work. Exact-final-head PostgreSQL runtime proof and direct text-client end-to-end proof are unclaimed. Generic prompt-mode login, deployment/mTLS, and fresh-image proof for the focused `PLAY` changes also remain incomplete. | | `AA-2.2` Reconnect, resume eligibility, and cross-device continuity | `partial` | `drift-found` | [Reconnection](../../architecture/system-architecture-reconnection.md); [Session behavior](../../architecture/system-architecture-session-behavior.md); [Redis architecture](../../architecture/system-architecture-redis.md); [ADR 0019](../../architecture/decisions/adr-0019-separate-active-session-resume-and-transcript-lifetimes.md); [ADR 0132](../../architecture/decisions/adr-0132-namespace-scoped-single-character-controller.md); [ADR 0133](../../architecture/decisions/adr-0133-fresh-edge-reconnect-without-client-input-replay.md); [ADR 0134](../../architecture/decisions/adr-0134-bounded-durable-semantic-reconnect-context.md) | [SessionAuthenticationService.java](../../../services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/service/SessionAuthenticationService.java); [RedisSessionContextService.java](../../../services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/service/impl/RedisSessionContextService.java); [DurableScreenBufferService.java](../../../services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/service/DurableScreenBufferService.java); [GameplayWebSocketBridgeHandler.java](../../../services/spring-cloud-gateway/src/main/java/net/firedevops/firemud/springcloudgateway/websocket/GameplayWebSocketBridgeHandler.java); [FirstPartyConnectContextService.java](../../../services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/service/FirstPartyConnectContextService.java); [EffectiveReconnectionSettingsResolver.java](../../../services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/config/EffectiveReconnectionSettingsResolver.java) | [SessionResumptionFlowTest.java](../../../services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/command/text/SessionResumptionFlowTest.java); [LookWebSocketCrossServiceTest.java](../../../services/game-session-service/src/test/java/crossservice/net/firedevops/firemud/gamesession/LookWebSocketCrossServiceTest.java); [GameSessionWebSocketHandlerIntegrationTest.java](../../../services/game-session-service/src/test/java/integration/net/firedevops/firemud/gamesession/websocket/GameSessionWebSocketHandlerIntegrationTest.java); [Telnet cross-service test](../../../services/tcp-proxy-service/src/test/java/crossservice/net/firedevops/firemud/tcpproxy/TelnetGatewayGameSessionAccountCrossServiceIntegrationTest.java) | [Player Experience](./player-experience-commands-and-communication.md); [Shared Runtime](./shared-runtime-contracts-and-persistence.md); [Platform Operations](./platform-operations-and-delivery.md) | Generic resume, bounded semantic context, and edge rebind exist, but the effective disconnected-resume window is resolved without `PLAY` enforcement; namespace-aware binding/transfer, complete authenticated real-service replacement, lifecycle/presence/stalled-input outcomes, first-party post-logout replay suppression, and proof of fresh-edge `LOOK`/prompt behavior are not complete or proved. First-party `LOGIN` plus `PLAY` can replay retained context after deliberate logout. Fresh edge reconnect must not replay client input/bytes/frames and must end with fresh `LOOK` plus exactly one reconnect prompt when both effective reconnect-prompt settings are enabled, or zero reconnect prompts when either is disabled. Full token refresh, membership-version and membership-authority-generation persistence, revocation, and non-edge restart continuity remain. | | `AA-2.3` Takeover, logout, idle expiry, and revocation | `partial` | `drift-found` | [Session behavior](../../architecture/system-architecture-session-behavior.md); [Reconnection](../../architecture/system-architecture-reconnection.md); [ADR 0132](../../architecture/decisions/adr-0132-namespace-scoped-single-character-controller.md) | [PlayCommandHandler.java](../../../services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/command/text/PlayCommandHandler.java); [LogoutCommandHandler.java](../../../services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/command/text/LogoutCommandHandler.java); [RedisSessionContextService.java](../../../services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/service/impl/RedisSessionContextService.java); [TelnetServerHandler.java](../../../services/tcp-proxy-service/src/main/java/net/firedevops/firemud/tcpproxy/telnet/TelnetServerHandler.java); [application.yml](../../../services/game-session-service/src/main/resources/application.yml) | [SessionResumptionFlowTest.java](../../../services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/command/text/SessionResumptionFlowTest.java); [LogoutCommandHandlerTest.java](../../../services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/command/text/LogoutCommandHandlerTest.java); [LookWebSocketCrossServiceTest.java](../../../services/game-session-service/src/test/java/crossservice/net/firedevops/firemud/gamesession/LookWebSocketCrossServiceTest.java) | [Player Experience](./player-experience-commands-and-communication.md); [World Runtime](./world-runtime-and-movement.md); [Gameplay Rules](./gameplay-rules-entities-and-effects.md); [Shared Runtime](./shared-runtime-contracts-and-persistence.md) | Gameplay takeover/LOGOUT and transport idle-close handling exist; target takeover requires namespace-scoped atomic monotonic `bindingGeneration`, old-input fencing, and preservation of already-admitted work as defined by [ADR 0132](../../architecture/decisions/adr-0132-namespace-scoped-single-character-controller.md), while Account control-plane logout/authority-generation workflows, full idle/session expiry convergence, and first-party post-logout replay cleanup are absent. | diff --git a/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/client/EntityManagementClient.java b/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/client/EntityManagementClient.java index 17dcdc8914..820bcad714 100644 --- a/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/client/EntityManagementClient.java +++ b/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/client/EntityManagementClient.java @@ -223,7 +223,7 @@ private String sessionAttestation( return gameplaySessionAttestationService.issueGameplaySessionAttestation( Long.toString(context.tenantId()), Long.toString(context.sessionId()), - Long.toString(context.accountId()), + context.accountId(), Long.toString(context.characterId()), gameInstanceId, canonicalRoomId, diff --git a/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/client/GameLogicClient.java b/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/client/GameLogicClient.java index 525f08b1ec..e192fad1db 100644 --- a/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/client/GameLogicClient.java +++ b/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/client/GameLogicClient.java @@ -160,14 +160,14 @@ public SendCommunicationResponse sendCommunication( String tenantId = Long.toString(context.tenantId()); String sessionId = Long.toString(context.sessionId()); String characterId = Long.toString(context.characterId()); - String accountId = Long.toString(context.accountId()); + String accountId = context.accountId(); String gameInstanceId = Long.toString(context.gameInstanceId()); SendCommunicationRequest request = SendCommunicationRequest.newBuilder() .setTenantId(tenantId) .setSessionId(sessionId) .setCharacterId(characterId) - .setAccountId(accountId) + .setAccountId(accountId == null ? "" : accountId) .setRoomInstance( RoomInstanceRef.newBuilder() .setTenantId(tenantId) @@ -346,7 +346,7 @@ public PickupItemFromRoomResponse pickupVisibleRoomItem( SessionContext context, String itemReference, int quantity, String effectId) { String tenantId = Long.toString(context.tenantId()); String sessionId = Long.toString(context.sessionId()); - String accountId = Long.toString(context.accountId()); + String accountId = context.accountId(); String characterId = Long.toString(context.characterId()); String gameInstanceId = Long.toString(context.gameInstanceId()); String roomInstanceId = @@ -355,7 +355,7 @@ public PickupItemFromRoomResponse pickupVisibleRoomItem( PickupVisibleRoomItemRequest.newBuilder() .setTenantId(tenantId) .setSessionId(sessionId) - .setAccountId(accountId) + .setAccountId(accountId == null ? "" : accountId) .setCharacterId(characterId) .setGameInstanceId(gameInstanceId) .setRoomInstanceId(roomInstanceId) @@ -449,7 +449,7 @@ public DropItemToRoomResponse dropCarriedItem( SessionContext context, String itemReference, int quantity, String effectId) { String tenantId = Long.toString(context.tenantId()); String sessionId = Long.toString(context.sessionId()); - String accountId = Long.toString(context.accountId()); + String accountId = context.accountId(); String characterId = Long.toString(context.characterId()); String gameInstanceId = Long.toString(context.gameInstanceId()); String roomInstanceId = @@ -458,7 +458,7 @@ public DropItemToRoomResponse dropCarriedItem( DropCarriedItemRequest.newBuilder() .setTenantId(tenantId) .setSessionId(sessionId) - .setAccountId(accountId) + .setAccountId(accountId == null ? "" : accountId) .setCharacterId(characterId) .setGameInstanceId(gameInstanceId) .setRoomInstanceId(roomInstanceId) @@ -720,7 +720,7 @@ private String sessionAttestation(SessionContext context, String roomId) { return gameplaySessionAttestationService.issueGameplaySessionAttestation( Long.toString(context.tenantId()), Long.toString(context.sessionId()), - Long.toString(context.accountId()), + context.accountId(), Long.toString(context.characterId()), Long.toString(context.gameInstanceId()), canonicalRoomId, diff --git a/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/command/text/FriendsCommandHandler.java b/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/command/text/FriendsCommandHandler.java index 1efb1f3de5..60801b312c 100644 --- a/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/command/text/FriendsCommandHandler.java +++ b/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/command/text/FriendsCommandHandler.java @@ -67,6 +67,15 @@ public TextCommandInterpretationResult handle(TextCommand command, SessionContex if (action.kind() == FriendActionKind.INVALID) { return invalidUsage(action.invalidUsage()); } + TextCommandInterpretationResult usageFailure = validateUsage(action); + if (usageFailure != null) { + return usageFailure; + } + try { + numericAccountId(context); + } catch (IllegalArgumentException ex) { + return accountIdUnavailable(action); + } if (action.kind() == FriendActionKind.LIST) { return handleList(context, action.listFilter(), rawCommandText); } @@ -105,15 +114,79 @@ public TextCommandInterpretationResult handle(TextCommand command, SessionContex }; } + private TextCommandInterpretationResult validateUsage(FriendAction action) { + if (action.kind() == FriendActionKind.DETAIL && !StringUtils.hasText(action.targetToken())) { + return invalidUsage("FRIENDS SHOW "); + } + if ((action.kind() == FriendActionKind.ADD || action.kind() == FriendActionKind.REMOVE) + && !StringUtils.hasText(action.targetToken())) { + return invalidUsage("FRIENDS " + action.keyword() + " "); + } + if (action.kind() == FriendActionKind.REMOVE + && isOrdinalToken(action.targetToken()) + && parseOrdinal(action.targetToken()) <= 0) { + return invalidUsage("FRIENDS REMOVE "); + } + if (action.kind() == FriendActionKind.DETAIL + && isOrdinalToken(action.targetToken()) + && parseOrdinal(action.targetToken()) <= 0) { + return invalidUsage("FRIENDS SHOW "); + } + if (action.kind() == FriendActionKind.VISIBILITY && StringUtils.hasText(action.targetToken())) { + net.firedevops.firemud.socialgroups.v1.FriendPresenceVisibilityPolicy visibilityPolicy = + parseVisibilityPolicy(action.targetToken()); + if (visibilityPolicy == null) { + return invalidUsage("FRIENDS VISIBILITY "); + } + if (visibilityPolicy + == net.firedevops.firemud.socialgroups.v1.FriendPresenceVisibilityPolicy + .FRIEND_PRESENCE_VISIBILITY_POLICY_HIDDEN_STAFF) { + return friendTargetError( + "INVALID_ARGUMENT", "HIDDEN_STAFF is reserved and cannot be set from gameplay"); + } + } + return null; + } + + private TextCommandInterpretationResult accountIdUnavailable(FriendAction action) { + String code = + switch (action.kind()) { + case LIST -> "FRIEND_PRESENCE_UNAVAILABLE"; + case ADD -> "FRIEND_ADD_UNAVAILABLE"; + case REMOVE -> "FRIEND_REMOVE_UNAVAILABLE"; + case DETAIL -> "FRIEND_DETAIL_UNAVAILABLE"; + case SUMMARY -> "FRIEND_SUMMARY_UNAVAILABLE"; + case VISIBILITY -> + StringUtils.hasText(action.targetToken()) + ? "FRIEND_VISIBILITY_UPDATE_UNAVAILABLE" + : "FRIEND_VISIBILITY_UNAVAILABLE"; + case INVALID -> "INVALID_ARGUMENT"; + }; + String message = + switch (code) { + case "FRIEND_PRESENCE_UNAVAILABLE" -> "Friend presence unavailable"; + case "FRIEND_ADD_UNAVAILABLE" -> "Friend add unavailable"; + case "FRIEND_REMOVE_UNAVAILABLE" -> "Friend removal unavailable"; + case "FRIEND_DETAIL_UNAVAILABLE" -> "Friend detail unavailable"; + case "FRIEND_SUMMARY_UNAVAILABLE" -> "Friend roster summary unavailable"; + case "FRIEND_VISIBILITY_UNAVAILABLE" -> "Friend presence visibility unavailable"; + case "FRIEND_VISIBILITY_UPDATE_UNAVAILABLE" -> + "Friend presence visibility update unavailable"; + default -> "Friend command unavailable"; + }; + return new TextCommandInterpretationResult( + CommandEnqueueResult.failure(code, message), List.of(PlayerOutput.error(code, message))); + } + private TextCommandInterpretationResult handleList( SessionContext context, FriendListFilter filter, String rawCommandText) { ListFriendsResponse response = filter == FriendListFilter.ALL - ? socialGroupsClient.listFriends(context.tenantId(), context.accountId()) + ? socialGroupsClient.listFriends(context.tenantId(), numericAccountId(context)) : socialGroupsClient.listFriends( - context.tenantId(), context.accountId(), mapRosterFilter(filter)); + context.tenantId(), numericAccountId(context), mapRosterFilter(filter)); if (response == null && filter != FriendListFilter.ALL) { - response = socialGroupsClient.listFriends(context.tenantId(), context.accountId()); + response = socialGroupsClient.listFriends(context.tenantId(), numericAccountId(context)); } if (response.hasError()) { String message = @@ -137,13 +210,13 @@ private TextCommandInterpretationResult handleList( private TextCommandInterpretationResult handleAdd( SessionContext context, ResolvedFriendTarget target, String rawCommandText) { - if (target.friendAccountId() == context.accountId()) { + if (target.friendAccountId() == numericAccountId(context)) { return friendTargetError( "FRIEND_SELF_LINK_FORBIDDEN", "Cannot add or remove your own account as a friend"); } AddFriendResponse response = socialGroupsClient.addFriend( - context.tenantId(), context.accountId(), target.friendAccountId()); + context.tenantId(), numericAccountId(context), target.friendAccountId()); if (response.hasError() || !response.getSuccess()) { String message = response.hasError() && !response.getError().getMessage().isBlank() @@ -161,13 +234,13 @@ private TextCommandInterpretationResult handleAdd( private TextCommandInterpretationResult handleRemove( SessionContext context, ResolvedFriendTarget target, String rawCommandText) { - if (target.friendAccountId() == context.accountId()) { + if (target.friendAccountId() == numericAccountId(context)) { return friendTargetError( "FRIEND_SELF_LINK_FORBIDDEN", "Cannot add or remove your own account as a friend"); } RemoveFriendResponse response = socialGroupsClient.removeFriend( - context.tenantId(), context.accountId(), target.friendAccountId()); + context.tenantId(), numericAccountId(context), target.friendAccountId()); if (response.hasError() || !response.getSuccess()) { String message = response.hasError() && !response.getError().getMessage().isBlank() @@ -187,7 +260,7 @@ private TextCommandInterpretationResult handleDetail( SessionContext context, ResolvedFriendTarget target, String rawCommandText) { GetFriendResponse response = socialGroupsClient.getFriend( - context.tenantId(), context.accountId(), target.friendAccountId()); + context.tenantId(), numericAccountId(context), target.friendAccountId()); if (response.hasError()) { String code = "NOT_FOUND".equalsIgnoreCase(response.getError().getCode()) @@ -221,7 +294,8 @@ private TextCommandInterpretationResult handleDetailByOrdinal( return invalidUsage("FRIENDS SHOW "); } GetFriendByOrdinalResponse response = - socialGroupsClient.getFriendByOrdinal(context.tenantId(), context.accountId(), ordinal); + socialGroupsClient.getFriendByOrdinal( + context.tenantId(), numericAccountId(context), ordinal); if (response.hasError()) { String code = "NOT_FOUND".equalsIgnoreCase(response.getError().getCode()) @@ -251,7 +325,7 @@ private TextCommandInterpretationResult handleDetailByOrdinal( private TextCommandInterpretationResult handleSummary( SessionContext context, String rawCommandText) { GetFriendRosterSummaryResponse response = - socialGroupsClient.getFriendRosterSummary(context.tenantId(), context.accountId()); + socialGroupsClient.getFriendRosterSummary(context.tenantId(), numericAccountId(context)); if (response.hasError()) { String message = response.getError().getMessage().isBlank() @@ -284,7 +358,7 @@ private TextCommandInterpretationResult handleSummary( private TextCommandInterpretationResult handleVisibilityView( SessionContext context, String rawCommandText) { GetFriendPresencePolicyResponse response = - socialGroupsClient.getFriendPresencePolicy(context.tenantId(), context.accountId()); + socialGroupsClient.getFriendPresencePolicy(context.tenantId(), numericAccountId(context)); if (response.hasError()) { String code = response.getError().getCode().isBlank() @@ -318,7 +392,7 @@ private TextCommandInterpretationResult handleVisibilityUpdate( } UpdateFriendPresencePolicyResponse response = socialGroupsClient.updateFriendPresencePolicy( - context.tenantId(), context.accountId(), visibilityPolicy); + context.tenantId(), numericAccountId(context), visibilityPolicy); if (response.hasError() || !response.getSuccess()) { String code = response.hasError() && !response.getError().getCode().isBlank() @@ -349,7 +423,8 @@ private TextCommandInterpretationResult handleRemoveByOrdinal( return invalidUsage("FRIENDS REMOVE "); } RemoveFriendByOrdinalResponse response = - socialGroupsClient.removeFriendByOrdinal(context.tenantId(), context.accountId(), ordinal); + socialGroupsClient.removeFriendByOrdinal( + context.tenantId(), numericAccountId(context), ordinal); if (response.hasError() || !response.getSuccess()) { String code = response.hasError() && "NOT_FOUND".equalsIgnoreCase(response.getError().getCode()) @@ -483,6 +558,11 @@ private long requireFriendAccountId(String value) { } } + private long numericAccountId(SessionContext context) { + return PositiveLongParsing.requireOptionalText(context.accountId(), "accountId") + .orElseThrow(() -> new IllegalArgumentException("accountId must be positive")); + } + private Long parseOptionalLong(String value) { return PositiveLongParsing.parseOptionalText(value, "friendLinkId") .optionalValue() diff --git a/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/command/text/LoginCommandHandler.java b/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/command/text/LoginCommandHandler.java index 3aa1ea039a..4f800c6f8d 100644 --- a/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/command/text/LoginCommandHandler.java +++ b/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/command/text/LoginCommandHandler.java @@ -166,7 +166,8 @@ public LoginCommandHandlingResult handle( private void invalidateStaleFirstPartyConnectContext(long sessionId, long accountId) { firstPartyConnectContextRegistry .find(sessionId) - .filter(connectContext -> connectContext.accountId() != accountId) + .filter( + connectContext -> !Objects.equals(connectContext.accountId(), Long.toString(accountId))) .ifPresent(ignored -> firstPartyConnectContextRegistry.unregister(sessionId)); } @@ -231,11 +232,27 @@ private LoginCommandHandlingResult handleVerifiedFirstPartyLogin(String sessionI var verifiedContext = maybeContext.get(); if (existingSession != null - && existingSession.accountId() > 0 - && existingSession.accountId() != verifiedContext.accountId()) { + && existingSession.hasAccountIdentity() + && !Objects.equals(existingSession.accountId(), verifiedContext.accountId())) { firstPartyConnectContextRegistry.unregister(numericSessionId); return failure("CONNECT_CONTEXT_INVALID", "Connect context invalid"); } + long numericAccountId; + try { + numericAccountId = + PositiveLongParsing.requireOptionalText(verifiedContext.accountId(), "accountId") + .orElseThrow(() -> new IllegalArgumentException("accountId must be positive")); + } catch (IllegalArgumentException ex) { + clearFailedFirstPartyLoginSessionState( + numericSessionId, + existingSession, + verifiedContext.tenantId(), + verifiedContext.gameInstanceId(), + verifiedContext.worldSlug(), + verifiedContext.realmSlug(), + verifiedContext.pointerVersion()); + return failure("CONNECT_CONTEXT_INVALID", "Connect context invalid"); + } Optional maybeInstance = gameInstanceRepository.findById(verifiedContext.gameInstanceId()); if (maybeInstance.isEmpty()) { @@ -275,7 +292,7 @@ private LoginCommandHandlingResult handleVerifiedFirstPartyLogin(String sessionI persistSessionContext( numericSessionId, verifiedContext.tenantId(), - verifiedContext.accountId(), + numericAccountId, "first-party:" + verifiedContext.accountId(), null, verifiedContext.gameInstanceId(), @@ -287,7 +304,27 @@ private LoginCommandHandlingResult handleVerifiedFirstPartyLogin(String sessionI PlayerOutput.message( "Logged in as first-party account " + verifiedContext.accountId(), "message.login.first-party-success", - Map.of("accountId", Long.toString(verifiedContext.accountId()))))); + Map.of("accountId", verifiedContext.accountId())))); + } + + private void clearFailedFirstPartyLoginSessionState( + long sessionId, + SessionContext existingSession, + long fallbackTenantId, + long fallbackBootstrapGameInstanceId, + String worldSlug, + String realmSlug, + long pointerVersion) { + if (existingSession != null && existingSession.hasAccountIdentity()) { + return; + } + clearFailedLoginSessionState( + sessionId, + fallbackTenantId, + fallbackBootstrapGameInstanceId, + worldSlug, + realmSlug, + pointerVersion); } private void persistSessionContext( @@ -310,7 +347,9 @@ private void persistSessionContext( projectedExisting != null && projectedExisting.tenantId() == tenantId ? projectedExisting : null; - boolean sameAuthenticatedAccount = existing != null && existing.accountId() == accountId; + String accountIdText = Long.toString(accountId); + boolean sameAuthenticatedAccount = + existing != null && Objects.equals(existing.accountId(), accountIdText); Optional reusableBootstrapShell = sameAuthenticatedAccount ? Optional.empty() @@ -339,7 +378,7 @@ private void persistSessionContext( ? new SessionContext( sessionId, tenantId, - accountId, + accountIdText, loginName, 0L, null, @@ -351,7 +390,7 @@ private void persistSessionContext( : new SessionContext( sessionId, tenantId, - accountId, + accountIdText, loginName, existing.characterId(), existing.characterName(), @@ -368,7 +407,8 @@ private void persistSessionContext( existing.playableStateScope(), existing.connectScopeId(), existing.connectRequestId()); - if (projectedExisting != null && projectedExisting.accountId() != accountId) { + if (projectedExisting != null + && !Objects.equals(projectedExisting.accountId(), accountIdText)) { gameplayPresenceLifecycleService.clearGameplayBinding( projectedExisting, "LOGIN_ACCOUNT_CHANGED"); } else if (projectedExisting != null && projectedExisting.tenantId() != tenantId) { @@ -391,7 +431,7 @@ private Optional reusableBootstrapShell( net.firedevops.firemud.gamesession.service.FirstPartyConnectContext verifiedConnectContext, String verifiedPlayableStateScope) { if (existing == null - || existing.accountId() != 0L + || existing.hasAccountIdentity() || existing.tenantId() != tenantId || existing.bootstrapGameInstanceId() != bootstrapGameInstanceId || existing.hasGameplayBinding() @@ -407,7 +447,7 @@ private Optional reusableBootstrapShell( boolean verifiedIdentityAndTargetMatch = verifiedConnectContext.hasCompleteRoutingScope() - && verifiedConnectContext.accountId() == accountId + && Objects.equals(verifiedConnectContext.accountId(), Long.toString(accountId)) && verifiedConnectContext.tenantId() == tenantId && verifiedConnectContext.gameInstanceId() == bootstrapGameInstanceId && Objects.equals(existing.playableStateScope(), verifiedPlayableStateScope) @@ -435,7 +475,7 @@ private SessionContext authenticatedBootstrapContext( return new SessionContext( sessionId, tenantId, - accountId, + Long.toString(accountId), loginName, 0L, null, @@ -565,7 +605,7 @@ private void clearFailedLoginSessionState( new SessionContext( sessionId, tenantId, - 0L, + null, null, 0L, null, diff --git a/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/command/text/PlayCommandHandler.java b/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/command/text/PlayCommandHandler.java index c182c81d4b..775c145547 100644 --- a/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/command/text/PlayCommandHandler.java +++ b/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/command/text/PlayCommandHandler.java @@ -340,7 +340,9 @@ private Optional validateModerationPolicy( SessionContext context, GameplayWorldCatalog.RealmView selectedRealm, String tenantTag) { var decision = moderationPolicyClient.evaluateGameplayAdmission( - selectedRealm.tenantId(), context.accountId()); + selectedRealm.tenantId(), + PositiveLongParsing.requireOptionalText(context.accountId(), "accountId") + .orElseThrow(() -> new IllegalArgumentException("accountId must be positive"))); if (decision.hasError() && decision.getError().getCode() != null && !decision.getError().getCode().isBlank()) { @@ -460,7 +462,7 @@ private ResolvedCharacter resolveCharacter( ListCharactersByAccountResponse response = entityManagementClient.listCharactersByAccount( Long.toString(selectedRealm.tenantId()), - Long.toString(context.accountId()), + context.accountId(), Long.toString(selectedRealm.gameInstanceId()), playableStateScope); if (response == null || response.hasError()) { @@ -472,7 +474,7 @@ private ResolvedCharacter resolveCharacter( for (Character character : roster) { long characterId = requireResolvedCharacterId(character.getId()); if (!Long.toString(selectedRealm.tenantId()).equals(character.getTenantId()) - || !Long.toString(context.accountId()).equals(character.getAccountId()) + || !context.accountId().equals(character.getAccountId()) || character.getPlayableStateScope() != playableStateScope || !StringUtils.hasText(character.getName()) || !characterIds.add(characterId)) { @@ -617,7 +619,7 @@ private Optional validateRuntimeAdmission( String requestId = context.sessionId() + ":" + UUID.randomUUID(); GetTenantMembershipForRuntimeResponse membershipResponse = accountClient.getTenantMembershipForRuntime( - Long.toString(context.accountId()), Long.toString(selectedRealm.tenantId()), requestId); + context.accountId(), Long.toString(selectedRealm.tenantId()), requestId); Optional membershipFailure = validateMembershipResponse( membershipResponse, @@ -723,7 +725,7 @@ private Optional validateMembershipResponse( if (!isPublicProductionRealm(selectedRealm)) { GetRealmAccessGrantForRuntimeResponse grantResponse = accountClient.getRealmAccessGrantForRuntime( - Long.toString(context.accountId()), + context.accountId(), Long.toString(selectedRealm.tenantId()), selectedWorld.slug(), selectedRealm.slug(), @@ -910,11 +912,12 @@ private boolean isSafeMembershipAuthorityResponse( } try { Instant.parse(response.getEvaluatedAt()); - if (Long.parseLong(response.getAccountId()) != context.accountId() + if (!PositiveLongParsing.requireOptionalText(response.getAccountId(), "accountId") + .equals(PositiveLongParsing.requireOptionalText(context.accountId(), "accountId")) || Long.parseLong(response.getTenantId()) != selectedRealm.tenantId()) { return false; } - } catch (DateTimeParseException | NumberFormatException ex) { + } catch (DateTimeParseException | IllegalArgumentException ex) { return false; } return response.getMembershipExists() @@ -1104,7 +1107,7 @@ && sameSlug(context.worldSlug(), requestedWorldSlug) new SessionContext( context.sessionId(), context.tenantId(), - 0L, + null, null, 0L, null, diff --git a/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/command/text/WorldsCommandHandler.java b/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/command/text/WorldsCommandHandler.java index 680d7852c2..43abe253c4 100644 --- a/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/command/text/WorldsCommandHandler.java +++ b/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/command/text/WorldsCommandHandler.java @@ -63,7 +63,7 @@ public CharacterBrowseResult browseCharacters( ListCharactersByAccountResponse response = entityManagementClient.listCharactersByAccount( Long.toString(realm.tenantId()), - Long.toString(sessionContext.accountId()), + sessionContext.accountId(), Long.toString(realm.gameInstanceId()), toPlayableStateScope(realm)); if (response.hasError()) { diff --git a/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/config/EffectiveReconnectionSettingsResolver.java b/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/config/EffectiveReconnectionSettingsResolver.java index 2923de43cc..4f6ecb40e0 100644 --- a/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/config/EffectiveReconnectionSettingsResolver.java +++ b/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/config/EffectiveReconnectionSettingsResolver.java @@ -90,7 +90,17 @@ public ResolvedValue resolvedReconnection(Session public FiremudReconnectionProperties resolve(long tenantId, long gameInstanceId) { return resolvedReconnection( new SessionContext( - 0L, tenantId, 0L, null, 0L, null, gameInstanceId, null, null, null, gameInstanceId)) + 0L, + tenantId, + null, + null, + 0L, + null, + gameInstanceId, + null, + null, + null, + gameInstanceId)) .effective(); } diff --git a/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/controller/EffectiveSettingsController.java b/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/controller/EffectiveSettingsController.java index d98e06ebaa..2b6cd3b1ca 100644 --- a/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/controller/EffectiveSettingsController.java +++ b/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/controller/EffectiveSettingsController.java @@ -152,7 +152,7 @@ private SessionResolution resolveContext( new SessionContext( 0L, resolvedTenantId, - 0L, + null, null, 0L, null, diff --git a/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/health/GameplayLocalPathReadinessProbe.java b/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/health/GameplayLocalPathReadinessProbe.java index 52beec5126..95621033df 100644 --- a/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/health/GameplayLocalPathReadinessProbe.java +++ b/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/health/GameplayLocalPathReadinessProbe.java @@ -44,7 +44,7 @@ public ProbeResult probeSessionContextStore() { new SessionContext( probeSessionId, PROBE_TENANT_ID, - PROBE_ACCOUNT_ID, + Long.toString(PROBE_ACCOUNT_ID), PROBE_CHARACTER_ID, PROBE_GAME_INSTANCE_ID, probeRoomInstanceId, diff --git a/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/service/AccountPresenceQueryService.java b/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/service/AccountPresenceQueryService.java index e2ab1978ce..1440bc2e9d 100644 --- a/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/service/AccountPresenceQueryService.java +++ b/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/service/AccountPresenceQueryService.java @@ -5,5 +5,5 @@ /** Resolves account-scoped social presence from running sessions plus live gameplay presence. */ public interface AccountPresenceQueryService { List queryAccountPresence( - long tenantId, long viewerAccountId, List accountIds); + long tenantId, String viewerAccountId, List accountIds); } diff --git a/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/service/AccountPresenceSnapshot.java b/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/service/AccountPresenceSnapshot.java index 244da44537..81627959d1 100644 --- a/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/service/AccountPresenceSnapshot.java +++ b/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/service/AccountPresenceSnapshot.java @@ -6,7 +6,7 @@ * Canonical account-scoped social presence snapshot derived from current gameplay runtime state. */ public record AccountPresenceSnapshot( - long accountId, + String accountId, boolean online, Long gameInstanceId, String playableStateScope, @@ -21,7 +21,7 @@ public record AccountPresenceSnapshot( Instant lastSeenAt, AccountRecentPresenceDisposition recentDisposition) { public AccountPresenceSnapshot( - long accountId, + String accountId, boolean online, Long gameInstanceId, String worldSlug, @@ -50,7 +50,7 @@ public AccountPresenceSnapshot( } public AccountPresenceSnapshot( - long accountId, + String accountId, boolean online, Long gameInstanceId, String playableStateScope, diff --git a/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/service/AccountRecentPresenceService.java b/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/service/AccountRecentPresenceService.java index 8fc44afeda..993d372864 100644 --- a/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/service/AccountRecentPresenceService.java +++ b/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/service/AccountRecentPresenceService.java @@ -11,6 +11,6 @@ public interface AccountRecentPresenceService { void recordDisconnect(long sessionId, AccountRecentPresenceDisposition disposition); - Map findByAccountIds( - long tenantId, Collection accountIds); + Map findByAccountIds( + long tenantId, Collection accountIds); } diff --git a/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/service/AccountRecentPresenceState.java b/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/service/AccountRecentPresenceState.java index c8ecc54aca..71db4e4192 100644 --- a/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/service/AccountRecentPresenceState.java +++ b/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/service/AccountRecentPresenceState.java @@ -5,7 +5,7 @@ /** Bounded recent-presence facts retained after a gameplay presence disconnects. */ public record AccountRecentPresenceState( long tenantId, - long accountId, + String accountId, Long gameInstanceId, String playableStateScope, String worldSlug, @@ -18,7 +18,7 @@ public record AccountRecentPresenceState( public AccountRecentPresenceState( long tenantId, - long accountId, + String accountId, long lastSeenAtEpochMs, AccountRecentPresenceDisposition disposition) { this(tenantId, accountId, null, null, null, null, null, lastSeenAtEpochMs, disposition); diff --git a/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/service/FirstPartyConnectContext.java b/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/service/FirstPartyConnectContext.java index 3a33918103..f2b6e237fe 100644 --- a/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/service/FirstPartyConnectContext.java +++ b/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/service/FirstPartyConnectContext.java @@ -4,7 +4,7 @@ import org.springframework.util.StringUtils; public record FirstPartyConnectContext( - long accountId, + String accountId, long tenantId, String worldSlug, String realmSlug, @@ -18,7 +18,7 @@ public record FirstPartyConnectContext( private static final long serialVersionUID = 1L; public boolean hasCompleteRoutingScope() { - return accountId > 0L + return StringUtils.hasText(accountId) && tenantId > 0L && gameInstanceId > 0L && pointerVersion > 0L diff --git a/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/service/FirstPartyConnectContextService.java b/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/service/FirstPartyConnectContextService.java index 5882a8ed83..fa8d707640 100644 --- a/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/service/FirstPartyConnectContextService.java +++ b/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/service/FirstPartyConnectContextService.java @@ -42,7 +42,7 @@ public Optional parse(String token) { claims, "first-party connect context account subject mismatch"); return Optional.of( new FirstPartyConnectContext( - routingClaims.accountId(), + Long.toString(routingClaims.accountId()), routingClaims.tenantId(), routingClaims.worldSlug(), routingClaims.realmSlug(), diff --git a/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/service/GameplayPresence.java b/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/service/GameplayPresence.java index 7f7938aa62..ef919528b9 100644 --- a/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/service/GameplayPresence.java +++ b/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/service/GameplayPresence.java @@ -11,7 +11,7 @@ public record GameplayPresence( String worldSlug, String realmSlug, long pointerVersion, - long accountId, + String accountId, long characterId, String characterName, GameplayPresenceRole role, @@ -28,7 +28,7 @@ public GameplayPresence( long gameInstanceId, String worldSlug, String realmSlug, - long accountId, + String accountId, long characterId, String characterName, GameplayPresenceRole role, @@ -60,7 +60,7 @@ public GameplayPresence( String playableStateScope, String worldSlug, String realmSlug, - long accountId, + String accountId, long characterId, String characterName, GameplayPresenceRole role, diff --git a/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/service/GameplayPresenceService.java b/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/service/GameplayPresenceService.java index 58f54f8c91..7ec56bd602 100644 --- a/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/service/GameplayPresenceService.java +++ b/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/service/GameplayPresenceService.java @@ -17,8 +17,8 @@ public interface GameplayPresenceService { List listConnectedByGameInstance(long tenantId, long gameInstanceId); - Map> listConnectedByAccountIds( - long tenantId, Collection accountIds); + Map> listConnectedByAccountIds( + long tenantId, Collection accountIds); Optional findConnectedBySessionId(long sessionId); } diff --git a/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/service/SessionAuthenticationService.java b/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/service/SessionAuthenticationService.java index 1956ffbf95..0ebff77e98 100644 --- a/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/service/SessionAuthenticationService.java +++ b/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/service/SessionAuthenticationService.java @@ -103,7 +103,7 @@ public SessionContext normalizeResolvedContext(SessionContext context) { } private boolean isAuthenticatedContext(SessionContext context) { - return context.accountId() > 0; + return context.hasAccountIdentity(); } private Optional parseSessionId(String text) { diff --git a/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/service/SessionContext.java b/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/service/SessionContext.java index d32a473932..d2ca6ff738 100644 --- a/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/service/SessionContext.java +++ b/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/service/SessionContext.java @@ -2,13 +2,15 @@ import java.io.Serializable; import java.util.Locale; +import java.util.Objects; import java.util.Optional; +import org.springframework.util.StringUtils; /** Represents persisted login context stored in Redis for a session. */ public record SessionContext( long sessionId, long tenantId, - long accountId, + String accountId, String loginName, long characterId, String characterName, @@ -41,7 +43,7 @@ public record SessionContext( public SessionContext( long sessionId, long tenantId, - long accountId, + String accountId, String loginName, long characterId, String characterName, @@ -77,7 +79,7 @@ public SessionContext( public SessionContext( long sessionId, long tenantId, - long accountId, + String accountId, String loginName, long characterId, String characterName, @@ -108,7 +110,7 @@ public SessionContext( public SessionContext( long sessionId, long tenantId, - long accountId, + String accountId, String loginName, long characterId, String characterName, @@ -140,7 +142,7 @@ public SessionContext( public SessionContext( long sessionId, long tenantId, - long accountId, + String accountId, long characterId, long gameInstanceId, String roomInstanceId, @@ -168,7 +170,7 @@ public SessionContext( public SessionContext( long sessionId, long tenantId, - long accountId, + String accountId, long characterId, long gameInstanceId, String jwt) { @@ -195,7 +197,7 @@ public SessionContext( public SessionContext( long sessionId, long tenantId, - long accountId, + String accountId, String loginName, long characterId, String characterName, @@ -224,7 +226,7 @@ public SessionContext( public SessionContext( long sessionId, long tenantId, - long accountId, + String accountId, String loginName, long characterId, String characterName, @@ -281,6 +283,10 @@ public boolean hasGameplayIdentity() { return gameInstanceId > 0 && characterId > 0; } + public boolean hasAccountIdentity() { + return StringUtils.hasText(accountId); + } + public boolean hasGameplayBinding() { return gameInstanceId > 0 || characterId > 0 @@ -304,13 +310,13 @@ public boolean sameGameplayIdentity(SessionContext that) { } return sessionId == that.sessionId() && tenantId == that.tenantId() - && accountId == that.accountId() + && Objects.equals(accountId, that.accountId()) && characterId == that.characterId() && gameInstanceId == that.gameInstanceId(); } public Optional persistedFirstPartyConnectContext() { - if (accountId <= 0 || tenantId <= 0) { + if (!hasAccountIdentity() || tenantId <= 0) { return Optional.empty(); } FirstPartyConnectContext connectContext = @@ -331,7 +337,7 @@ public Optional persistedFirstPartyConnectContext() { } public boolean hasPartialPersistedFirstPartyConnectContext() { - if (accountId <= 0 || tenantId <= 0) { + if (!hasAccountIdentity() || tenantId <= 0) { return false; } boolean hasAnyPersistedSelectorField = connectScopeId != null || connectRequestId != null; diff --git a/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/service/impl/AccountPresenceQueryServiceImpl.java b/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/service/impl/AccountPresenceQueryServiceImpl.java index df33088477..3c4a0e5084 100644 --- a/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/service/impl/AccountPresenceQueryServiceImpl.java +++ b/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/service/impl/AccountPresenceQueryServiceImpl.java @@ -57,11 +57,11 @@ public AccountPresenceQueryServiceImpl( @Override public List queryAccountPresence( - long tenantId, long viewerAccountId, List accountIds) { + long tenantId, String viewerAccountId, List accountIds) { Objects.requireNonNull(accountIds, "accountIds"); - LinkedHashSet requestedIds = new LinkedHashSet<>(); - for (Long accountId : accountIds) { - if (accountId != null && accountId > 0) { + LinkedHashSet requestedIds = new LinkedHashSet<>(); + for (String accountId : accountIds) { + if (accountId != null && !accountId.isBlank()) { requestedIds.add(accountId); } } @@ -69,20 +69,20 @@ public List queryAccountPresence( return List.of(); } - Map results = new LinkedHashMap<>(); + Map results = new LinkedHashMap<>(); Map currentRuntimePointers = new HashMap<>(); - Map recentStates = + Map recentStates = accountRecentPresenceService.findByAccountIds(tenantId, requestedIds); - for (Long accountId : requestedIds) { + for (String accountId : requestedIds) { results.put( accountId, offline(tenantId, accountId, recentStates.get(accountId), currentRuntimePointers)); } - Map> activePresences = + Map> activePresences = gameplayPresenceService.listConnectedByAccountIds(tenantId, requestedIds); - for (Map.Entry> entry : activePresences.entrySet()) { - Long accountId = entry.getKey(); + for (Map.Entry> entry : activePresences.entrySet()) { + String accountId = entry.getKey(); GameplayPresence presence = selectCurrentPresence(tenantId, entry.getValue(), currentRuntimePointers); if (presence == null) { @@ -170,7 +170,7 @@ private boolean isCurrentPresence( private AccountPresenceSnapshot offline( long tenantId, - long accountId, + String accountId, AccountRecentPresenceState recentState, Map currentRuntimePointers) { GameplayAdmissionPointerSnapshot pointer = diff --git a/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/service/impl/CommandServiceImpl.java b/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/service/impl/CommandServiceImpl.java index f24de8b5ad..1c89763768 100644 --- a/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/service/impl/CommandServiceImpl.java +++ b/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/service/impl/CommandServiceImpl.java @@ -19,6 +19,7 @@ import net.firedevops.firemud.gamesession.service.GameplayAdmissionPointerAuthorityService; import net.firedevops.firemud.gamesession.service.GameplayAdmissionPointerSnapshot; import net.firedevops.firemud.gamesession.service.GameplayAdmissionPointerSnapshots; +import net.firedevops.firemud.gamesession.service.PositiveLongParsing; import net.firedevops.firemud.gamesession.service.ScriptEventPublisher; import net.firedevops.firemud.gamesession.service.SessionAuthenticationService; import net.firedevops.firemud.gamesession.service.SessionContext; @@ -99,6 +100,15 @@ public CommandEnqueueResult enqueue( } var sessionContext = resolveSessionContext(sessionIdText); + Optional numericAccountId; + try { + numericAccountId = + sessionContext + .map(SessionContext::accountId) + .flatMap(id -> PositiveLongParsing.requireOptionalText(id, "accountId")); + } catch (IllegalArgumentException ex) { + return CommandEnqueueResult.failure("INVALID_ARGUMENT", ex.getMessage()); + } Optional queueTarget = resolveQueueTarget(sessionContext); String tenantContext = queueTarget.map(target -> String.valueOf(target.tenantId())).orElse("unknown"); @@ -148,6 +158,7 @@ public CommandEnqueueResult enqueue( requiresSoloTick, queueTarget.get(), sessionContext, + numericAccountId, authoredAdmission, runtimeScope.get()); logger.info( @@ -189,6 +200,7 @@ private GameplayCommand persistAcceptedCommand( boolean requiresSoloTick, QueueTarget queueTarget, Optional sessionContext, + Optional numericAccountId, AuthoredCommandAdmission authoredAdmission, RuntimeRegionStatus runtimeScope) { Instant now = Instant.now(); @@ -197,10 +209,7 @@ private GameplayCommand persistAcceptedCommand( gameplayCommand.setTenantId(queueTarget.tenantId()); gameplayCommand.setGameInstanceId(queueTarget.queueTargetId()); gameplayCommand.setSessionId(sessionId); - sessionContext - .map(SessionContext::accountId) - .filter(id -> id > 0) - .ifPresent(gameplayCommand::setAccountId); + numericAccountId.ifPresent(gameplayCommand::setAccountId); sessionContext .map(SessionContext::characterId) .filter(id -> id > 0) 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 d415a8532e..518ac43b8f 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 @@ -232,9 +232,11 @@ private long parseOwnerAccountId(String ownerAccountIdText) { return ControlPlaneRequestParser.parsePositiveLong(ownerAccountIdText, "ownerAccountId"); } - private List parseAccountIds(List accountIds) { + private List parseAccountIds(List accountIds) { return accountIds.stream() - .map(accountId -> ControlPlaneRequestParser.parsePositiveLong(accountId, "accountId")) + .map( + accountId -> + Long.toString(ControlPlaneRequestParser.parsePositiveLong(accountId, "accountId"))) .toList(); } @@ -442,13 +444,14 @@ public void queryAccountPresence( if (request.getAccountIdsCount() > 100) { throw new IllegalArgumentException("accountIds must contain at most 100 entries"); } - List accountIds = parseAccountIds(request.getAccountIdsList()); + List accountIds = parseAccountIds(request.getAccountIdsList()); QueryAccountPresenceResponse.Builder builder = QueryAccountPresenceResponse.newBuilder(); for (var snapshot : - accountPresenceQueryService.queryAccountPresence(tenantId, viewerAccountId, accountIds)) { + accountPresenceQueryService.queryAccountPresence( + tenantId, Long.toString(viewerAccountId), accountIds)) { AccountPresenceEntry.Builder entry = AccountPresenceEntry.newBuilder() - .setAccountId(Long.toString(snapshot.accountId())) + .setAccountId(snapshot.accountId()) .setOnline(snapshot.online()); if (snapshot.gameInstanceId() != null) { entry.setGameInstanceId(Long.toString(snapshot.gameInstanceId())); diff --git a/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/service/impl/RedisAccountRecentPresenceService.java b/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/service/impl/RedisAccountRecentPresenceService.java index baaec064eb..dd83268e9e 100644 --- a/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/service/impl/RedisAccountRecentPresenceService.java +++ b/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/service/impl/RedisAccountRecentPresenceService.java @@ -1,5 +1,6 @@ package net.firedevops.firemud.gamesession.service.impl; +import edu.umd.cs.findbugs.annotations.SuppressFBWarnings; import java.time.Duration; import java.util.Collection; import java.util.LinkedHashMap; @@ -14,14 +15,22 @@ import net.firedevops.firemud.gamesession.service.GameplayPresenceService; import net.firedevops.firemud.gamesession.service.SessionContext; import net.firedevops.firemud.gamesession.service.SessionRoutingNormalizationService; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.data.redis.core.RedisOperations; import org.springframework.data.redis.core.RedisTemplate; +import org.springframework.data.redis.core.SessionCallback; import org.springframework.data.redis.core.ValueOperations; +import org.springframework.data.redis.serializer.SerializationException; import org.springframework.stereotype.Service; @Service public final class RedisAccountRecentPresenceService implements AccountRecentPresenceService { - private static final String RECENT_PRESENCE_KEY_TEMPLATE = "accountrecentpresence:%d:%d"; + private static final String RECENT_PRESENCE_KEY_TEMPLATE = "accountrecentpresence:%d:%s"; + private static final int MAX_WRITE_RETRIES = 8; + private static final Logger logger = + LoggerFactory.getLogger(RedisAccountRecentPresenceService.class); private final RedisTemplate redisTemplate; private final SessionRoutingNormalizationService sessionRoutingNormalizationService; @@ -58,7 +67,7 @@ public RedisAccountRecentPresenceService( @Override public void recordConnected(SessionContext context) { - if (context == null || context.tenantId() <= 0 || context.accountId() <= 0) { + if (context == null || context.tenantId() <= 0 || !context.hasAccountIdentity()) { return; } GameplayPresence presence = @@ -99,18 +108,22 @@ public void recordDisconnect(long sessionId, AccountRecentPresenceDisposition di } @Override - public Map findByAccountIds( - long tenantId, Collection accountIds) { + public Map findByAccountIds( + long tenantId, Collection accountIds) { ValueOperations valueOps = redisTemplate.opsForValue(); - LinkedHashMap results = new LinkedHashMap<>(); - for (Long accountId : accountIds) { - if (accountId == null || accountId <= 0 || valueOps == null) { + LinkedHashMap results = new LinkedHashMap<>(); + for (String accountId : accountIds) { + if (accountId == null || accountId.isBlank() || valueOps == null) { continue; } - AccountRecentPresenceState state = - (AccountRecentPresenceState) valueOps.get(key(tenantId, accountId)); - if (state != null) { - results.put(accountId, state); + try { + AccountRecentPresenceState state = + (AccountRecentPresenceState) valueOps.get(key(tenantId, accountId)); + if (state != null) { + results.put(accountId, state); + } + } catch (SerializationException | ClassCastException ex) { + // Retain unreadable evidence; it must not be treated as an absent value for cleanup. } } return Map.copyOf(results); @@ -122,8 +135,8 @@ private void write( if (valueOps == null || snapshot == null) { return; } - valueOps.set( - key(snapshot.tenantId(), snapshot.accountId()), + String key = key(snapshot.tenantId(), snapshot.accountId()); + AccountRecentPresenceState state = new AccountRecentPresenceState( snapshot.tenantId(), snapshot.accountId(), @@ -133,12 +146,45 @@ private void write( snapshot.realmSlug(), snapshot.pointerVersion(), timestampMs, - disposition), - ttl); + disposition); + for (int attempt = 0; attempt < MAX_WRITE_RETRIES; attempt++) { + WriteAttemptResult result = + redisTemplate.execute( + new SessionCallback<>() { + @Override + @SuppressFBWarnings( + value = "RCN_REDUNDANT_NULLCHECK_OF_NONNULL_VALUE", + justification = + "Redis EXEC returns null when WATCH detects a concurrent key change; retrying preserves the newer retained presence.") + public WriteAttemptResult execute(RedisOperations operations) { + operations.watch(key); + Object retained; + try { + retained = operations.opsForValue().get(key); + } catch (SerializationException | ClassCastException ex) { + operations.unwatch(); + return WriteAttemptResult.PRESERVED; + } + if (retained != null && !(retained instanceof AccountRecentPresenceState)) { + operations.unwatch(); + return WriteAttemptResult.PRESERVED; + } + operations.multi(); + operations.opsForValue().set(key, state, ttl); + return operations.exec() == null + ? WriteAttemptResult.RETRY + : WriteAttemptResult.COMMITTED; + } + }); + if (result == WriteAttemptResult.COMMITTED || result == WriteAttemptResult.PRESERVED) { + return; + } + } + logger.warn("Recent account presence projection update skipped after concurrent Redis changes"); } private RoutingSnapshot routingSnapshot(SessionContext context, GameplayPresence presence) { - if (context == null || context.tenantId() <= 0 || context.accountId() <= 0) { + if (context == null || context.tenantId() <= 0 || !context.hasAccountIdentity()) { return null; } GameplayPresence effectivePresence = @@ -180,16 +226,22 @@ private String blankToNull(String value) { return null; } - private String key(long tenantId, long accountId) { + private String key(long tenantId, String accountId) { return String.format(RECENT_PRESENCE_KEY_TEMPLATE, tenantId, accountId); } private record RoutingSnapshot( long tenantId, - long accountId, + String accountId, Long gameInstanceId, String playableStateScope, String worldSlug, String realmSlug, Long pointerVersion) {} + + private enum WriteAttemptResult { + COMMITTED, + RETRY, + PRESERVED + } } diff --git a/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/service/impl/RedisFirstPartyConnectContextRegistry.java b/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/service/impl/RedisFirstPartyConnectContextRegistry.java index fefa592746..b8ded43bcc 100644 --- a/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/service/impl/RedisFirstPartyConnectContextRegistry.java +++ b/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/service/impl/RedisFirstPartyConnectContextRegistry.java @@ -8,6 +8,7 @@ import net.firedevops.firemud.gamesession.service.FirstPartyConnectContextRegistry; import org.springframework.data.redis.core.RedisTemplate; import org.springframework.data.redis.core.ValueOperations; +import org.springframework.data.redis.serializer.SerializationException; import org.springframework.stereotype.Service; @Service @@ -29,17 +30,39 @@ public RedisFirstPartyConnectContextRegistry( @Override public void register(long sessionId, FirstPartyConnectContext connectContext) { - valueOperations().set(key(sessionId), connectContext, ttl); + String key = key(sessionId); + try { + Object retained = valueOperations().get(key); + if (retained != null && !(retained instanceof FirstPartyConnectContext)) { + throw new IllegalStateException( + "Retained first-party connect context is incompatible and cannot be replaced"); + } + } catch (SerializationException | ClassCastException ex) { + throw new IllegalStateException( + "Retained first-party connect context is unreadable and cannot be replaced", ex); + } + valueOperations().set(key, connectContext, ttl); } @Override public Optional find(long sessionId) { - return Optional.ofNullable((FirstPartyConnectContext) valueOperations().get(key(sessionId))); + try { + return Optional.ofNullable((FirstPartyConnectContext) valueOperations().get(key(sessionId))); + } catch (SerializationException | ClassCastException ex) { + return Optional.empty(); + } } @Override public void unregister(long sessionId) { - redisTemplate.delete(key(sessionId)); + String key = key(sessionId); + try { + if (valueOperations().get(key) instanceof FirstPartyConnectContext) { + redisTemplate.delete(key); + } + } catch (SerializationException | ClassCastException ex) { + // Retain unreadable evidence instead of treating it as an absent context. + } } private ValueOperations valueOperations() { diff --git a/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/service/impl/RedisGameplayPresenceService.java b/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/service/impl/RedisGameplayPresenceService.java index 47dcad6f62..153dfc047d 100644 --- a/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/service/impl/RedisGameplayPresenceService.java +++ b/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/service/impl/RedisGameplayPresenceService.java @@ -24,6 +24,7 @@ import org.springframework.data.redis.core.RedisTemplate; import org.springframework.data.redis.core.SetOperations; import org.springframework.data.redis.core.ValueOperations; +import org.springframework.data.redis.serializer.SerializationException; import org.springframework.stereotype.Service; import org.springframework.util.StringUtils; @@ -33,7 +34,7 @@ public final class RedisGameplayPresenceService implements GameplayPresenceServi private static final Logger logger = LoggingUtil.getLogger(RedisGameplayPresenceService.class); private static final String PRESENCE_KEY_TEMPLATE = "gameplaypresence:session:%d"; private static final String GAME_INSTANCE_SET_TEMPLATE = "gameplaypresence:%d:%d:sessions"; - private static final String ACCOUNT_SET_TEMPLATE = "gameplaypresence:%d:account:%d:sessions"; + private static final String ACCOUNT_SET_TEMPLATE = "gameplaypresence:%d:account:%s:sessions"; private static final Comparator ACCOUNT_PRESENCE_PREFERENCE = Comparator.comparing( GameplayPresence::lastMeaningfulActivityAtEpochMs, @@ -98,32 +99,37 @@ public void registerConnected(SessionContext context) { null); String presenceKey = presenceKey(context.sessionId()); String gameInstanceKey = gameInstanceKey(context.tenantId(), context.gameInstanceId()); - String accountKey = accountKey(context.tenantId(), context.accountId()); + String accountKey = + context.hasAccountIdentity() ? accountKey(context.tenantId(), context.accountId()) : null; valueOps.set(presenceKey, presence, presenceTtl); setOps.add(gameInstanceKey, Long.toString(context.sessionId())); - setOps.add(accountKey, Long.toString(context.sessionId())); redisTemplate.expire(gameInstanceKey, presenceTtl); - redisTemplate.expire(accountKey, presenceTtl); + if (accountKey != null) { + setOps.add(accountKey, Long.toString(context.sessionId())); + redisTemplate.expire(accountKey, presenceTtl); + } } @Override public void removeBySessionId(long sessionId) { ValueOperations valueOps = redisTemplate.opsForValue(); - GameplayPresence existing = (GameplayPresence) valueOps.get(presenceKey(sessionId)); + GameplayPresence existing = readRetainedPresenceForMutation(valueOps, presenceKey(sessionId)); redisTemplate.delete(presenceKey(sessionId)); if (existing != null) { String gameInstanceKey = gameInstanceKey(existing.tenantId(), existing.gameInstanceId()); - String accountKey = accountKey(existing.tenantId(), existing.accountId()); SetOperations setOps = redisTemplate.opsForSet(); setOps.remove(gameInstanceKey, Long.toString(sessionId)); - setOps.remove(accountKey, Long.toString(sessionId)); + if (StringUtils.hasText(existing.accountId())) { + setOps.remove( + accountKey(existing.tenantId(), existing.accountId()), Long.toString(sessionId)); + } } } @Override public void setExplicitAfk(long sessionId, boolean explicitAfk) { ValueOperations valueOps = redisTemplate.opsForValue(); - GameplayPresence existing = (GameplayPresence) valueOps.get(presenceKey(sessionId)); + GameplayPresence existing = readRetainedPresenceForMutation(valueOps, presenceKey(sessionId)); if (existing == null) { return; } @@ -147,13 +153,15 @@ public void setExplicitAfk(long sessionId, boolean explicitAfk) { valueOps.set(presenceKey(sessionId), updated, presenceTtl); redisTemplate.expire( gameInstanceKey(existing.tenantId(), existing.gameInstanceId()), presenceTtl); - redisTemplate.expire(accountKey(existing.tenantId(), existing.accountId()), presenceTtl); + if (StringUtils.hasText(existing.accountId())) { + redisTemplate.expire(accountKey(existing.tenantId(), existing.accountId()), presenceTtl); + } } @Override public void recordCommandActivity(long sessionId, boolean meaningfulGameplayActivity) { ValueOperations valueOps = redisTemplate.opsForValue(); - GameplayPresence existing = (GameplayPresence) valueOps.get(presenceKey(sessionId)); + GameplayPresence existing = readRetainedPresenceForMutation(valueOps, presenceKey(sessionId)); if (existing == null) { return; } @@ -180,7 +188,9 @@ public void recordCommandActivity(long sessionId, boolean meaningfulGameplayActi valueOps.set(presenceKey(sessionId), updated, presenceTtl); redisTemplate.expire( gameInstanceKey(existing.tenantId(), existing.gameInstanceId()), presenceTtl); - redisTemplate.expire(accountKey(existing.tenantId(), existing.accountId()), presenceTtl); + if (StringUtils.hasText(existing.accountId())) { + redisTemplate.expire(accountKey(existing.tenantId(), existing.accountId()), presenceTtl); + } } @Override @@ -201,7 +211,12 @@ public List listConnectedByGameInstance(long tenantId, long ga setOps.remove(gameInstanceKey, sessionIdText); continue; } - GameplayPresence presence = (GameplayPresence) valueOps.get(presenceKey); + GameplayPresence presence; + try { + presence = (GameplayPresence) valueOps.get(presenceKey); + } catch (SerializationException | ClassCastException ex) { + continue; + } if (presence == null) { setOps.remove(gameInstanceKey, sessionIdText); continue; @@ -221,17 +236,17 @@ public List listConnectedByGameInstance(long tenantId, long ga } @Override - public Map> listConnectedByAccountIds( - long tenantId, Collection accountIds) { + public Map> listConnectedByAccountIds( + long tenantId, Collection accountIds) { if (accountIds == null || accountIds.isEmpty()) { return Map.of(); } SetOperations setOps = redisTemplate.opsForSet(); ValueOperations valueOps = redisTemplate.opsForValue(); - LinkedHashMap> matches = new LinkedHashMap<>(); - for (Long accountId : accountIds) { - if (accountId == null || accountId <= 0) { + LinkedHashMap> matches = new LinkedHashMap<>(); + for (String accountId : accountIds) { + if (accountId == null || accountId.isBlank()) { continue; } String accountKey = accountKey(tenantId, accountId); @@ -247,12 +262,18 @@ public Map> listConnectedByAccountIds( setOps.remove(accountKey, sessionIdText); continue; } - GameplayPresence presence = (GameplayPresence) valueOps.get(presenceKey); + GameplayPresence presence; + try { + presence = (GameplayPresence) valueOps.get(presenceKey); + } catch (SerializationException | ClassCastException ex) { + continue; + } if (presence == null) { setOps.remove(accountKey, sessionIdText); continue; } - if (presence.tenantId() != tenantId || presence.accountId() != accountId) { + if (presence.tenantId() != tenantId + || !java.util.Objects.equals(presence.accountId(), accountId)) { setOps.remove(accountKey, sessionIdText); continue; } @@ -269,13 +290,27 @@ public Map> listConnectedByAccountIds( @Override public Optional findConnectedBySessionId(long sessionId) { ValueOperations valueOps = redisTemplate.opsForValue(); - return Optional.ofNullable((GameplayPresence) valueOps.get(presenceKey(sessionId))); + try { + return Optional.ofNullable((GameplayPresence) valueOps.get(presenceKey(sessionId))); + } catch (SerializationException | ClassCastException ex) { + return Optional.empty(); + } } private String presenceKey(long sessionId) { return String.format(PRESENCE_KEY_TEMPLATE, sessionId); } + private GameplayPresence readRetainedPresenceForMutation( + ValueOperations valueOps, String presenceKey) { + try { + return (GameplayPresence) valueOps.get(presenceKey); + } catch (SerializationException | ClassCastException ex) { + throw new IllegalStateException( + "Retained gameplay presence is unreadable or incompatible; mutation aborted", ex); + } + } + private String presenceKey(String sessionId) { PositiveLongParsing.ParsedPositiveLong parsed = PositiveLongParsing.parseOptionalText(sessionId, "sessionId"); @@ -289,7 +324,7 @@ private String gameInstanceKey(long tenantId, long gameInstanceId) { return String.format(GAME_INSTANCE_SET_TEMPLATE, tenantId, gameInstanceId); } - private String accountKey(long tenantId, long accountId) { + private String accountKey(long tenantId, String accountId) { return String.format(ACCOUNT_SET_TEMPLATE, tenantId, accountId); } diff --git a/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/service/impl/RedisSessionContextService.java b/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/service/impl/RedisSessionContextService.java index b7b8d502a8..742f1aeb5b 100644 --- a/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/service/impl/RedisSessionContextService.java +++ b/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/service/impl/RedisSessionContextService.java @@ -5,6 +5,7 @@ import java.util.ArrayList; import java.util.LinkedHashSet; import java.util.List; +import java.util.Objects; import java.util.Optional; import java.util.Set; import net.firedevops.firemud.gamesession.service.SessionContext; @@ -12,6 +13,7 @@ import org.springframework.beans.factory.annotation.Value; import org.springframework.data.redis.core.RedisTemplate; import org.springframework.data.redis.core.SessionCallback; +import org.springframework.data.redis.serializer.SerializationException; import org.springframework.stereotype.Service; import org.springframework.util.StringUtils; @@ -47,6 +49,8 @@ public Boolean execute( SessionContext existingContext = readContext( operations, contextKey(context.tenantId(), context.sessionId())); + SessionContext existingSessionContext = + readContext(operations, sessionKey(context.sessionId())); SessionContext existingIdentityContext = context.hasGameplayIdentity() ? readContext( @@ -68,6 +72,9 @@ public Boolean execute( : null; LinkedHashSet additionalWatchKeys = new LinkedHashSet<>(); addWatchKeys(additionalWatchKeys, existingContext); + if (isSessionAliasFor(existingSessionContext, context)) { + addWatchKeys(additionalWatchKeys, existingSessionContext); + } addWatchKeys(additionalWatchKeys, existingIdentityContext); addWatchKeys(additionalWatchKeys, existingNameContext); if (additionalWatchKeys.removeAll(watchedKeys) @@ -78,6 +85,10 @@ public Boolean execute( } operations.multi(); deleteIndexes(operations, existingContext); + if (!Objects.equals(existingContext, existingSessionContext) + && isSessionAliasFor(existingSessionContext, context)) { + deleteIndexes(operations, existingSessionContext); + } deleteIndexes(operations, existingIdentityContext); deleteIndexes(operations, existingNameContext); writeContext(operations, context); @@ -94,22 +105,18 @@ public Boolean execute( @Override public Optional findBySessionId(long sessionId) { - return Optional.ofNullable( - (SessionContext) redisTemplate.opsForValue().get(sessionKey(sessionId))); + return findContextForLookup(sessionKey(sessionId)); } @Override public Optional findByTenantAndSessionId(long tenantId, long sessionId) { - return Optional.ofNullable( - (SessionContext) redisTemplate.opsForValue().get(contextKey(tenantId, sessionId))); + return findContextForLookup(contextKey(tenantId, sessionId)); } @Override public Optional findByGameplayIdentity( long tenantId, long gameInstanceId, long characterId) { - return Optional.ofNullable( - (SessionContext) - redisTemplate.opsForValue().get(identityKey(tenantId, gameInstanceId, characterId))); + return findContextForLookup(identityKey(tenantId, gameInstanceId, characterId)); } @Override @@ -118,9 +125,7 @@ public Optional findByGameplayName( if (!StringUtils.hasText(characterName)) { return Optional.empty(); } - return Optional.ofNullable( - (SessionContext) - redisTemplate.opsForValue().get(nameKey(tenantId, gameInstanceId, characterName))); + return findContextForLookup(nameKey(tenantId, gameInstanceId, characterName)); } @Override @@ -139,8 +144,11 @@ public Boolean execute( operations.watch(watchedKeys); SessionContext existing = readContext(operations, contextKey(tenantId, sessionId)); + SessionContext existingSessionContext = + readContext(operations, sessionKey(sessionId)); LinkedHashSet additionalWatchKeys = new LinkedHashSet<>(); addWatchKeys(additionalWatchKeys, existing); + addWatchKeys(additionalWatchKeys, existingSessionContext); if (additionalWatchKeys.removeAll(watchedKeys) && !additionalWatchKeys.isEmpty()) { operations.unwatch(); @@ -149,6 +157,12 @@ public Boolean execute( } operations.multi(); deleteIndexes(operations, existing); + if (!Objects.equals(existing, existingSessionContext) + && existingSessionContext != null + && existingSessionContext.tenantId() == tenantId + && existingSessionContext.sessionId() == sessionId) { + deleteIndexes(operations, existingSessionContext); + } return operations.exec() != null; } } @@ -176,6 +190,12 @@ private String nameKey(long tenantId, long gameInstanceId, String characterName) return SessionContextRedisKeys.nameKey(tenantId, gameInstanceId, characterName); } + private boolean isSessionAliasFor(SessionContext candidate, SessionContext context) { + return candidate != null + && candidate.tenantId() == context.tenantId() + && candidate.sessionId() == context.sessionId(); + } + private List watchKeys(SessionContext context) { List keys = new ArrayList<>(); keys.add(contextKey(context.tenantId(), context.sessionId())); @@ -194,6 +214,14 @@ private SessionContext readContext( return (SessionContext) operations.opsForValue().get(key); } + private Optional findContextForLookup(String key) { + try { + return Optional.ofNullable((SessionContext) redisTemplate.opsForValue().get(key)); + } catch (SerializationException | ClassCastException ex) { + return Optional.empty(); + } + } + private void addWatchKeys(Set watchKeys, SessionContext context) { if (context == null) { return; diff --git a/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/websocket/GameSessionWebSocketHandler.java b/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/websocket/GameSessionWebSocketHandler.java index 3aa81f2452..205f6998f4 100644 --- a/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/websocket/GameSessionWebSocketHandler.java +++ b/services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/websocket/GameSessionWebSocketHandler.java @@ -749,7 +749,14 @@ private void bootstrapFirstPartySessionContext(WebSocketSession session, long se return; } String playableStateScope = currentPointer.orElseThrow().stateScope(); - firstPartyConnectContextRegistry.register(sessionId, connectContext); + try { + firstPartyConnectContextRegistry.register(sessionId, connectContext); + } catch (IllegalStateException ex) { + logger.warn( + "Unable to register first-party connect context because retained state is invalid"); + closeInvalidFirstPartyContext(session); + return; + } Optional existing = sessionAuthenticationService.resolveUnverifiedSessionContext( connectContext.tenantId(), sessionId); @@ -799,7 +806,7 @@ private void maybeRefreshBootstrapShell(SessionContext existing, SessionContext new SessionContext( existing.sessionId(), existing.tenantId(), - 0L, + null, null, 0L, null, @@ -846,7 +853,7 @@ private void maybeRefreshBootstrapShell(SessionContext existing, SessionContext new SessionContext( incomingShell.sessionId(), incomingShell.tenantId(), - 0L, + null, null, 0L, null, @@ -864,7 +871,7 @@ private void maybeRefreshBootstrapShell(SessionContext existing, SessionContext } private boolean hasAuthenticatedOrGameplayBinding(SessionContext context) { - return context.accountId() > 0 + return context.hasAccountIdentity() || context.characterId() > 0 || context.gameInstanceId() > 0 || StringUtils.hasText(context.roomInstanceId()) @@ -885,7 +892,7 @@ private SessionContext bootstrapShell( return new SessionContext( sessionId, tenantId, - 0L, + null, null, 0L, null, diff --git a/services/game-session-service/src/test/java/integration/net/firedevops/firemud/gamesession/GameSessionApplicationIntegrationTest.java b/services/game-session-service/src/test/java/integration/net/firedevops/firemud/gamesession/GameSessionApplicationIntegrationTest.java index 5d27ddca8a..802aebe29e 100644 --- a/services/game-session-service/src/test/java/integration/net/firedevops/firemud/gamesession/GameSessionApplicationIntegrationTest.java +++ b/services/game-session-service/src/test/java/integration/net/firedevops/firemud/gamesession/GameSessionApplicationIntegrationTest.java @@ -296,7 +296,7 @@ void effectiveSettingsEndpointMergesScopedOverridesForPersistedSession() { new SessionContext( 999L, 42L, - 100L, + "100", "player@example.com", 55L, "Player", diff --git a/services/game-session-service/src/test/java/integration/net/firedevops/firemud/gamesession/GameSessionLoginIntegrationTest.java b/services/game-session-service/src/test/java/integration/net/firedevops/firemud/gamesession/GameSessionLoginIntegrationTest.java index 39b104b419..d3299aa316 100644 --- a/services/game-session-service/src/test/java/integration/net/firedevops/firemud/gamesession/GameSessionLoginIntegrationTest.java +++ b/services/game-session-service/src/test/java/integration/net/firedevops/firemud/gamesession/GameSessionLoginIntegrationTest.java @@ -34,6 +34,9 @@ import org.springframework.boot.test.context.SpringBootTest.WebEnvironment; import org.springframework.boot.test.web.server.LocalServerPort; import org.springframework.context.annotation.Import; +import org.springframework.data.redis.core.RedisOperations; +import org.springframework.data.redis.core.RedisTemplate; +import org.springframework.data.redis.core.SessionCallback; import org.springframework.test.context.bean.override.mockito.MockitoBean; @SuppressWarnings({"removal"}) @@ -63,8 +66,7 @@ class GameSessionLoginIntegrationTest { @MockitoBean private org.springframework.data.redis.connection.RedisConnectionFactory redisConnectionFactory; - @MockitoBean - private org.springframework.data.redis.core.RedisTemplate redisTemplate; + @MockitoBean private RedisTemplate redisTemplate; @MockitoBean private org.springframework.data.redis.core.ValueOperations redisValueOperations; @@ -96,6 +98,7 @@ void setUp() { }) .when(redisTemplate) .delete(anyString()); + stubTransactionExecution(redisTemplate); when(accountClient.authenticate(anyString(), anyString())) .thenReturn( AuthenticateResponse.newBuilder().setAuthToken("stub-token").setAccountId("7").build()); @@ -140,7 +143,19 @@ void loginCallsAccountServiceAndReturnsOk() throws Exception { assertThat(payloads).anyMatch(s -> s.startsWith("OK LOGIN")); assertThat(sessionContextService.findByTenantAndSessionId(42L, 1L)).isPresent(); + assertThat(redisValueStore).containsKey("accountrecentpresence:42:7"); verify(accountClient).authenticate(eq("demo@example.com"), eq("swordfish")); } + + @SuppressWarnings("unchecked") + private static void stubTransactionExecution(RedisTemplate redisTemplate) { + when(redisTemplate.execute(org.mockito.Mockito.any(SessionCallback.class))) + .thenAnswer( + invocation -> { + SessionCallback callback = invocation.getArgument(0); + return callback.execute((RedisOperations) redisTemplate); + }); + when(redisTemplate.exec()).thenReturn(List.of("OK")); + } } 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 50a75aa443..66f1849c1e 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 @@ -67,7 +67,9 @@ import org.springframework.boot.test.web.server.LocalServerPort; import org.springframework.context.annotation.Import; import org.springframework.data.redis.connection.RedisConnectionFactory; +import org.springframework.data.redis.core.RedisOperations; import org.springframework.data.redis.core.RedisTemplate; +import org.springframework.data.redis.core.SessionCallback; import org.springframework.data.redis.core.SetOperations; import org.springframework.data.redis.core.ValueOperations; import org.springframework.grpc.server.lifecycle.GrpcServerLifecycle; @@ -210,6 +212,7 @@ void setUp() { }) .when(redisTemplate) .delete(org.mockito.ArgumentMatchers.anyString()); + stubTransactionExecution(redisTemplate); when(gameInstanceRepository.save(org.mockito.ArgumentMatchers.any(GameInstance.class))) .thenAnswer(invocation -> invocation.getArgument(0)); org.mockito.Mockito.doAnswer( @@ -653,7 +656,8 @@ void unexpectedDisconnectKeepsReplayEligibleForFreshReconnect() throws Exception GameplayAsyncAssertions.assertPresenceCountEventually( gameplayPresenceService, 22L, 1L, 0, java.time.Duration.ofSeconds(5)); assertThat(sessionContextService.findByTenantAndSessionId(22L, 41L)).isPresent(); - assertThat(accountRecentPresenceService.findByAccountIds(22L, List.of(123L))).containsKey(123L); + assertThat(accountRecentPresenceService.findByAccountIds(22L, List.of("123"))) + .containsKey("123"); List secondPayloads; try (GameplayWebSocketDriver client = openAdmittedGameplayDriver("42")) { @@ -1104,7 +1108,8 @@ void websocketFirstPartyLogoutRetainsReplayStateForFreshReconnect() throws Excep verify(screenBufferService, never()).clear(22L, 1L, 123L); GameplayAsyncAssertions.assertPresenceCountEventually( gameplayPresenceService, 22L, 1L, 0, java.time.Duration.ofSeconds(5)); - assertThat(accountRecentPresenceService.findByAccountIds(22L, List.of(123L))).containsKey(123L); + assertThat(accountRecentPresenceService.findByAccountIds(22L, List.of("123"))) + .containsKey("123"); java.util.List secondPayloads; try (GameplayWebSocketDriver client = @@ -1301,7 +1306,7 @@ void websocketGenericRouteChangeOnReusedTransportClearsOldStateAndRefreshesBoots assertThat(sessionContextService.findByTenantAndSessionId(22L, 41L)) .hasValueSatisfying( context -> { - assertThat(context.accountId()).isEqualTo(123L); + assertThat(context.accountId()).isEqualTo("123"); assertThat(context.gameInstanceId()).isZero(); assertThat(context.characterId()).isZero(); assertThat(context.bootstrapGameInstanceId()).isEqualTo(2L); @@ -1469,7 +1474,7 @@ void websocketFirstPartyRouteChangeOnReusedTransportClearsOldGameplayBeforeRelog assertThat(sessionContextService.findByTenantAndSessionId(22L, 2L)) .hasValueSatisfying( context -> { - assertThat(context.accountId()).isEqualTo(123L); + assertThat(context.accountId()).isEqualTo("123"); assertThat(context.gameInstanceId()).isZero(); assertThat(context.characterId()).isZero(); assertThat(context.bootstrapGameInstanceId()).isEqualTo(2L); @@ -1562,7 +1567,7 @@ void websocketFirstPartySelectorChangeOnReusedTransportClearsOldGameplayBeforeRe assertThat(sessionContextService.findByTenantAndSessionId(22L, 2L)) .hasValueSatisfying( context -> { - assertThat(context.accountId()).isEqualTo(123L); + assertThat(context.accountId()).isEqualTo("123"); assertThat(context.gameInstanceId()).isZero(); assertThat(context.characterId()).isZero(); assertThat(context.bootstrapGameInstanceId()).isEqualTo(1L); @@ -1743,6 +1748,17 @@ private void resetAdmissionPointers() { .containsExactly("demo"); } + @SuppressWarnings("unchecked") + private static void stubTransactionExecution(RedisTemplate redisTemplate) { + when(redisTemplate.execute(Mockito.any(SessionCallback.class))) + .thenAnswer( + invocation -> { + SessionCallback callback = invocation.getArgument(0); + return callback.execute((RedisOperations) redisTemplate); + }); + when(redisTemplate.exec()).thenReturn(List.of("OK")); + } + private static JsonNode json(String payload) { return GameplayStructuredCommandAssertions.parseStructuredResponse(payload); } diff --git a/services/game-session-service/src/test/java/net/firedevops/firemud/gamesession/service/impl/FakeGameplayPresenceService.java b/services/game-session-service/src/test/java/net/firedevops/firemud/gamesession/service/impl/FakeGameplayPresenceService.java index a425f43d3c..cdb8c9dadd 100644 --- a/services/game-session-service/src/test/java/net/firedevops/firemud/gamesession/service/impl/FakeGameplayPresenceService.java +++ b/services/game-session-service/src/test/java/net/firedevops/firemud/gamesession/service/impl/FakeGameplayPresenceService.java @@ -6,6 +6,7 @@ import java.util.List; import java.util.Locale; import java.util.Map; +import java.util.Objects; import java.util.Optional; import java.util.concurrent.ConcurrentHashMap; import java.util.concurrent.ConcurrentMap; @@ -100,20 +101,22 @@ public List listConnectedByGameInstance(long tenantId, long ga } @Override - public Map> listConnectedByAccountIds( - long tenantId, Collection accountIds) { + public Map> listConnectedByAccountIds( + long tenantId, Collection accountIds) { if (accountIds == null || accountIds.isEmpty()) { return Map.of(); } - Map> results = new LinkedHashMap<>(); - for (Long accountId : accountIds) { - if (accountId == null || accountId <= 0) { + Map> results = new LinkedHashMap<>(); + for (String accountId : accountIds) { + if (accountId == null || accountId.isBlank()) { continue; } List matches = presences.values().stream() .filter( - presence -> presence.tenantId() == tenantId && presence.accountId() == accountId) + presence -> + presence.tenantId() == tenantId + && Objects.equals(presence.accountId(), accountId)) .sorted(ordering()) .toList(); if (!matches.isEmpty()) { diff --git a/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/client/EntityManagementClientTest.java b/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/client/EntityManagementClientTest.java index 370c36e59c..dd50ee2bde 100644 --- a/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/client/EntityManagementClientTest.java +++ b/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/client/EntityManagementClientTest.java @@ -15,7 +15,8 @@ class EntityManagementClientTest { private static final SessionContext SESSION_CONTEXT = new SessionContext( - 41L, 22L, 0L, "", 123L, "", 1L, "R-1021", "", null, 1L, "world", "realm", 17L, "SHARED"); + 41L, 22L, "20", "", 123L, "", 1L, "R-1021", "", null, 1L, "world", "realm", 17L, + "SHARED"); @Test void listRoomEntitiesFailsClosedWhenSessionContextDropsPartOfAdmittedRoutingBundle() { diff --git a/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/client/GameLogicClientTest.java b/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/client/GameLogicClientTest.java index 49f6284c6b..c91a9c9043 100644 --- a/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/client/GameLogicClientTest.java +++ b/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/client/GameLogicClientTest.java @@ -4,6 +4,7 @@ import static org.assertj.core.api.Assertions.assertThatThrownBy; import static org.mockito.ArgumentMatchers.any; import static org.mockito.Mockito.mock; +import static org.mockito.Mockito.times; import static org.mockito.Mockito.verify; import static org.mockito.Mockito.when; @@ -27,12 +28,15 @@ import net.firedevops.firemud.entitymanagement.v1.QueryInventoryRequest; import net.firedevops.firemud.entitymanagement.v1.QueryInventoryResponse; import net.firedevops.firemud.entitymanagement.v1.RoomGroundInventoryItem; +import net.firedevops.firemud.gamelogic.v1.CommunicationType; import net.firedevops.firemud.gamelogic.v1.DropCarriedItemRequest; import net.firedevops.firemud.gamelogic.v1.GameLogicServiceGrpc; import net.firedevops.firemud.gamelogic.v1.LookRequest; import net.firedevops.firemud.gamelogic.v1.LookResult; import net.firedevops.firemud.gamelogic.v1.MoveResult; import net.firedevops.firemud.gamelogic.v1.PickupVisibleRoomItemRequest; +import net.firedevops.firemud.gamelogic.v1.SendCommunicationRequest; +import net.firedevops.firemud.gamelogic.v1.SendCommunicationResponse; import net.firedevops.firemud.gamesession.service.SessionContext; import net.firedevops.firemud.shared.v1.RoomInstanceRef; import org.junit.jupiter.api.Test; @@ -41,7 +45,7 @@ class GameLogicClientTest { private static final SessionContext SESSION_CONTEXT = new SessionContext( - 41L, 22L, 0L, "", 123L, "", 1L, "R-1021", "", null, 1L, "world", "realm", 17L, "SHARED"); + 41L, 22L, "0", "", 123L, "", 1L, "R-1021", "", null, 1L, "world", "realm", 17L, "SHARED"); @Test void resolveLookForwardsGameInstanceIdIntoRoomInstance() throws Exception { @@ -340,6 +344,43 @@ void pickupVisibleRoomItemForwardsRawReferenceAndSessionContextThroughGameLogic( assertThat(response.getInventoryItem().getItemName()).isEqualTo("Torch"); } + @Test + void sendCommunicationMapsNullAccountToEmptyAndPreservesOpaqueAccount() throws Exception { + GameLogicClient client = newClient(); + GameLogicServiceGrpc.GameLogicServiceBlockingStub stub = + mock(GameLogicServiceGrpc.GameLogicServiceBlockingStub.class); + when(stub.withDeadlineAfter(5L, TimeUnit.SECONDS)).thenReturn(stub); + when(stub.sendCommunication(any(SendCommunicationRequest.class))) + .thenReturn(SendCommunicationResponse.getDefaultInstance()); + setStub(client, stub); + + client.sendCommunication( + sessionContextWithAccountId(null), + "Sora", + "R-1021", + CommunicationType.SAY, + "hello", + null, + null, + null); + client.sendCommunication( + sessionContextWithAccountId("acct:opaque/legacy"), + "Sora", + "R-1021", + CommunicationType.SAY, + "hello", + null, + null, + null); + + ArgumentCaptor requestCaptor = + ArgumentCaptor.forClass(SendCommunicationRequest.class); + verify(stub, times(2)).sendCommunication(requestCaptor.capture()); + assertThat(requestCaptor.getAllValues()) + .extracting(SendCommunicationRequest::getAccountId) + .containsExactly("", "acct:opaque/legacy"); + } + @Test void listRoomGroundInventoryForwardsCurrentGameRoomAndAttestation() throws Exception { GameLogicClient client = newClient(); @@ -445,6 +486,48 @@ void dropCarriedItemForwardsRawReferenceAndSessionContextThroughGameLogic() thro assertThat(response.getRoomGroundItem().getItemName()).isEqualTo("Torch"); } + @Test + void pickupVisibleRoomItemMapsNullAccountToEmptyAndPreservesOpaqueAccount() throws Exception { + GameLogicClient client = newClient(); + GameLogicServiceGrpc.GameLogicServiceBlockingStub stub = + mock(GameLogicServiceGrpc.GameLogicServiceBlockingStub.class); + when(stub.withDeadlineAfter(5L, TimeUnit.SECONDS)).thenReturn(stub); + when(stub.pickupVisibleRoomItem(any(PickupVisibleRoomItemRequest.class))) + .thenReturn(PickupItemFromRoomResponse.getDefaultInstance()); + setStub(client, stub); + + client.pickupVisibleRoomItem(sessionContextWithAccountId(null), "torch1", 1); + client.pickupVisibleRoomItem(sessionContextWithAccountId("acct:opaque/legacy"), "torch1", 1); + + ArgumentCaptor requestCaptor = + ArgumentCaptor.forClass(PickupVisibleRoomItemRequest.class); + verify(stub, times(2)).pickupVisibleRoomItem(requestCaptor.capture()); + assertThat(requestCaptor.getAllValues()) + .extracting(PickupVisibleRoomItemRequest::getAccountId) + .containsExactly("", "acct:opaque/legacy"); + } + + @Test + void dropCarriedItemMapsNullAccountToEmptyAndPreservesOpaqueAccount() throws Exception { + GameLogicClient client = newClient(); + GameLogicServiceGrpc.GameLogicServiceBlockingStub stub = + mock(GameLogicServiceGrpc.GameLogicServiceBlockingStub.class); + when(stub.withDeadlineAfter(5L, TimeUnit.SECONDS)).thenReturn(stub); + when(stub.dropCarriedItem(any(DropCarriedItemRequest.class))) + .thenReturn(DropItemToRoomResponse.getDefaultInstance()); + setStub(client, stub); + + client.dropCarriedItem(sessionContextWithAccountId(null), "torch1", 1); + client.dropCarriedItem(sessionContextWithAccountId("acct:opaque/legacy"), "torch1", 1); + + ArgumentCaptor requestCaptor = + ArgumentCaptor.forClass(DropCarriedItemRequest.class); + verify(stub, times(2)).dropCarriedItem(requestCaptor.capture()); + assertThat(requestCaptor.getAllValues()) + .extracting(DropCarriedItemRequest::getAccountId) + .containsExactly("", "acct:opaque/legacy"); + } + @Test void queryInventoryFailsClosedWhenSessionContextDropsAdmittedPlayableStateScope() { GameLogicClient client = newClient(); @@ -529,6 +612,21 @@ private static GameLogicClient newClient() { when(attestationService.issueGameplaySessionAttestation( "22", "41", "0", "123", "1", "R-1021", "world", "realm", "17", "SHARED")) .thenReturn("attestation"); + when(attestationService.issueGameplaySessionAttestation( + "22", "41", null, "123", "1", "R-1021", "world", "realm", "17", "SHARED")) + .thenReturn("attestation"); + when(attestationService.issueGameplaySessionAttestation( + "22", + "41", + "acct:opaque/legacy", + "123", + "1", + "R-1021", + "world", + "realm", + "17", + "SHARED")) + .thenReturn("attestation"); when(attestationService.issueGameplaySessionAttestation( "22", "41", "0", "123", "1", "R-2045", "world", "realm", "17", "SHARED")) .thenReturn("destination-attestation"); @@ -542,6 +640,25 @@ private static GameLogicClient newClient() { attestationService); } + private static SessionContext sessionContextWithAccountId(String accountId) { + return new SessionContext( + SESSION_CONTEXT.sessionId(), + SESSION_CONTEXT.tenantId(), + accountId, + SESSION_CONTEXT.loginName(), + SESSION_CONTEXT.characterId(), + SESSION_CONTEXT.characterName(), + SESSION_CONTEXT.gameInstanceId(), + SESSION_CONTEXT.roomInstanceId(), + SESSION_CONTEXT.jwt(), + SESSION_CONTEXT.localeTag(), + SESSION_CONTEXT.bootstrapGameInstanceId(), + SESSION_CONTEXT.worldSlug(), + SESSION_CONTEXT.realmSlug(), + SESSION_CONTEXT.pointerVersion(), + SESSION_CONTEXT.playableStateScope()); + } + private static void setStub(GameLogicClient client, Object stub) throws Exception { Field field = net.firedevops.firemud.common.grpc.AbstractBlockingGrpcClient.class.getDeclaredField( diff --git a/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/command/text/ActionStateCommandHandlerTest.java b/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/command/text/ActionStateCommandHandlerTest.java index 2db4c405ba..ed4c0ccc78 100644 --- a/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/command/text/ActionStateCommandHandlerTest.java +++ b/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/command/text/ActionStateCommandHandlerTest.java @@ -22,7 +22,7 @@ class ActionStateCommandHandlerTest { private final ActionStateCommandHandler handler = new ActionStateCommandHandler(gameLogicClient, Clock.fixed(NOW, ZoneOffset.UTC)); private final SessionContext context = - new SessionContext(42L, 22L, 7L, "demo@example.com", 91L, "Demo", 5L, "R-1", "jwt-token"); + new SessionContext(42L, 22L, "7", "demo@example.com", 91L, "Demo", 5L, "R-1", "jwt-token"); @Test void blockAppliesShortLivedBlockingState() { @@ -106,7 +106,7 @@ void applyUsesTheProvidedEffectPayload() { @Test void blockRejectsPartialGameplayIdentityShell() { SessionContext partialContext = - new SessionContext(42L, 22L, 7L, "demo@example.com", 0L, null, 5L, "R-1", "jwt-token"); + new SessionContext(42L, 22L, "7", "demo@example.com", 0L, null, 5L, "R-1", "jwt-token"); var result = handler.handle( diff --git a/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/command/text/AdmittedCommandDefinitionReaderTest.java b/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/command/text/AdmittedCommandDefinitionReaderTest.java index 35c17c0645..7457fb6443 100644 --- a/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/command/text/AdmittedCommandDefinitionReaderTest.java +++ b/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/command/text/AdmittedCommandDefinitionReaderTest.java @@ -266,7 +266,7 @@ void rejectsUnregisteredCommandEffectsFromTheAdmittedBundle() { } private SessionContext context() { - return new SessionContext(1L, 7L, 2L, "player", 3L, "hero", 44L, "room", "jwt", 0L); + return new SessionContext(1L, 7L, "2", "player", 3L, "hero", 44L, "room", "jwt", 0L); } private GameInstance admittedInstance() { diff --git a/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/command/text/AfkCommandHandlerTest.java b/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/command/text/AfkCommandHandlerTest.java index 8340547b0a..58cdabf168 100644 --- a/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/command/text/AfkCommandHandlerTest.java +++ b/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/command/text/AfkCommandHandlerTest.java @@ -25,7 +25,7 @@ class AfkCommandHandlerTest { void afkOnSetsExplicitAfkOnPresence() { SessionContext context = new SessionContext( - 7L, 22L, 123L, "demo@example.com", 123L, "demo", 1L, "R-1021", null, "en-NZ", 1L); + 7L, 22L, "123", "demo@example.com", 123L, "demo", 1L, "R-1021", null, "en-NZ", 1L); when(sessionAuthenticationService.resolveSessionContext("7")).thenReturn(Optional.of(context)); AfkCommandHandlingResult result = @@ -40,7 +40,7 @@ void afkOnSetsExplicitAfkOnPresence() { void afkOffClearsExplicitAfkOnPresence() { SessionContext context = new SessionContext( - 7L, 22L, 123L, "demo@example.com", 123L, "demo", 1L, "R-1021", null, "en-NZ", 1L); + 7L, 22L, "123", "demo@example.com", 123L, "demo", 1L, "R-1021", null, "en-NZ", 1L); when(sessionAuthenticationService.resolveSessionContext("7")).thenReturn(Optional.of(context)); AfkCommandHandlingResult result = @@ -72,7 +72,7 @@ void afkRequiresGameplayContext() { void afkRejectsPartialGameplayIdentityShellFromResolvedSession() { SessionContext context = new SessionContext( - 7L, 22L, 123L, "demo@example.com", 0L, null, 1L, "R-1021", null, "en-NZ", 1L); + 7L, 22L, "123", "demo@example.com", 0L, null, 1L, "R-1021", null, "en-NZ", 1L); when(sessionAuthenticationService.resolveSessionContext("7")).thenReturn(Optional.of(context)); AfkCommandHandlingResult result = @@ -87,7 +87,7 @@ void afkRejectsPartialGameplayIdentityShellFromResolvedSession() { void directAfkRejectsPartialGameplayIdentityShell() { SessionContext context = new SessionContext( - 7L, 22L, 123L, "demo@example.com", 0L, null, 1L, "R-1021", null, "en-NZ", 1L); + 7L, 22L, "123", "demo@example.com", 0L, null, 1L, "R-1021", null, "en-NZ", 1L); AfkCommandHandlingResult result = handler.handle( diff --git a/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/command/text/AuthoredActionCommandHandlerTest.java b/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/command/text/AuthoredActionCommandHandlerTest.java index e065a0e8dd..1f3e56e298 100644 --- a/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/command/text/AuthoredActionCommandHandlerTest.java +++ b/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/command/text/AuthoredActionCommandHandlerTest.java @@ -43,7 +43,7 @@ void admittedAuthoredActionFailsClosedUntilItsDeclaredEffectHasARuntimeHandler() TextCommandInterpretationResult result = handler.handle( - new SessionContext(1L, 1L, 2L, "player@example.com", 3L, "Player", 4L, "room", "jwt"), + new SessionContext(1L, 1L, "2", "player@example.com", 3L, "Player", 4L, "room", "jwt"), command); assertFalse(result.commandResult().accepted()); diff --git a/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/command/text/AuthoredActionTextCommandDispatchHandlerTest.java b/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/command/text/AuthoredActionTextCommandDispatchHandlerTest.java index 13063bac47..c7b2dc90e6 100644 --- a/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/command/text/AuthoredActionTextCommandDispatchHandlerTest.java +++ b/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/command/text/AuthoredActionTextCommandDispatchHandlerTest.java @@ -87,7 +87,7 @@ void rejectsAuthoredActionsWithoutGameplayContext() { private static SessionContext context() { return new SessionContext( - 7L, 22L, 41L, "emberline@example.com", 7001L, "Emberline", 9L, "R-1", "jwt"); + 7L, 22L, "41", "emberline@example.com", 7001L, "Emberline", 9L, "R-1", "jwt"); } private static TextCommand authoredAction(String commandId, String rawLine, List args) { diff --git a/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/command/text/CommunicationCommandHandlerTest.java b/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/command/text/CommunicationCommandHandlerTest.java index 930b9ec39c..d81046a54d 100644 --- a/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/command/text/CommunicationCommandHandlerTest.java +++ b/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/command/text/CommunicationCommandHandlerTest.java @@ -43,7 +43,7 @@ class CommunicationCommandHandlerTest { new SessionContext( 1L, 22L, - 123L, + "123", "emberline@example.com", 911L, "Emberline", @@ -164,7 +164,7 @@ void tellRequiresOnlineTarget() { void tellFailsClosedWhenTargetGameplayBindingNormalizesAway() { SessionContext normalizedTarget = new SessionContext( - 77L, 22L, 700L, "sora@example.com", 0L, null, 0L, null, "jwt", "en-NZ", 1L); + 77L, 22L, "700", "sora@example.com", 0L, null, 0L, null, "jwt", "en-NZ", 1L); when(entityManagementClient.findCharacterByName( sessionContext, PlayableStateScope.PLAYABLE_STATE_SCOPE_SHARED, "Sora")) .thenReturn( diff --git a/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/command/text/ContainerCommandHandlerTest.java b/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/command/text/ContainerCommandHandlerTest.java index 7624a3e4fc..da1de2c984 100644 --- a/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/command/text/ContainerCommandHandlerTest.java +++ b/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/command/text/ContainerCommandHandlerTest.java @@ -26,7 +26,7 @@ class ContainerCommandHandlerTest { private final ContainerCommandHandler handler = new ContainerCommandHandler(gameLogicClient); private final SessionContext context = new SessionContext( - 1L, 22L, 123L, "emberline@example.com", 911L, "Emberline", 77L, "R-7", "jwt-token"); + 1L, 22L, "123", "emberline@example.com", 911L, "Emberline", 77L, "R-7", "jwt-token"); @Test void containerViewReturnsStructuredContents() { diff --git a/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/command/text/EquipmentCommandHandlerTest.java b/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/command/text/EquipmentCommandHandlerTest.java index 211de4cf9c..649c86ac1e 100644 --- a/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/command/text/EquipmentCommandHandlerTest.java +++ b/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/command/text/EquipmentCommandHandlerTest.java @@ -24,7 +24,7 @@ class EquipmentCommandHandlerTest { private final EquipmentCommandHandler handler = new EquipmentCommandHandler(gameLogicClient); private final SessionContext context = new SessionContext( - 1L, 22L, 123L, "emberline@example.com", 911L, "Emberline", 77L, "R-7", "jwt-token"); + 1L, 22L, "123", "emberline@example.com", 911L, "Emberline", 77L, "R-7", "jwt-token"); @Test void wearWithoutItemReferenceFailsFast() { diff --git a/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/command/text/FriendsCommandHandlerTest.java b/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/command/text/FriendsCommandHandlerTest.java index c7dd4a3e8f..7b7d5aa4b8 100644 --- a/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/command/text/FriendsCommandHandlerTest.java +++ b/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/command/text/FriendsCommandHandlerTest.java @@ -4,6 +4,7 @@ import static org.mockito.Mockito.when; import java.time.Instant; +import java.util.List; import java.util.Optional; import net.firedevops.firemud.entitymanagement.v1.Character; import net.firedevops.firemud.entitymanagement.v1.PlayableStateScope; @@ -36,11 +37,13 @@ import org.mockito.Mockito; class FriendsCommandHandlerTest { + private record InvalidAccountAction(List args, String errorCode, String message) {} + private static final SessionContext GAMEPLAY_CONTEXT = new SessionContext( 7L, 1L, - 41L, + "41", "demo@example.com", 99L, "Emberline", @@ -62,6 +65,133 @@ private FriendsCommandHandler newHandler( socialGroupsClient, entityManagementClient, scriptEventPublisher); } + private SessionContext gameplayContextWithAccountId(String accountId) { + return new SessionContext( + 7L, + 1L, + accountId, + "demo@example.com", + 99L, + "Emberline", + 7L, + "R-1", + null, + null, + 7L, + "demo", + "production", + 1L, + "SHARED"); + } + + @Test + void unsupportedAccountIdsFailByActionBeforeEntitySocialOrEventCalls() { + SocialGroupsClient socialGroupsClient = Mockito.mock(SocialGroupsClient.class); + EntityManagementClient entityManagementClient = Mockito.mock(EntityManagementClient.class); + ScriptEventPublisher scriptEventPublisher = Mockito.mock(ScriptEventPublisher.class); + FriendsCommandHandler handler = + newHandler(socialGroupsClient, entityManagementClient, scriptEventPublisher); + List actions = + List.of( + new InvalidAccountAction( + List.of(), "FRIEND_PRESENCE_UNAVAILABLE", "Friend presence unavailable"), + new InvalidAccountAction( + List.of("ADD", "Sora"), "FRIEND_ADD_UNAVAILABLE", "Friend add unavailable"), + new InvalidAccountAction( + List.of("REMOVE", "77"), "FRIEND_REMOVE_UNAVAILABLE", "Friend removal unavailable"), + new InvalidAccountAction( + List.of("SHOW", "77"), "FRIEND_DETAIL_UNAVAILABLE", "Friend detail unavailable"), + new InvalidAccountAction( + List.of("REMOVE", "#1"), "FRIEND_REMOVE_UNAVAILABLE", "Friend removal unavailable"), + new InvalidAccountAction( + List.of("SHOW", "#1"), "FRIEND_DETAIL_UNAVAILABLE", "Friend detail unavailable"), + new InvalidAccountAction( + List.of("SUMMARY"), + "FRIEND_SUMMARY_UNAVAILABLE", + "Friend roster summary unavailable"), + new InvalidAccountAction( + List.of("VISIBILITY"), + "FRIEND_VISIBILITY_UNAVAILABLE", + "Friend presence visibility unavailable"), + new InvalidAccountAction( + List.of("VISIBILITY", "PRIVATE"), + "FRIEND_VISIBILITY_UPDATE_UNAVAILABLE", + "Friend presence visibility update unavailable")); + + for (String accountId : List.of("opaque-account-uuid", "", "0", "-41")) { + SessionContext context = gameplayContextWithAccountId(accountId); + for (InvalidAccountAction action : actions) { + TextCommandInterpretationResult result = + handler.handle( + new TextCommand( + TextCommandType.FRIENDS, + action.args(), + "FRIENDS " + String.join(" ", action.args())), + context); + + assertThat(result.commandResult().accepted()).isFalse(); + assertThat(result.commandResult().errorCode()).isEqualTo(action.errorCode()); + assertThat(result.outputs()) + .singleElement() + .extracting(PlayerOutput::text) + .isEqualTo("ERROR " + action.errorCode() + " " + action.message()); + } + } + + Mockito.verifyNoInteractions(socialGroupsClient, entityManagementClient, scriptEventPublisher); + } + + @Test + void usageErrorsRemainVisibleBeforeUnsupportedAccountFailure() { + SocialGroupsClient socialGroupsClient = Mockito.mock(SocialGroupsClient.class); + EntityManagementClient entityManagementClient = Mockito.mock(EntityManagementClient.class); + ScriptEventPublisher scriptEventPublisher = Mockito.mock(ScriptEventPublisher.class); + FriendsCommandHandler handler = + newHandler(socialGroupsClient, entityManagementClient, scriptEventPublisher); + + TextCommandInterpretationResult missingTarget = + handler.handle( + new TextCommand(TextCommandType.FRIENDS, List.of("ADD"), "FRIENDS ADD"), + gameplayContextWithAccountId("opaque-account-uuid")); + TextCommandInterpretationResult invalidOrdinal = + handler.handle( + new TextCommand( + TextCommandType.FRIENDS, List.of("REMOVE", "#bad"), "FRIENDS REMOVE #bad"), + gameplayContextWithAccountId("opaque-account-uuid")); + TextCommandInterpretationResult invalidVisibility = + handler.handle( + new TextCommand( + TextCommandType.FRIENDS, + List.of("VISIBILITY", "UNKNOWN"), + "FRIENDS VISIBILITY UNKNOWN"), + gameplayContextWithAccountId("opaque-account-uuid")); + + assertThat(missingTarget.commandResult().errorCode()).isEqualTo("INVALID_ARGUMENT"); + assertThat(invalidOrdinal.commandResult().errorCode()).isEqualTo("INVALID_ARGUMENT"); + assertThat(invalidVisibility.commandResult().errorCode()).isEqualTo("INVALID_ARGUMENT"); + Mockito.verifyNoInteractions(socialGroupsClient, entityManagementClient, scriptEventPublisher); + } + + @Test + void friendsListPreservesMaximumPositiveLongAccountId() { + SocialGroupsClient socialGroupsClient = Mockito.mock(SocialGroupsClient.class); + EntityManagementClient entityManagementClient = Mockito.mock(EntityManagementClient.class); + ScriptEventPublisher scriptEventPublisher = Mockito.mock(ScriptEventPublisher.class); + FriendsCommandHandler handler = + newHandler(socialGroupsClient, entityManagementClient, scriptEventPublisher); + when(socialGroupsClient.listFriends(1L, Long.MAX_VALUE)) + .thenReturn(ListFriendsResponse.newBuilder().build()); + + TextCommandInterpretationResult result = + handler.handle( + new TextCommand(TextCommandType.FRIENDS, List.of(), "FRIENDS"), + gameplayContextWithAccountId(Long.toString(Long.MAX_VALUE))); + + assertThat(result.commandResult().accepted()).isTrue(); + Mockito.verify(socialGroupsClient).listFriends(1L, Long.MAX_VALUE); + Mockito.verify(scriptEventPublisher).publishCommandEvent(Mockito.any(), Mockito.any()); + } + @Test void friendsMapsVisiblePresenceToTypedViewAndText() { SocialGroupsClient socialGroupsClient = Mockito.mock(SocialGroupsClient.class); @@ -781,26 +911,33 @@ void friendsShowByOrdinalUsesCanonicalDetailSurface() { } @Test - void friendsMutationRejectsSelfLink() { + void friendsAddAndRemoveRejectSelfLinkForEquivalentNumericAccountText() { SocialGroupsClient socialGroupsClient = Mockito.mock(SocialGroupsClient.class); EntityManagementClient entityManagementClient = Mockito.mock(EntityManagementClient.class); + ScriptEventPublisher scriptEventPublisher = Mockito.mock(ScriptEventPublisher.class); FriendsCommandHandler handler = - newHandler( - socialGroupsClient, entityManagementClient, Mockito.mock(ScriptEventPublisher.class)); - - TextCommandInterpretationResult result = - handler.handle( - new TextCommand( - TextCommandType.FRIENDS, java.util.List.of("ADD", "41"), "FRIENDS ADD 41"), - GAMEPLAY_CONTEXT); + newHandler(socialGroupsClient, entityManagementClient, scriptEventPublisher); - assertThat(result.commandResult().accepted()).isFalse(); - assertThat(result.commandResult().errorCode()).isEqualTo("FRIEND_SELF_LINK_FORBIDDEN"); - assertThat(result.outputs()) - .singleElement() - .extracting(PlayerOutput::text) - .isEqualTo( - "ERROR FRIEND_SELF_LINK_FORBIDDEN Cannot add or remove your own account as a friend"); + for (String accountIdText : List.of("41", "041", "+41")) { + SessionContext context = gameplayContextWithAccountId(accountIdText); + for (String action : List.of("ADD", "REMOVE")) { + TextCommandInterpretationResult result = + handler.handle( + new TextCommand( + TextCommandType.FRIENDS, List.of(action, "41"), "FRIENDS " + action + " 41"), + context); + + assertThat(result.commandResult().accepted()).isFalse(); + assertThat(result.commandResult().errorCode()).isEqualTo("FRIEND_SELF_LINK_FORBIDDEN"); + assertThat(result.outputs()) + .singleElement() + .extracting(PlayerOutput::text) + .isEqualTo( + "ERROR FRIEND_SELF_LINK_FORBIDDEN Cannot add or remove your own account as a friend"); + } + } + + Mockito.verifyNoInteractions(socialGroupsClient, entityManagementClient, scriptEventPublisher); } @Test diff --git a/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/command/text/HelpCommandHandlerTest.java b/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/command/text/HelpCommandHandlerTest.java index 9b38159a98..728f673e5f 100644 --- a/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/command/text/HelpCommandHandlerTest.java +++ b/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/command/text/HelpCommandHandlerTest.java @@ -225,7 +225,7 @@ void helpIndexHidesHistoryWhenFeatureDisabled() { (context, topic) -> Optional.empty(), null, capabilitiesResolver(false)); SessionContext context = new SessionContext( - 42L, 22L, 123L, "emberline@example.com", 7001L, "Emberline", 9L, "R-1", "jwt"); + 42L, 22L, "123", "emberline@example.com", 7001L, "Emberline", 9L, "R-1", "jwt"); TextCommandInterpretationResult result = disabledHandler.handle( @@ -244,7 +244,7 @@ void helpIndexHidesEveryDisabledStandardCapabilityFamily() { CommandCapabilitiesTestSupport.resolver(false, false, false, true)); SessionContext context = new SessionContext( - 42L, 22L, 123L, "emberline@example.com", 7001L, "Emberline", 9L, "R-1", "jwt"); + 42L, 22L, "123", "emberline@example.com", 7001L, "Emberline", 9L, "R-1", "jwt"); TextCommandInterpretationResult result = disabledHandler.handle( @@ -264,7 +264,7 @@ void helpHistoryTopicUnavailableWhenFeatureDisabled() { (context, topic) -> Optional.empty(), null, capabilitiesResolver(false)); SessionContext context = new SessionContext( - 42L, 22L, 123L, "emberline@example.com", 7001L, "Emberline", 9L, "R-1", "jwt"); + 42L, 22L, "123", "emberline@example.com", 7001L, "Emberline", 9L, "R-1", "jwt"); TextCommandInterpretationResult result = disabledHandler.handle( @@ -282,7 +282,7 @@ void helpHistoryTopicAvailableWhenFeatureEnabled() { (context, topic) -> Optional.empty(), null, capabilitiesResolver(true)); SessionContext context = new SessionContext( - 42L, 22L, 123L, "emberline@example.com", 7001L, "Emberline", 9L, "R-1", "jwt"); + 42L, 22L, "123", "emberline@example.com", 7001L, "Emberline", 9L, "R-1", "jwt"); TextCommandInterpretationResult result = enabledHandler.handle( @@ -305,7 +305,7 @@ void publishedGameAuthoredTopicOverridesPlatformTopicForAdmittedSession() { HelpCommandHandler authoredHelpHandler = new HelpCommandHandler(reader, null, null); SessionContext context = new SessionContext( - 41L, 22L, 123L, "demo@example.com", 7001L, "Emberline", 7L, "R-1", "jwt"); + 41L, 22L, "123", "demo@example.com", 7001L, "Emberline", 7L, "R-1", "jwt"); TextCommandInterpretationResult result = authoredHelpHandler.handle( diff --git a/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/command/text/HelpTextCommandDispatchHandlerTest.java b/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/command/text/HelpTextCommandDispatchHandlerTest.java index 2d20e1651b..1ad2d47676 100644 --- a/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/command/text/HelpTextCommandDispatchHandlerTest.java +++ b/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/command/text/HelpTextCommandDispatchHandlerTest.java @@ -20,7 +20,7 @@ class HelpTextCommandDispatchHandlerTest { void publishesCommandEventForGameplayScopedHelp() { SessionContext context = new SessionContext( - 7L, 22L, 41L, "emberline@example.com", 7001L, "Emberline", 9L, "R-1", "jwt"); + 7L, 22L, "41", "emberline@example.com", 7001L, "Emberline", 9L, "R-1", "jwt"); TextCommandInterpretationResult result = handler.handle( diff --git a/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/command/text/HistoryCommandHandlerTest.java b/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/command/text/HistoryCommandHandlerTest.java index d69cd7549a..5f5db10d8d 100644 --- a/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/command/text/HistoryCommandHandlerTest.java +++ b/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/command/text/HistoryCommandHandlerTest.java @@ -193,7 +193,7 @@ void rejectsNonPositiveHistoryCountWithoutReadingStorage() { private SessionContext standardContext() { return new SessionContext( - 22L, 7L, 99L, "demo@example.com", 7001L, "Emberline", 9L, "R-1", "jwt"); + 22L, 7L, "99", "demo@example.com", 7001L, "Emberline", 9L, "R-1", "jwt"); } private HistoryCommandHandler handler( diff --git a/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/command/text/HistoryTextCommandDispatchHandlerTest.java b/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/command/text/HistoryTextCommandDispatchHandlerTest.java index 4859f2ae05..8534846196 100644 --- a/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/command/text/HistoryTextCommandDispatchHandlerTest.java +++ b/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/command/text/HistoryTextCommandDispatchHandlerTest.java @@ -31,7 +31,7 @@ void dispatchesToHistoryHandler() { Mockito.when(historyStorageService.findRecent(7L, 9L, 7001L, 2)) .thenReturn(List.of("LOOK", "SAY hi")); SessionContext context = - new SessionContext(22L, 7L, 99L, "demo@example.com", 7001L, "Emberline", 9L, "R-1", "jwt"); + new SessionContext(22L, 7L, "99", "demo@example.com", 7001L, "Emberline", 9L, "R-1", "jwt"); TextCommandInterpretationResult result = handler.handle( diff --git a/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/command/text/InventoryCommandHandlerTest.java b/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/command/text/InventoryCommandHandlerTest.java index 8e29601ed9..005255ed07 100644 --- a/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/command/text/InventoryCommandHandlerTest.java +++ b/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/command/text/InventoryCommandHandlerTest.java @@ -26,7 +26,7 @@ class InventoryCommandHandlerTest { private final InventoryCommandHandler handler = new InventoryCommandHandler(gameLogicClient); private final SessionContext context = new SessionContext( - 1L, 22L, 123L, "emberline@example.com", 911L, "Emberline", 77L, "R-7", "jwt-token"); + 1L, 22L, "123", "emberline@example.com", 911L, "Emberline", 77L, "R-7", "jwt-token"); @Test void inventoryReturnsStructuredViewFromRuntimeContract() { diff --git a/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/command/text/ItemCommandHandlerTest.java b/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/command/text/ItemCommandHandlerTest.java index b716bebb5c..1e5331db58 100644 --- a/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/command/text/ItemCommandHandlerTest.java +++ b/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/command/text/ItemCommandHandlerTest.java @@ -30,7 +30,7 @@ class ItemCommandHandlerTest { scriptEventPublisher); private final SessionContext context = new SessionContext( - 1L, 22L, 123L, "emberline@example.com", 911L, "Emberline", 77L, "R-7", "jwt-token"); + 1L, 22L, "123", "emberline@example.com", 911L, "Emberline", 77L, "R-7", "jwt-token"); @Test void recordsInvocationForSuccessfulItemCommand() { diff --git a/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/command/text/LoginCommandHandlerTest.java b/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/command/text/LoginCommandHandlerTest.java index e0bc1e530d..4b3ae791f2 100644 --- a/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/command/text/LoginCommandHandlerTest.java +++ b/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/command/text/LoginCommandHandlerTest.java @@ -361,6 +361,50 @@ void missingCredentialsReturnsPromptError() { assertClearedSessionContext(lastCaptured(captor), 0L, null, null); } + @Test + void bareLoginWithUnavailableFirstPartyContextDoesNotAuthenticateOrChangeOwnership() { + when(firstPartyConnectContextRegistry.find(1L)).thenReturn(Optional.empty()); + TextCommand command = new TextCommand(TextCommandType.LOGIN, List.of(), "LOGIN"); + + LoginCommandHandlingResult result = handler.handle("1", command, false); + + assertFalse(result.commandResult().accepted()); + assertEquals( + LoginCommandConstants.PROMPT_MODE_UNSUPPORTED_CODE, result.commandResult().errorCode()); + verify(accountClient, never()).authenticate(anyString(), anyString()); + verify(firstPartyConnectContextRegistry, never()).unregister(1L); + verify(gameInstanceRepository, never()).findById(anyLong()); + ArgumentCaptor saved = ArgumentCaptor.forClass(SessionContext.class); + verify(sessionContextService).save(saved.capture()); + assertNull(saved.getValue().accountId()); + } + + @Test + void credentialLoginCanReauthenticateAfterUnavailableFirstPartyContext() { + when(firstPartyConnectContextRegistry.find(1L)).thenReturn(Optional.empty()); + when(gameInstanceRepository.findById(1L)).thenReturn(Optional.of(buildInstance(1L, 22L, 77L))); + + LoginCommandHandlingResult bareLogin = + handler.handle("1", new TextCommand(TextCommandType.LOGIN, List.of(), "LOGIN"), false); + LoginCommandHandlingResult credentialLogin = + handler.handle( + "1", + new TextCommand( + TextCommandType.LOGIN, + List.of("demo@example.com", "swordfish"), + "LOGIN demo@example.com swordfish"), + false); + + assertFalse(bareLogin.commandResult().accepted()); + assertTrue(credentialLogin.commandResult().accepted()); + verify(accountClient).authenticate("demo@example.com", "swordfish"); + ArgumentCaptor saved = ArgumentCaptor.forClass(SessionContext.class); + verify(sessionContextService, times(2)).save(saved.capture()); + assertNull(saved.getAllValues().get(0).accountId()); + assertEquals("77", saved.getAllValues().get(1).accountId()); + assertEquals("demo@example.com", saved.getAllValues().get(1).loginName()); + } + @Test void bareLoginPersistsVerifiedFirstPartyAccountWithoutEnqueueingGameplayCommand() { TextCommand command = new TextCommand(TextCommandType.LOGIN, List.of(), "LOGIN"); @@ -369,7 +413,7 @@ void bareLoginPersistsVerifiedFirstPartyAccountWithoutEnqueueingGameplayCommand( new SessionContext( 1L, 22L, - 0L, + null, null, 0L, null, @@ -388,7 +432,7 @@ void bareLoginPersistsVerifiedFirstPartyAccountWithoutEnqueueingGameplayCommand( .thenReturn( Optional.of( new FirstPartyConnectContext( - 99L, + "99", 22L, "demo", "production", @@ -408,7 +452,7 @@ void bareLoginPersistsVerifiedFirstPartyAccountWithoutEnqueueingGameplayCommand( ArgumentCaptor captor = ArgumentCaptor.forClass(SessionContext.class); verify(sessionContextService).save(captor.capture()); SessionContext context = captor.getValue(); - assertEquals(99L, context.accountId()); + assertEquals("99", context.accountId()); assertEquals(1L, context.bootstrapGameInstanceId()); assertEquals(0L, context.gameInstanceId()); assertEquals(0L, context.characterId()); @@ -422,6 +466,125 @@ void bareLoginPersistsVerifiedFirstPartyAccountWithoutEnqueueingGameplayCommand( assertEquals(77L, instance.getOwnerAccountId()); } + @Test + void bareLoginRejectsUnsupportedFirstPartyAccountTextBeforeInstanceLookup() { + TextCommand command = new TextCommand(TextCommandType.LOGIN, List.of(), "LOGIN"); + List unsupportedAccountIds = List.of("0", "-17", "account:opaque"); + for (int index = 0; index < unsupportedAccountIds.size(); index++) { + long sessionId = index + 1L; + stubSessionContext(bootstrapShell(sessionId, 1L)); + when(firstPartyConnectContextRegistry.find(sessionId)) + .thenReturn( + Optional.of( + new FirstPartyConnectContext( + unsupportedAccountIds.get(index), + 22L, + "demo", + "production", + 1L, + 1L, + "scope-1", + "jti-1", + "req-1", + "gateway-1"))); + + LoginCommandHandlingResult result = handler.handle(Long.toString(sessionId), command, false); + + assertFalse(result.commandResult().accepted()); + assertEquals("CONNECT_CONTEXT_INVALID", result.commandResult().errorCode()); + } + + verify(gameInstanceRepository, never()).findById(anyLong()); + verify(gameplayAdmissionPointerAuthorityService, never()) + .listByRuntimeTarget(anyLong(), anyLong()); + ArgumentCaptor captor = ArgumentCaptor.forClass(SessionContext.class); + verify(sessionContextService, times(unsupportedAccountIds.size())).save(captor.capture()); + assertTrue(captor.getAllValues().stream().allMatch(context -> context.accountId() == null)); + verify(firstPartyConnectContextRegistry, never()).unregister(anyLong()); + } + + @Test + void bareLoginRejectsAbsentFirstPartyAccountBeforeInstanceLookup() { + TextCommand command = new TextCommand(TextCommandType.LOGIN, List.of(), "LOGIN"); + String[] absentAccountIds = {null, " "}; + for (int index = 0; index < absentAccountIds.length; index++) { + long sessionId = index + 1L; + stubSessionContext(bootstrapShell(sessionId, 1L)); + when(firstPartyConnectContextRegistry.find(sessionId)) + .thenReturn( + Optional.of( + new FirstPartyConnectContext( + absentAccountIds[index], + 22L, + "demo", + "production", + 1L, + 1L, + "scope-1", + "jti-1", + "req-1", + "gateway-1"))); + + LoginCommandHandlingResult result = handler.handle(Long.toString(sessionId), command, false); + + assertFalse(result.commandResult().accepted()); + assertEquals("CONNECT_CONTEXT_INVALID", result.commandResult().errorCode()); + } + + verify(gameInstanceRepository, never()).findById(anyLong()); + ArgumentCaptor captor = ArgumentCaptor.forClass(SessionContext.class); + verify(sessionContextService, times(absentAccountIds.length)).save(captor.capture()); + assertTrue(captor.getAllValues().stream().allMatch(context -> context.accountId() == null)); + verify(firstPartyConnectContextRegistry, never()).unregister(anyLong()); + } + + @Test + void bareLoginRejectsOpaqueFirstPartyAccountWithoutClearingExistingOwnerAlias() { + TextCommand command = new TextCommand(TextCommandType.LOGIN, List.of(), "LOGIN"); + String accountId = "acct:opaque/legacy"; + stubSessionContext( + new SessionContext( + 1L, + 22L, + accountId, + null, + 0L, + null, + 0L, + null, + null, + "en-NZ", + 1L, + "demo", + "production", + 1L, + null, + "scope-1", + "req-1")); + when(firstPartyConnectContextRegistry.find(1L)) + .thenReturn( + Optional.of( + new FirstPartyConnectContext( + accountId, + 22L, + "demo", + "production", + 1L, + 1L, + "scope-1", + "jti-1", + "req-1", + "gateway-1"))); + + LoginCommandHandlingResult result = handler.handle("1", command, false); + + assertFalse(result.commandResult().accepted()); + assertEquals("CONNECT_CONTEXT_INVALID", result.commandResult().errorCode()); + verify(gameInstanceRepository, never()).findById(anyLong()); + verify(sessionContextService, never()).save(any(SessionContext.class)); + verify(firstPartyConnectContextRegistry, never()).unregister(anyLong()); + } + @Test void credentialLoginAsDifferentAccountInvalidatesFirstPartyContextBeforeBareLogin() { TextCommand bareLogin = new TextCommand(TextCommandType.LOGIN, List.of(), "LOGIN"); @@ -433,7 +596,7 @@ void credentialLoginAsDifferentAccountInvalidatesFirstPartyContextBeforeBareLogi GameInstance instance = buildInstance(1L, 22L, 77L); FirstPartyConnectContext accountAContext = new FirstPartyConnectContext( - 99L, 22L, "demo", "production", 1L, 1L, "scope-1", "jti-1", "req-1", "gateway-1"); + "99", 22L, "demo", "production", 1L, 1L, "scope-1", "jti-1", "req-1", "gateway-1"); AtomicBoolean accountAContextRegistered = new AtomicBoolean(true); List registryEvents = new java.util.ArrayList<>(); Mockito.doAnswer( @@ -469,23 +632,23 @@ void credentialLoginAsDifferentAccountInvalidatesFirstPartyContextBeforeBareLogi List.of("find-account-a", "find-account-a", "unregister", "find-empty"), registryEvents); ArgumentCaptor captor = ArgumentCaptor.forClass(SessionContext.class); verify(sessionContextService, times(3)).save(captor.capture()); - assertEquals(99L, captor.getAllValues().get(0).accountId()); - assertEquals(77L, captor.getAllValues().get(1).accountId()); + assertEquals("99", captor.getAllValues().get(0).accountId()); + assertEquals("77", captor.getAllValues().get(1).accountId()); assertEquals("demo@example.com", captor.getAllValues().get(1).loginName()); assertEquals(AUTH_TOKEN, captor.getAllValues().get(1).jwt()); - assertEquals(0L, captor.getAllValues().get(2).accountId()); + assertEquals(null, captor.getAllValues().get(2).accountId()); } @Test void staleFirstPartyRegistryCannotReplacePersistedCredentialIdentity() { SessionContext credentialIdentity = - new SessionContext(1L, 22L, 77L, "demo@example.com", 0L, null, 0L, "mock-jwt"); + new SessionContext(1L, 22L, "77", "demo@example.com", 0L, null, 0L, "mock-jwt"); stubSessionContext(credentialIdentity); when(firstPartyConnectContextRegistry.find(1L)) .thenReturn( Optional.of( new FirstPartyConnectContext( - 99L, + "99", 22L, "demo", "production", @@ -514,7 +677,7 @@ void bareLoginFallsBackToPersistedFirstPartyContextWhenRegistryEntryIsMissing() new SessionContext( 1L, 22L, - 77L, + "77", null, 0L, null, @@ -547,7 +710,7 @@ void bareLoginRejectsIncompletePersistedFirstPartyContextWhenRegistryEntryIsMiss new SessionContext( 1L, 22L, - 77L, + "77", null, 0L, null, @@ -583,7 +746,7 @@ void bareLoginDoesNotFallBackToRawPersistedFirstPartyContextWhenTenantScopedSess new SessionContext( 1L, 22L, - 77L, + "77", null, 0L, null, @@ -616,7 +779,7 @@ void bareLoginDoesNotProceedWhenCurrentAdmissionPointerTenantIsInvalid() { .thenReturn( Optional.of( new FirstPartyConnectContext( - 77L, + "77", 0L, "demo", "production", @@ -641,7 +804,7 @@ void bareLoginDoesNotProceedWhenCurrentAdmissionPointerGameInstanceIdIsInvalid() .thenReturn( Optional.of( new FirstPartyConnectContext( - 77L, + "77", 22L, "demo", "production", @@ -668,7 +831,7 @@ void bareLoginDoesNotProceedWhenCurrentAdmissionPointerWorldOrRealmIsMissing() { .thenReturn( Optional.of( new FirstPartyConnectContext( - 77L, + "77", 22L, " ", "production", @@ -693,7 +856,7 @@ void bareLoginDoesNotProceedWhenCurrentAdmissionPointerRealmIsMissing() { .thenReturn( Optional.of( new FirstPartyConnectContext( - 77L, 22L, "demo", " ", 1L, 1L, "scope-1", "jti-1", "req-1", "gateway-1"))); + "77", 22L, "demo", " ", 1L, 1L, "scope-1", "jti-1", "req-1", "gateway-1"))); when(gameInstanceRepository.findById(1L)).thenReturn(Optional.of(buildInstance(1L, 22L, 77L))); LoginCommandHandlingResult result = handler.handle("1", command, false); @@ -711,7 +874,7 @@ void bareLoginRejectsStalePointerVersion() { .thenReturn( Optional.of( new FirstPartyConnectContext( - 77L, + "77", 22L, "demo", "production", @@ -751,7 +914,7 @@ void successfulLoginStoresSessionContext() { net.firedevops.firemud.gamesession.service.SessionContext context = captor.getValue(); assertEquals(1L, context.sessionId()); assertEquals(22L, context.tenantId()); - assertEquals(77L, context.accountId()); + assertEquals("77", context.accountId()); assertEquals(0L, context.characterId()); assertEquals(0L, context.gameInstanceId()); assertNull(context.roomInstanceId()); @@ -768,7 +931,7 @@ void loginUsesBootstrappedGameInstanceInsteadOfTransportSessionId() { GameInstance instance = buildInstance(99L, 22L, 77L); SessionContext bootstrapContext = - new SessionContext(12345L, 22L, 0L, null, 0L, null, 99L, null, null); + new SessionContext(12345L, 22L, null, null, 0L, null, 99L, null, null); when(sessionContextService.findBySessionId(12345L)).thenReturn(Optional.of(bootstrapContext)); when(sessionContextService.findByTenantAndSessionId(22L, 12345L)) .thenReturn(Optional.of(bootstrapContext)); @@ -816,7 +979,7 @@ void reloginPreservesExistingGameplayBindingForSameSession() { new SessionContext( 1L, 22L, - 77L, + "77", "demo@example.com", 88L, "Sora", @@ -837,7 +1000,7 @@ void reloginPreservesExistingGameplayBindingForSameSession() { new SessionContext( 1L, 22L, - 77L, + "77", "demo@example.com", 88L, "Sora", @@ -860,7 +1023,7 @@ void reloginPreservesExistingGameplayBindingForSameSession() { SessionContext context = captor.getValue(); assertEquals(1L, context.sessionId()); assertEquals(22L, context.tenantId()); - assertEquals(77L, context.accountId()); + assertEquals("77", context.accountId()); assertEquals(88L, context.characterId()); assertEquals(1L, context.gameInstanceId()); assertEquals("R-2045", context.roomInstanceId()); @@ -884,7 +1047,7 @@ void loginAsDifferentAccountClearsCrossTenantProjectedPresenceBeforeSaving() { new SessionContext( 1L, 22L, - 77L, + "77", "demo@example.com", 88L, "Sora", @@ -911,7 +1074,7 @@ void loginAsDifferentAccountClearsCrossTenantProjectedPresenceBeforeSaving() { inOrder.verify(sessionContextService).save(savedContext.capture()); assertEquals(22L, existing.tenantId()); assertEquals(23L, savedContext.getValue().tenantId()); - assertEquals(99L, savedContext.getValue().accountId()); + assertEquals("99", savedContext.getValue().accountId()); assertEquals(0L, savedContext.getValue().characterId()); assertEquals(0L, savedContext.getValue().gameInstanceId()); } @@ -940,10 +1103,10 @@ void loginAsDifferentAccountClearsCrossTenantPresenceAfterProjectionNormalizatio .clearGameplayBinding(clearedContext.capture(), eq("LOGIN_ACCOUNT_CHANGED")); inOrder.verify(sessionContextService).save(savedContext.capture()); assertEquals(22L, clearedContext.getValue().tenantId()); - assertEquals(77L, clearedContext.getValue().accountId()); + assertEquals("77", clearedContext.getValue().accountId()); assertFalse(clearedContext.getValue().hasGameplayBinding()); assertEquals(23L, savedContext.getValue().tenantId()); - assertEquals(99L, savedContext.getValue().accountId()); + assertEquals("99", savedContext.getValue().accountId()); assertEquals(0L, savedContext.getValue().characterId()); assertEquals(0L, savedContext.getValue().gameInstanceId()); } @@ -964,7 +1127,7 @@ void loginAsSameAccountClearsCrossTenantPresenceBeforeSaving() { new SessionContext( 1L, 22L, - 77L, + "77", "demo@example.com", 88L, "Sora", @@ -990,9 +1153,9 @@ void loginAsSameAccountClearsCrossTenantPresenceBeforeSaving() { .clearGameplayBinding(existing, "LOGIN_TENANT_CHANGED"); inOrder.verify(sessionContextService).save(savedContext.capture()); assertEquals(22L, existing.tenantId()); - assertEquals(77L, existing.accountId()); + assertEquals("77", existing.accountId()); assertEquals(23L, savedContext.getValue().tenantId()); - assertEquals(77L, savedContext.getValue().accountId()); + assertEquals("77", savedContext.getValue().accountId()); assertEquals(0L, savedContext.getValue().characterId()); assertEquals(0L, savedContext.getValue().gameInstanceId()); } @@ -1021,10 +1184,10 @@ void loginAsSameAccountClearsCrossTenantPresenceAfterProjectionNormalization() { .clearGameplayBinding(clearedContext.capture(), eq("LOGIN_TENANT_CHANGED")); inOrder.verify(sessionContextService).save(savedContext.capture()); assertEquals(22L, clearedContext.getValue().tenantId()); - assertEquals(77L, clearedContext.getValue().accountId()); + assertEquals("77", clearedContext.getValue().accountId()); assertFalse(clearedContext.getValue().hasGameplayBinding()); assertEquals(23L, savedContext.getValue().tenantId()); - assertEquals(77L, savedContext.getValue().accountId()); + assertEquals("77", savedContext.getValue().accountId()); assertEquals(0L, savedContext.getValue().characterId()); assertEquals(0L, savedContext.getValue().gameInstanceId()); } @@ -1046,7 +1209,7 @@ void reloginAsDifferentAccountClearsExistingGameplayBinding() { new SessionContext( 1L, 22L, - 77L, + "77", "demo@example.com", 88L, "Sora", @@ -1072,7 +1235,7 @@ void reloginAsDifferentAccountClearsExistingGameplayBinding() { .clearGameplayBinding(existing, "LOGIN_ACCOUNT_CHANGED"); inOrder.verify(sessionContextService).save(captor.capture()); SessionContext context = captor.getValue(); - assertEquals(99L, context.accountId()); + assertEquals("99", context.accountId()); assertEquals("other@example.com", context.loginName()); assertEquals(0L, context.characterId()); assertNull(context.characterName()); @@ -1136,7 +1299,7 @@ void reloginClearsStaleGameplayBindingBeforeRefreshingLoginContext() { SessionContext context = captor.getValue(); assertEquals(1L, context.sessionId()); assertEquals(22L, context.tenantId()); - assertEquals(77L, context.accountId()); + assertEquals("77", context.accountId()); assertEquals(0L, context.characterId()); assertNull(context.characterName()); assertEquals(0L, context.gameInstanceId()); @@ -1205,7 +1368,7 @@ void invalidCredentialsDropPartialProjectedRoutingBundleDuringFailedLoginCleanup new SessionContext( 1L, 22L, - 77L, + "77", "demo@example.com", 88L, "Sora", @@ -1252,7 +1415,7 @@ void authenticatedNonOwnerAccountIsAcceptedAndStored() { assertEquals("Logged in as demo@example.com", joinedOutputText(result.outputs())); ArgumentCaptor captor = ArgumentCaptor.forClass(SessionContext.class); verify(sessionContextService).save(captor.capture()); - assertEquals(99L, captor.getValue().accountId()); + assertEquals("99", captor.getValue().accountId()); assertEquals("demo@example.com", captor.getValue().loginName()); assertEquals(77L, instance.getOwnerAccountId()); } @@ -1634,7 +1797,7 @@ private static SessionContext bootstrapShell(long sessionId, long bootstrapGameI return new SessionContext( sessionId, 22L, - 0L, + null, null, 0L, null, @@ -1653,7 +1816,7 @@ private static SessionContext staleGameplayContext(long pointerVersion) { return new SessionContext( 1L, 22L, - 77L, + "77", "demo@example.com", 88L, "Sora", @@ -1674,7 +1837,7 @@ private static SessionContext staleGameplayContextWithoutSelector(long pointerVe return new SessionContext( 1L, 22L, - 77L, + "77", "demo@example.com", 88L, "Sora", @@ -1700,7 +1863,7 @@ private static void assertClearedSessionContext( String expectedConnectRequestId) { assertEquals(1L, context.sessionId()); assertEquals(22L, context.tenantId()); - assertEquals(0L, context.accountId()); + assertEquals(null, context.accountId()); assertNull(context.loginName()); assertEquals(0L, context.characterId()); assertNull(context.characterName()); diff --git a/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/command/text/LogoutCommandHandlerTest.java b/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/command/text/LogoutCommandHandlerTest.java index a2175fe179..a33d26a7e1 100644 --- a/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/command/text/LogoutCommandHandlerTest.java +++ b/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/command/text/LogoutCommandHandlerTest.java @@ -51,7 +51,7 @@ void logoutPreservesDurableReplayContextWithoutStoppingSharedRuntime() { new SessionContext( 41L, 22L, - 123L, + "123", "demo@example.com", 123L, "demo", @@ -88,7 +88,7 @@ void logoutStopsIsolatedRuntime() { new SessionContext( 41L, 22L, - 123L, + "123", "demo@example.com", 123L, "demo", @@ -115,7 +115,7 @@ void logoutDoesNotStopSharedRuntimeWhenCurrentRuntimeAuthorityIsShared() { new SessionContext( 41L, 22L, - 123L, + "123", "demo@example.com", 123L, "demo", @@ -158,7 +158,7 @@ void logoutDoesNotStopSharedRuntimeWhenNormalizationClearsProjectedBinding() { new SessionContext( 41L, 22L, - 123L, + "123", "demo@example.com", 123L, "demo", @@ -186,7 +186,7 @@ void logoutDoesNotStopRuntimeWhenPointerAuthorityIsUnknown() { new SessionContext( 41L, 22L, - 123L, + "123", "demo@example.com", 123L, "demo", @@ -215,7 +215,7 @@ void logoutDoesNotStopRuntimeWhenCurrentRuntimeAuthorityIsAmbiguous() { new SessionContext( 41L, 22L, - 123L, + "123", "demo@example.com", 123L, "demo", @@ -271,7 +271,7 @@ void logoutDoesNotStopRuntimeWhenSingularRuntimeAuthorityIsIncomplete() { new SessionContext( 41L, 22L, - 123L, + "123", "demo@example.com", 123L, "demo", @@ -314,7 +314,7 @@ void logoutSkipsGameplayCleanupForPartialGameplayShell() { new SessionContext( 41L, 22L, - 123L, + "123", "demo@example.com", 123L, "demo", diff --git a/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/command/text/LookCommandHandlerTest.java b/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/command/text/LookCommandHandlerTest.java index 180d6e8d3b..a2bf9448da 100644 --- a/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/command/text/LookCommandHandlerTest.java +++ b/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/command/text/LookCommandHandlerTest.java @@ -54,7 +54,7 @@ class LookCommandHandlerTest { lookCacheService, outputRenderer); private final SessionContext sessionContext = - new SessionContext(1L, 22L, 123L, 911L, 0L, "R-42", "jwt"); + new SessionContext(1L, 22L, "123", 911L, 0L, "R-42", "jwt"); private final LookResult lookResult = LookResult.newBuilder() .setRoomInstance(RoomInstanceRef.newBuilder().setRoomInstanceId("R-1021").build()) @@ -217,7 +217,7 @@ void quickLookUsesSharedLookupButShorterRenderVariant() { @Test void cachesRenderedLookByGameplayInstanceWhenAvailable() { SessionContext playedContext = - new SessionContext(17L, 22L, 123L, "demo", 911L, "demo", 77L, "R-42", "jwt"); + new SessionContext(17L, 22L, "123", "demo", 911L, "demo", 77L, "R-42", "jwt"); when(sessionAuthenticationService.resolveSessionContext("played")) .thenReturn(Optional.of(playedContext)); when(gameLogicClient.resolveLook(playedContext, "R-42", "")).thenReturn(lookResult); diff --git a/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/command/text/MoveCommandHandlerTest.java b/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/command/text/MoveCommandHandlerTest.java index a69f16082f..f3ebe061c0 100644 --- a/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/command/text/MoveCommandHandlerTest.java +++ b/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/command/text/MoveCommandHandlerTest.java @@ -58,7 +58,7 @@ void setUp() { meterRegistry); context = new SessionContext( - 42L, 22L, 123L, "emberline@example.com", 911L, "Emberline", 7L, "R-1021", "jwt-token"); + 42L, 22L, "123", "emberline@example.com", 911L, "Emberline", 7L, "R-1021", "jwt-token"); } @Test diff --git a/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/command/text/PlayCommandHandlerTest.java b/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/command/text/PlayCommandHandlerTest.java index bc6c04ede6..87959b400f 100644 --- a/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/command/text/PlayCommandHandlerTest.java +++ b/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/command/text/PlayCommandHandlerTest.java @@ -161,7 +161,7 @@ void setUp() { @Test void playPromotesSessionIntoGameplay() { SessionContext context = - new SessionContext(1L, 22L, 123L, "demo@example.com", 0L, null, 0L, "jwt-token"); + new SessionContext(1L, 22L, "123", "demo@example.com", 0L, null, 0L, "jwt-token"); when(sessionAuthenticationService.resolveSessionContext("1")).thenReturn(Optional.of(context)); when(sessionAuthenticationService.resolveByGameplayIdentity(22L, 1L, 7001L)) .thenReturn(Optional.empty()); @@ -176,7 +176,7 @@ void playPromotesSessionIntoGameplay() { new SessionContext( 1L, 22L, - 123L, + "123", "demo@example.com", 7001L, "demo", @@ -194,7 +194,7 @@ void playPromotesSessionIntoGameplay() { new SessionContext( 1L, 22L, - 123L, + "123", "demo@example.com", 7001L, "demo", @@ -212,7 +212,7 @@ void playPromotesSessionIntoGameplay() { new SessionContext( 1L, 22L, - 123L, + "123", "demo@example.com", 7001L, "demo", @@ -231,7 +231,7 @@ void playPromotesSessionIntoGameplay() { new SessionContext( 1L, 22L, - 123L, + "123", "demo@example.com", 7001L, "demo", @@ -270,7 +270,7 @@ void playFailsClosedWhenTenantHasMultiplePublicProductionRealmsAcrossWorlds() { .getFirst() .setPublicProductionRealm(true); SessionContext context = - new SessionContext(1L, 22L, 123L, "demo@example.com", 0L, null, 0L, "jwt-token"); + new SessionContext(1L, 22L, "123", "demo@example.com", 0L, null, 0L, "jwt-token"); when(sessionAuthenticationService.resolveSessionContext("1")).thenReturn(Optional.of(context)); PlayCommandHandlingResult ambiguousDefaultResult = @@ -301,7 +301,7 @@ void playFailsClosedWhenTenantHasNoPublicProductionRealm() { .getFirst() .setPublicProductionRealm(false); SessionContext context = - new SessionContext(1L, 22L, 123L, "demo@example.com", 0L, null, 0L, "jwt-token"); + new SessionContext(1L, 22L, "123", "demo@example.com", 0L, null, 0L, "jwt-token"); when(sessionAuthenticationService.resolveSessionContext("1")).thenReturn(Optional.of(context)); PlayCommandHandlingResult result = @@ -353,7 +353,7 @@ void playUsesSelectedTenantAuthorityWhenAnotherTenantHasNoPublicProductionRealm( "Maintenance World", List.of(realm("maintenance", "Maintenance Realm", 23L, 99L, true, false)))); SessionContext context = - new SessionContext(1L, 22L, 123L, "demo@example.com", 0L, null, 0L, "jwt-token"); + new SessionContext(1L, 22L, "123", "demo@example.com", 0L, null, 0L, "jwt-token"); when(sessionAuthenticationService.resolveSessionContext("1")).thenReturn(Optional.of(context)); when(sessionAuthenticationService.resolveByGameplayIdentity(22L, 1L, 7001L)) .thenReturn(Optional.empty()); @@ -388,7 +388,7 @@ void playStillRejectsSelectedTenantWithoutPublicProductionRealm() { "Other Public World", List.of(realm("production", "Live Realm", 23L, 99L, true, false)))); SessionContext context = - new SessionContext(1L, 22L, 123L, "demo@example.com", 0L, null, 0L, "jwt-token"); + new SessionContext(1L, 22L, "123", "demo@example.com", 0L, null, 0L, "jwt-token"); when(sessionAuthenticationService.resolveSessionContext("1")).thenReturn(Optional.of(context)); PlayCommandHandlingResult result = @@ -406,7 +406,7 @@ void playStillRejectsSelectedTenantWithoutPublicProductionRealm() { @Test void playRejectsModerationPolicyDeniedAdmission() { SessionContext context = - new SessionContext(1L, 22L, 123L, "demo@example.com", 0L, null, 0L, "jwt-token"); + new SessionContext(1L, 22L, "123", "demo@example.com", 0L, null, 0L, "jwt-token"); when(sessionAuthenticationService.resolveSessionContext("1")).thenReturn(Optional.of(context)); when(moderationPolicyClient.evaluateGameplayAdmission(22L, 123L)) .thenReturn( @@ -428,7 +428,7 @@ void playRejectsModerationPolicyDeniedAdmission() { @Test void playUsesPersistedAccountRosterCharacterForSelectedTarget() { SessionContext context = - new SessionContext(1L, 22L, 123L, "demo@example.com", 0L, null, 0L, "jwt-token"); + new SessionContext(1L, 22L, "123", "demo@example.com", 0L, null, 0L, "jwt-token"); when(sessionAuthenticationService.resolveSessionContext("1")).thenReturn(Optional.of(context)); when(sessionAuthenticationService.resolveByGameplayIdentity(22L, 2L, 9007L)) .thenReturn(Optional.empty()); @@ -447,7 +447,7 @@ void playUsesPersistedAccountRosterCharacterForSelectedTarget() { new SessionContext( 1L, 22L, - 123L, + "123", "demo@example.com", 9007L, "Emberline", @@ -465,7 +465,7 @@ void playUsesPersistedAccountRosterCharacterForSelectedTarget() { new SessionContext( 1L, 22L, - 123L, + "123", "demo@example.com", 9007L, "Emberline", @@ -485,7 +485,7 @@ void playUsesPersistedAccountRosterCharacterForSelectedTarget() { new SessionContext( 1L, 22L, - 123L, + "123", "demo@example.com", 9007L, "Emberline", @@ -505,7 +505,7 @@ void playUsesPersistedAccountRosterCharacterForSelectedTarget() { @Test void playWithoutCharacterSelectorShowsPersistedRosterCharacterName() { SessionContext context = - new SessionContext(1L, 22L, 123L, "demo@example.com", 0L, null, 0L, "jwt-token"); + new SessionContext(1L, 22L, "123", "demo@example.com", 0L, null, 0L, "jwt-token"); when(sessionAuthenticationService.resolveSessionContext("1")).thenReturn(Optional.of(context)); when(sessionAuthenticationService.resolveByGameplayIdentity(22L, 1L, 7001L)) .thenReturn(Optional.empty()); @@ -525,7 +525,7 @@ void playWithoutCharacterSelectorShowsPersistedRosterCharacterName() { @Test void playWithCaseVariedCharacterSelectorShowsPersistedRosterCharacterName() { SessionContext context = - new SessionContext(1L, 22L, 123L, "demo@example.com", 0L, null, 0L, "jwt-token"); + new SessionContext(1L, 22L, "123", "demo@example.com", 0L, null, 0L, "jwt-token"); when(sessionAuthenticationService.resolveSessionContext("1")).thenReturn(Optional.of(context)); when(sessionAuthenticationService.resolveByGameplayIdentity(22L, 1L, 7001L)) .thenReturn(Optional.empty()); @@ -548,7 +548,7 @@ void playWithCaseVariedCharacterSelectorShowsPersistedRosterCharacterName() { @Test void playRejectsMalformedPersistedRosterCharacterId() { SessionContext context = - new SessionContext(1L, 22L, 123L, "demo@example.com", 0L, null, 0L, "jwt-token"); + new SessionContext(1L, 22L, "123", "demo@example.com", 0L, null, 0L, "jwt-token"); when(sessionAuthenticationService.resolveSessionContext("1")).thenReturn(Optional.of(context)); when(entityManagementClient.listCharactersByAccount( "22", "123", "2", PlayableStateScope.PLAYABLE_STATE_SCOPE_SHARED)) @@ -580,7 +580,7 @@ void playRejectsMalformedPersistedRosterCharacterId() { @Test void playRejectsCharacterRosterFromAnotherAccountBeforeBinding() { SessionContext context = - new SessionContext(1L, 22L, 123L, "demo@example.com", 0L, null, 0L, "jwt-token"); + new SessionContext(1L, 22L, "123", "demo@example.com", 0L, null, 0L, "jwt-token"); when(sessionAuthenticationService.resolveSessionContext("1")).thenReturn(Optional.of(context)); when(entityManagementClient.listCharactersByAccount( "22", "123", "1", PlayableStateScope.PLAYABLE_STATE_SCOPE_SHARED)) @@ -599,7 +599,7 @@ void playRejectsCharacterRosterFromAnotherAccountBeforeBinding() { @Test void playRejectsCharacterRosterFromAnotherTenantBeforeBinding() { SessionContext context = - new SessionContext(1L, 22L, 123L, "demo@example.com", 0L, null, 0L, "jwt-token"); + new SessionContext(1L, 22L, "123", "demo@example.com", 0L, null, 0L, "jwt-token"); when(sessionAuthenticationService.resolveSessionContext("1")).thenReturn(Optional.of(context)); when(entityManagementClient.listCharactersByAccount( "22", "123", "1", PlayableStateScope.PLAYABLE_STATE_SCOPE_SHARED)) @@ -618,7 +618,7 @@ void playRejectsCharacterRosterFromAnotherTenantBeforeBinding() { @Test void playRejectsDuplicatePersistedCharacterIdsBeforeBinding() { SessionContext context = - new SessionContext(1L, 22L, 123L, "demo@example.com", 0L, null, 0L, "jwt-token"); + new SessionContext(1L, 22L, "123", "demo@example.com", 0L, null, 0L, "jwt-token"); when(sessionAuthenticationService.resolveSessionContext("1")).thenReturn(Optional.of(context)); ListCharactersByAccountResponse roster = characterRoster("8008", "demo", "22", "123", PlayableStateScope.PLAYABLE_STATE_SCOPE_SHARED) @@ -647,7 +647,7 @@ void playRejectsDuplicatePersistedCharacterIdsBeforeBinding() { @Test void playWithAmbiguousCharacterNameReturnsSelectionGuidanceBeforeBinding() { SessionContext context = - new SessionContext(1L, 22L, 123L, "demo@example.com", 0L, null, 0L, "jwt-token"); + new SessionContext(1L, 22L, "123", "demo@example.com", 0L, null, 0L, "jwt-token"); when(sessionAuthenticationService.resolveSessionContext("1")).thenReturn(Optional.of(context)); ListCharactersByAccountResponse roster = characterRoster("8008", "demo", "22", "123", PlayableStateScope.PLAYABLE_STATE_SCOPE_SHARED) @@ -675,7 +675,7 @@ void playWithAmbiguousCharacterNameReturnsSelectionGuidanceBeforeBinding() { @Test void playWithEmptyCharacterRosterReturnsSelectionGuidanceBeforeBinding() { SessionContext context = - new SessionContext(1L, 22L, 123L, "demo@example.com", 0L, null, 0L, "jwt-token"); + new SessionContext(1L, 22L, "123", "demo@example.com", 0L, null, 0L, "jwt-token"); when(sessionAuthenticationService.resolveSessionContext("1")).thenReturn(Optional.of(context)); when(entityManagementClient.listCharactersByAccount( "22", "123", "1", PlayableStateScope.PLAYABLE_STATE_SCOPE_SHARED)) @@ -691,7 +691,7 @@ void playWithEmptyCharacterRosterReturnsSelectionGuidanceBeforeBinding() { @Test void playWithoutCharacterSelectorReturnsSelectionGuidanceForMultipleCharacters() { SessionContext context = - new SessionContext(1L, 22L, 123L, "demo@example.com", 0L, null, 0L, "jwt-token"); + new SessionContext(1L, 22L, "123", "demo@example.com", 0L, null, 0L, "jwt-token"); when(sessionAuthenticationService.resolveSessionContext("1")).thenReturn(Optional.of(context)); ListCharactersByAccountResponse roster = characterRoster("8008", "demo", "22", "123", PlayableStateScope.PLAYABLE_STATE_SCOPE_SHARED) @@ -719,7 +719,7 @@ void playWithoutCharacterSelectorReturnsSelectionGuidanceForMultipleCharacters() @Test void playWithUnmatchedCharacterSelectorReturnsGuidanceBeforeBinding() { SessionContext context = - new SessionContext(1L, 22L, 123L, "demo@example.com", 0L, null, 0L, "jwt-token"); + new SessionContext(1L, 22L, "123", "demo@example.com", 0L, null, 0L, "jwt-token"); when(sessionAuthenticationService.resolveSessionContext("1")).thenReturn(Optional.of(context)); PlayCommandHandlingResult result = @@ -734,7 +734,7 @@ void playWithUnmatchedCharacterSelectorReturnsGuidanceBeforeBinding() { @Test void playRejectsUnavailableCharacterRosterBeforeBinding() { SessionContext context = - new SessionContext(1L, 22L, 123L, "demo@example.com", 0L, null, 0L, "jwt-token"); + new SessionContext(1L, 22L, "123", "demo@example.com", 0L, null, 0L, "jwt-token"); when(sessionAuthenticationService.resolveSessionContext("1")).thenReturn(Optional.of(context)); when(entityManagementClient.listCharactersByAccount( "22", "123", "1", PlayableStateScope.PLAYABLE_STATE_SCOPE_SHARED)) @@ -760,7 +760,7 @@ void playResumeDoesNotPublishSpawnEvent() { new SessionContext( 1L, 22L, - 123L, + "123", "demo@example.com", 7001L, "Emberline", @@ -798,9 +798,9 @@ void playResumeDoesNotPublishSpawnEvent() { @Test void playIgnoresStaleExistingBindingAfterNormalization() { SessionContext context = - new SessionContext(1L, 22L, 123L, "demo@example.com", 0L, null, 0L, "jwt-token"); + new SessionContext(1L, 22L, "123", "demo@example.com", 0L, null, 0L, "jwt-token"); SessionContext clearedExisting = - new SessionContext(9L, 22L, 123L, "demo@example.com", 0L, null, 0L, null, "old-jwt", 1L); + new SessionContext(9L, 22L, "123", "demo@example.com", 0L, null, 0L, null, "old-jwt", 1L); when(sessionAuthenticationService.resolveSessionContext("1")).thenReturn(Optional.of(context)); when(sessionAuthenticationService.resolveByGameplayIdentity(22L, 1L, 7001L)) .thenReturn(Optional.of(clearedExisting)); @@ -815,7 +815,7 @@ void playIgnoresStaleExistingBindingAfterNormalization() { new SessionContext( 1L, 22L, - 123L, + "123", "demo@example.com", 7001L, "demo", @@ -837,12 +837,12 @@ void playIgnoresStaleExistingBindingAfterNormalization() { @Test void playIgnoresExistingBindingWithoutRoomRegion() { SessionContext context = - new SessionContext(1L, 22L, 123L, "demo@example.com", 0L, null, 0L, "jwt-token"); + new SessionContext(1L, 22L, "123", "demo@example.com", 0L, null, 0L, "jwt-token"); SessionContext existingWithoutRoom = new SessionContext( 9L, 22L, - 123L, + "123", "demo@example.com", 7001L, "demo", @@ -869,7 +869,7 @@ void playIgnoresExistingBindingWithoutRoomRegion() { new SessionContext( 1L, 22L, - 123L, + "123", "demo@example.com", 7001L, "demo", @@ -890,13 +890,13 @@ void playIgnoresExistingBindingWithoutRoomRegion() { @Test void firstPartyPlayRejectsMismatchedConnectScope() { SessionContext context = - new SessionContext(1L, 22L, 123L, "first-party:123", 0L, null, 0L, null, null, 41L); + new SessionContext(1L, 22L, "123", "first-party:123", 0L, null, 0L, null, null, 41L); when(sessionAuthenticationService.resolveSessionContext("1")).thenReturn(Optional.of(context)); when(firstPartyConnectContextRegistry.find(1L)) .thenReturn( Optional.of( new FirstPartyConnectContext( - 123L, + "123", 22L, "demo", "production", @@ -922,13 +922,13 @@ void firstPartyPlayRejectsMismatchedConnectScope() { @Test void firstPartyPlayRejectsMismatchedWorldSlug() { SessionContext context = - new SessionContext(1L, 22L, 123L, "first-party:123", 0L, null, 0L, null, null, 1L); + new SessionContext(1L, 22L, "123", "first-party:123", 0L, null, 0L, null, null, 1L); when(sessionAuthenticationService.resolveSessionContext("1")).thenReturn(Optional.of(context)); when(firstPartyConnectContextRegistry.find(1L)) .thenReturn( Optional.of( new FirstPartyConnectContext( - 123L, + "123", 22L, "sandbox", "production", @@ -950,13 +950,22 @@ void firstPartyPlayRejectsMismatchedWorldSlug() { void firstPartyPlayRejectsStalePointerVersion() { gameplayCatalogProperties.getWorlds().get(0).getRealms().get(0).setPointerVersion(9L); SessionContext context = - new SessionContext(1L, 22L, 123L, "first-party:123", 0L, null, 0L, null, null, 1L); + new SessionContext(1L, 22L, "123", "first-party:123", 0L, null, 0L, null, null, 1L); when(sessionAuthenticationService.resolveSessionContext("1")).thenReturn(Optional.of(context)); when(firstPartyConnectContextRegistry.find(1L)) .thenReturn( Optional.of( new FirstPartyConnectContext( - 123L, 22L, "demo", "production", 1L, 8L, "scope-1", "jti-1", "req-1", "gw-1"))); + "123", + 22L, + "demo", + "production", + 1L, + 8L, + "scope-1", + "jti-1", + "req-1", + "gw-1"))); PlayCommandHandlingResult result = handler.handle("1", new TextCommand(TextCommandType.PLAY, List.of("demo"), "PLAY demo")); @@ -968,13 +977,13 @@ void firstPartyPlayRejectsStalePointerVersion() { @Test void firstPartyPlayRejectsConnectContextMissingRealmSlug() { SessionContext context = - new SessionContext(1L, 22L, 123L, "first-party:123", 0L, null, 0L, null, null, 1L); + new SessionContext(1L, 22L, "123", "first-party:123", 0L, null, 0L, null, null, 1L); when(sessionAuthenticationService.resolveSessionContext("1")).thenReturn(Optional.of(context)); when(firstPartyConnectContextRegistry.find(1L)) .thenReturn( Optional.of( new FirstPartyConnectContext( - 123L, 22L, "demo", null, 1L, 1L, "scope-1", "jti-1", "req-1", "gw-1"))); + "123", 22L, "demo", null, 1L, 1L, "scope-1", "jti-1", "req-1", "gw-1"))); PlayCommandHandlingResult result = handler.handle("1", new TextCommand(TextCommandType.PLAY, List.of("demo"), "PLAY demo")); @@ -988,13 +997,13 @@ void firstPartyPlayRejectsConnectContextMissingRealmSlug() { @Test void firstPartyPlayRejectsConnectContextMissingConnectScope() { SessionContext context = - new SessionContext(1L, 22L, 123L, "first-party:123", 0L, null, 0L, null, null, 1L); + new SessionContext(1L, 22L, "123", "first-party:123", 0L, null, 0L, null, null, 1L); when(sessionAuthenticationService.resolveSessionContext("1")).thenReturn(Optional.of(context)); when(firstPartyConnectContextRegistry.find(1L)) .thenReturn( Optional.of( new FirstPartyConnectContext( - 123L, 22L, "demo", "production", 1L, 1L, "", "jti-1", "req-1", "gw-1"))); + "123", 22L, "demo", "production", 1L, 1L, "", "jti-1", "req-1", "gw-1"))); PlayCommandHandlingResult result = handler.handle("1", new TextCommand(TextCommandType.PLAY, List.of("demo"), "PLAY demo")); @@ -1006,13 +1015,13 @@ void firstPartyPlayRejectsConnectContextMissingConnectScope() { @Test void firstPartyPlayRejectsConnectContextMissingConnectRequest() { SessionContext context = - new SessionContext(1L, 22L, 123L, "first-party:123", 0L, null, 0L, null, null, 1L); + new SessionContext(1L, 22L, "123", "first-party:123", 0L, null, 0L, null, null, 1L); when(sessionAuthenticationService.resolveSessionContext("1")).thenReturn(Optional.of(context)); when(firstPartyConnectContextRegistry.find(1L)) .thenReturn( Optional.of( new FirstPartyConnectContext( - 123L, 22L, "demo", "production", 1L, 1L, "scope-1", "jti-1", "", "gw-1"))); + "123", 22L, "demo", "production", 1L, 1L, "scope-1", "jti-1", "", "gw-1"))); PlayCommandHandlingResult result = handler.handle("1", new TextCommand(TextCommandType.PLAY, List.of("demo"), "PLAY demo")); @@ -1034,7 +1043,7 @@ void playWithoutSessionReturnsLoginRequired() { @Test void playWithoutArgumentsReturnsInvalidArgument() { - SessionContext context = new SessionContext(1L, 22L, 123L, 0L, 0L, "jwt-token"); + SessionContext context = new SessionContext(1L, 22L, "123", 0L, 0L, "jwt-token"); when(sessionAuthenticationService.resolveSessionContext("1")).thenReturn(Optional.of(context)); PlayCommandHandlingResult result = @@ -1046,7 +1055,7 @@ void playWithoutArgumentsReturnsInvalidArgument() { @Test void unknownWorldReturnsSelectionGuidance() { - SessionContext context = new SessionContext(1L, 22L, 123L, 0L, 0L, "jwt-token"); + SessionContext context = new SessionContext(1L, 22L, "123", 0L, 0L, "jwt-token"); when(sessionAuthenticationService.resolveSessionContext("1")).thenReturn(Optional.of(context)); PlayCommandHandlingResult result = @@ -1095,7 +1104,7 @@ void playDoesNotAdmitV6QuarantinedPointerWithoutCatalogIdentity() { gameplayPresenceLifecycleService, scriptEventPublisher, meterRegistry); - SessionContext context = new SessionContext(1L, 22L, 123L, 0L, 0L, "jwt-token"); + SessionContext context = new SessionContext(1L, 22L, "123", 0L, 0L, "jwt-token"); when(sessionAuthenticationService.resolveSessionContext("1")).thenReturn(Optional.of(context)); PlayCommandHandlingResult result = @@ -1150,7 +1159,7 @@ void retainedPointerWithUnknownStateScopeCannotBindOrSpawn() { scriptEventPublisher, meterRegistry); SessionContext context = - new SessionContext(1L, 22L, 123L, "demo@example.com", 0L, null, 0L, "jwt-token"); + new SessionContext(1L, 22L, "123", "demo@example.com", 0L, null, 0L, "jwt-token"); when(sessionAuthenticationService.resolveSessionContext("1")).thenReturn(Optional.of(context)); PlayCommandHandlingResult result = @@ -1168,7 +1177,7 @@ void retainedPointerWithUnknownStateScopeCannotBindOrSpawn() { @Test void sandboxWithoutCharacterReturnsSelectionRequired() { - SessionContext context = new SessionContext(1L, 22L, 123L, 0L, 0L, "jwt-token"); + SessionContext context = new SessionContext(1L, 22L, "123", 0L, 0L, "jwt-token"); when(sessionAuthenticationService.resolveSessionContext("1")).thenReturn(Optional.of(context)); PlayCommandHandlingResult result = @@ -1189,7 +1198,7 @@ void sandboxWithoutCharacterReturnsSelectionRequired() { @Test void explicitRealmWithoutCharacterReturnsCharacterSelectionGuidance() { - SessionContext context = new SessionContext(1L, 22L, 123L, 0L, 0L, "jwt-token"); + SessionContext context = new SessionContext(1L, 22L, "123", 0L, 0L, "jwt-token"); when(sessionAuthenticationService.resolveSessionContext("1")).thenReturn(Optional.of(context)); PlayCommandHandlingResult result = @@ -1219,7 +1228,7 @@ void playRejectsIsolatedStateRealm() { .getRealms() .get(1) .setCharacterCreationPolicy(GameplayCatalogProperties.CharacterCreationPolicy.COPIED_ONLY); - SessionContext context = new SessionContext(1L, 22L, 123L, 0L, 0L, "jwt-token"); + SessionContext context = new SessionContext(1L, 22L, "123", 0L, 0L, "jwt-token"); when(sessionAuthenticationService.resolveSessionContext("1")).thenReturn(Optional.of(context)); PlayCommandHandlingResult result = @@ -1242,13 +1251,13 @@ void firstPartyPlayAcceptsNonProductionRealmWhenScopeMatches() { .get(1) .setStateScope(GameplayCatalogProperties.RealmStateScope.ISOLATED); SessionContext context = - new SessionContext(1L, 22L, 123L, "first-party:123", 0L, null, 0L, null, null, 41L); + new SessionContext(1L, 22L, "123", "first-party:123", 0L, null, 0L, null, null, 41L); when(sessionAuthenticationService.resolveSessionContext("1")).thenReturn(Optional.of(context)); when(firstPartyConnectContextRegistry.find(1L)) .thenReturn( Optional.of( new FirstPartyConnectContext( - 123L, 22L, "sandbox", "preview", 41L, 1L, "scope-1", "jti-1", "req-1", + "123", 22L, "sandbox", "preview", 41L, 1L, "scope-1", "jti-1", "req-1", "gw-1"))); when(entityManagementClient.listCharactersByAccount( "22", "123", "41", PlayableStateScope.PLAYABLE_STATE_SCOPE_ISOLATED)) @@ -1281,7 +1290,7 @@ void firstPartyPlayFallsBackToPersistedSelectorWhenRegistryEntryIsMissing() { new SessionContext( 1L, 22L, - 123L, + "123", "first-party:123", 0L, null, @@ -1325,7 +1334,7 @@ void firstPartyPlayRejectsIncompletePersistedSelectorWhenRegistryEntryIsMissing( new SessionContext( 1L, 22L, - 123L, + "123", "first-party:123", 0L, null, @@ -1360,7 +1369,8 @@ void firstPartyPlayRejectsIncompletePersistedSelectorWhenRegistryEntryIsMissing( @Test void playDeniedByMembershipReturnsWorldAccessDenied() { SessionContext context = - new SessionContext(1L, 22L, 123L, "demo@example.com", 123L, "demo", 1L, "R-1", "jwt-token"); + new SessionContext( + 1L, 22L, "123", "demo@example.com", 123L, "demo", 1L, "R-1", "jwt-token"); when(sessionAuthenticationService.resolveSessionContext("1")).thenReturn(Optional.of(context)); when(accountClient.getTenantMembershipForRuntime( Mockito.anyString(), Mockito.anyString(), Mockito.anyString())) @@ -1398,7 +1408,7 @@ void playDeniedDoesNotClearCrossTenantBindingForSameVisibleRealm() { new SessionContext( 1L, 23L, - 123L, + "123", "demo@example.com", 7001L, "demo", @@ -1441,7 +1451,8 @@ void playDeniedDoesNotClearCrossTenantBindingForSameVisibleRealm() { @Test void playNonPublicRealmRequiresExistingAdmissibleMembership() { SessionContext context = - new SessionContext(1L, 22L, 123L, "demo@example.com", 123L, "demo", 1L, "R-1", "jwt-token"); + new SessionContext( + 1L, 22L, "123", "demo@example.com", 123L, "demo", 1L, "R-1", "jwt-token"); when(sessionAuthenticationService.resolveSessionContext("1")).thenReturn(Optional.of(context)); when(accountClient.getTenantMembershipForRuntime( Mockito.anyString(), Mockito.anyString(), Mockito.anyString())) @@ -1604,7 +1615,8 @@ void playInvisibleRealmWithUnavailableGrantFailsClosed() { @ValueSource(strings = {"NOT_FOUND", "PERMISSION_DENIED"}) void playNonAuthorityMembershipErrorReturnsAccessDeniedAndClearsBinding(String errorCode) { SessionContext context = - new SessionContext(1L, 22L, 123L, "demo@example.com", 123L, "demo", 1L, "R-1", "jwt-token"); + new SessionContext( + 1L, 22L, "123", "demo@example.com", 123L, "demo", 1L, "R-1", "jwt-token"); when(sessionAuthenticationService.resolveSessionContext("1")).thenReturn(Optional.of(context)); when(accountClient.getTenantMembershipForRuntime( Mockito.anyString(), Mockito.anyString(), Mockito.anyString())) @@ -1630,7 +1642,8 @@ void playNonAuthorityMembershipErrorReturnsAccessDeniedAndClearsBinding(String e @Test void playRequiresExplicitJoinWhenPublicProductionMembershipIsMissing() { SessionContext context = - new SessionContext(1L, 22L, 123L, "demo@example.com", 123L, "demo", 1L, "R-1", "jwt-token"); + new SessionContext( + 1L, 22L, "123", "demo@example.com", 123L, "demo", 1L, "R-1", "jwt-token"); when(sessionAuthenticationService.resolveSessionContext("1")).thenReturn(Optional.of(context)); when(accountClient.getTenantMembershipForRuntime( Mockito.anyString(), Mockito.anyString(), Mockito.anyString())) @@ -1659,7 +1672,8 @@ void playRequiresExplicitJoinWhenPublicProductionMembershipIsMissing() { @Test void playRequiresExplicitJoinWhenPublicProductionMembershipIsInactive() { SessionContext context = - new SessionContext(1L, 22L, 123L, "demo@example.com", 123L, "demo", 1L, "R-1", "jwt-token"); + new SessionContext( + 1L, 22L, "123", "demo@example.com", 123L, "demo", 1L, "R-1", "jwt-token"); when(sessionAuthenticationService.resolveSessionContext("1")).thenReturn(Optional.of(context)); when(accountClient.getTenantMembershipForRuntime( Mockito.anyString(), Mockito.anyString(), Mockito.anyString())) @@ -1687,7 +1701,8 @@ void playRequiresExplicitJoinWhenPublicProductionMembershipIsInactive() { @Test void playWhenMembershipAuthorityTimestampIsMalformedFailsClosed() { SessionContext context = - new SessionContext(1L, 22L, 123L, "demo@example.com", 123L, "demo", 1L, "R-1", "jwt-token"); + new SessionContext( + 1L, 22L, "123", "demo@example.com", 123L, "demo", 1L, "R-1", "jwt-token"); when(sessionAuthenticationService.resolveSessionContext("1")).thenReturn(Optional.of(context)); when(accountClient.getTenantMembershipForRuntime( Mockito.anyString(), Mockito.anyString(), Mockito.anyString())) @@ -1719,7 +1734,8 @@ void playWhenMembershipAuthorityTimestampIsMalformedFailsClosed() { @Test void playBlockedByEntitlementsReturnsBillingBlocked() { SessionContext context = - new SessionContext(1L, 22L, 123L, "demo@example.com", 123L, "demo", 1L, "R-1", "jwt-token"); + new SessionContext( + 1L, 22L, "123", "demo@example.com", 123L, "demo", 1L, "R-1", "jwt-token"); when(sessionAuthenticationService.resolveSessionContext("1")).thenReturn(Optional.of(context)); when(accountClient.getTenantEntitlementsForRuntime(Mockito.anyString(), Mockito.anyString())) .thenReturn( @@ -1748,7 +1764,8 @@ void playBlockedByEntitlementsReturnsBillingBlocked() { @Test void playMapsNonAuthorityEntitlementFailureToBillingBlocked() { SessionContext context = - new SessionContext(1L, 22L, 123L, "demo@example.com", 123L, "demo", 1L, "R-1", "jwt-token"); + new SessionContext( + 1L, 22L, "123", "demo@example.com", 123L, "demo", 1L, "R-1", "jwt-token"); when(sessionAuthenticationService.resolveSessionContext("1")).thenReturn(Optional.of(context)); when(accountClient.getTenantEntitlementsForRuntime(Mockito.anyString(), Mockito.anyString())) .thenReturn( @@ -1779,7 +1796,8 @@ void playMapsNonAuthorityEntitlementFailureToBillingBlocked() { @Test void playWhenMembershipAuthorityUnavailableFailsClosed() { SessionContext context = - new SessionContext(1L, 22L, 123L, "demo@example.com", 123L, "demo", 1L, "R-1", "jwt-token"); + new SessionContext( + 1L, 22L, "123", "demo@example.com", 123L, "demo", 1L, "R-1", "jwt-token"); when(sessionAuthenticationService.resolveSessionContext("1")).thenReturn(Optional.of(context)); when(accountClient.getTenantMembershipForRuntime( Mockito.anyString(), Mockito.anyString(), Mockito.anyString())) @@ -1810,7 +1828,8 @@ void playWhenMembershipAuthorityUnavailableFailsClosed() { @Test void playWhenEntitlementAuthorityUnavailablePreservesExistingBinding() { SessionContext context = - new SessionContext(1L, 22L, 123L, "demo@example.com", 123L, "demo", 1L, "R-1", "jwt-token"); + new SessionContext( + 1L, 22L, "123", "demo@example.com", 123L, "demo", 1L, "R-1", "jwt-token"); when(sessionAuthenticationService.resolveSessionContext("1")).thenReturn(Optional.of(context)); when(accountClient.getTenantEntitlementsForRuntime(Mockito.anyString(), Mockito.anyString())) .thenReturn( @@ -1840,7 +1859,7 @@ void playWhenEntitlementAuthorityUnavailablePreservesExistingBinding() { @Test void staleContextCharacterIsReplacedByPersistedRosterActorBeforeFreshEntry() { SessionContext context = - new SessionContext(1L, 22L, 123L, "demo@example.com", 123L, "demo", 1L, null, "jwt-token"); + new SessionContext(1L, 22L, "123", "demo@example.com", 123L, "demo", 1L, null, "jwt-token"); when(sessionAuthenticationService.resolveSessionContext("1")).thenReturn(Optional.of(context)); when(sessionAuthenticationService.resolveByGameplayIdentity(22L, 1L, 7001L)) .thenReturn(Optional.empty()); @@ -1855,7 +1874,7 @@ void staleContextCharacterIsReplacedByPersistedRosterActorBeforeFreshEntry() { new SessionContext( 1L, 22L, - 123L, + "123", "demo@example.com", 7001L, "demo", @@ -1881,7 +1900,7 @@ void staleContextCharacterIsReplacedByPersistedRosterActorBeforeFreshEntry() { new SessionContext( 1L, 22L, - 123L, + "123", "demo@example.com", 7001L, "demo", @@ -1900,7 +1919,7 @@ void staleContextCharacterIsReplacedByPersistedRosterActorBeforeFreshEntry() { new SessionContext( 1L, 22L, - 123L, + "123", "demo@example.com", 7001L, "demo", @@ -1933,7 +1952,7 @@ private SessionContext previewRealmContext() { return new SessionContext( 1L, 22L, - 123L, + "123", "demo@example.com", 123L, "Emberline", diff --git a/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/command/text/PlayerCommandHistoryFlowTest.java b/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/command/text/PlayerCommandHistoryFlowTest.java index d70f74a2b9..08dcd3dfd4 100644 --- a/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/command/text/PlayerCommandHistoryFlowTest.java +++ b/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/command/text/PlayerCommandHistoryFlowTest.java @@ -27,7 +27,7 @@ void doesNotRecordHistoryDisplayCommands() { Mockito.mock(PlayerCommandHistoryStorageService.class); SessionAuthenticationService sessionAuthenticationService = Mockito.mock(SessionAuthenticationService.class); - SessionContext context = new SessionContext(1L, 7L, 9L, 17L, 11L, "R-1", "token"); + SessionContext context = new SessionContext(1L, 7L, "9", 17L, 11L, "R-1", "token"); List storedCommands = new ArrayList<>(List.of("LOOK")); when(sessionAuthenticationService.resolveSessionContext("41")).thenReturn(Optional.of(context)); when(storage.findRecent(7L, 11L, 17L, 10)) diff --git a/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/command/text/PlayerCommandHistoryRecorderTest.java b/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/command/text/PlayerCommandHistoryRecorderTest.java index 5b76eb52ba..4701725a85 100644 --- a/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/command/text/PlayerCommandHistoryRecorderTest.java +++ b/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/command/text/PlayerCommandHistoryRecorderTest.java @@ -239,6 +239,6 @@ void quarantinesCapabilityResolutionFailure() { } private SessionContext gameplayContext(long characterId) { - return new SessionContext(1L, 7L, 9L, characterId, 11L, "R-1", "token"); + return new SessionContext(1L, 7L, "9", characterId, 11L, "R-1", "token"); } } diff --git a/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/command/text/SessionResumptionFlowTest.java b/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/command/text/SessionResumptionFlowTest.java index ccfde37969..237ec04168 100644 --- a/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/command/text/SessionResumptionFlowTest.java +++ b/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/command/text/SessionResumptionFlowTest.java @@ -626,7 +626,7 @@ private static SessionContext bootstrapShell(long sessionId, long bootstrapGameI return new SessionContext( sessionId, 22L, - 0L, + null, null, 0L, null, diff --git a/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/command/text/StatusCommandHandlerTest.java b/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/command/text/StatusCommandHandlerTest.java index 2cc4258542..8e17011d2b 100644 --- a/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/command/text/StatusCommandHandlerTest.java +++ b/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/command/text/StatusCommandHandlerTest.java @@ -23,7 +23,7 @@ class StatusCommandHandlerTest { new StatusCommandHandler(gameLogicClient, scriptEventPublisher); private final SessionContext context = new SessionContext( - 1L, 22L, 123L, "emberline@example.com", 911L, "Emberline", 77L, "R-7", "jwt-token"); + 1L, 22L, "123", "emberline@example.com", 911L, "Emberline", 77L, "R-7", "jwt-token"); @Test void statusProjectsEvaluatedResourcesAndVisibleConditionsInStableOrder() { diff --git a/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/command/text/TextCommandInterpreterCapabilityTest.java b/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/command/text/TextCommandInterpreterCapabilityTest.java index 66cd161139..fd85cecb77 100644 --- a/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/command/text/TextCommandInterpreterCapabilityTest.java +++ b/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/command/text/TextCommandInterpreterCapabilityTest.java @@ -29,7 +29,7 @@ void rejectsDisabledStandardOptionalCommandsBeforeDispatch( TextCommandDispatcher dispatcher = Mockito.mock(TextCommandDispatcher.class); SessionContext gameplayContext = new SessionContext( - 41L, 22L, 123L, "demo@example.com", 7001L, "Emberline", 7L, "R-1", "jwt"); + 41L, 22L, "123", "demo@example.com", 7001L, "Emberline", 7L, "R-1", "jwt"); when(sessionAuthenticationService.resolveSessionContext("41")) .thenReturn(Optional.of(gameplayContext)); TextCommandInterpreter interpreter = @@ -62,7 +62,7 @@ void failsClosedWhenCapabilityResolutionIsUnavailable() { Mockito.mock(EffectiveCommandCapabilitiesSettingsResolver.class); SessionContext gameplayContext = new SessionContext( - 41L, 22L, 123L, "demo@example.com", 7001L, "Emberline", 7L, "R-1", "jwt"); + 41L, 22L, "123", "demo@example.com", 7001L, "Emberline", 7L, "R-1", "jwt"); when(sessionAuthenticationService.resolveSessionContext("41")) .thenReturn(Optional.of(gameplayContext)); when(capabilitiesResolver.isEnabled(PlayerCommandCapability.SOCIAL, 22L, 7L)) diff --git a/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/command/text/TextCommandInterpreterDispatchSeamTest.java b/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/command/text/TextCommandInterpreterDispatchSeamTest.java index c227399313..ad8a6add09 100644 --- a/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/command/text/TextCommandInterpreterDispatchSeamTest.java +++ b/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/command/text/TextCommandInterpreterDispatchSeamTest.java @@ -23,7 +23,7 @@ void interpretUsesRegistryAndDispatcherInsteadOfCommandTypeBranches() { Mockito.mock(SessionAuthenticationService.class); SessionContext gameplayContext = new SessionContext( - 1L, 7L, 8L, "player@example.com", 9L, "Demo", 10L, "R-1", "token", "en-NZ", 10L); + 1L, 7L, "8", "player@example.com", 9L, "Demo", 10L, "R-1", "token", "en-NZ", 10L); Mockito.when(authenticationService.resolveSessionContext("1")) .thenReturn(Optional.of(gameplayContext)); diff --git a/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/command/text/TextCommandInterpreterTest.java b/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/command/text/TextCommandInterpreterTest.java index 1504b7ed76..ddbf4bc986 100644 --- a/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/command/text/TextCommandInterpreterTest.java +++ b/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/command/text/TextCommandInterpreterTest.java @@ -815,7 +815,7 @@ void takeAfterPlayEnqueuesDurableMutation() { @Test void bootstrapContextWithoutAuthenticatedAccountStillRequiresLogin() { ((InMemorySessionContextService) sessionContextService) - .save(new SessionContext(55L, 22L, 0L, null, 0L, null, 77L, null, null)); + .save(new SessionContext(55L, 22L, null, null, 0L, null, 77L, null, null)); TextCommandInterpretationResult interpretation = interpreter.interpret("55", "LOOK", false); @@ -852,7 +852,7 @@ void gameplayAfterLoginBeforePlayReturnsPlayRequired() { @Test void gameplayWithRoomOnlyPartialShellStillReturnsPlayRequired() { ((InMemorySessionContextService) sessionContextService) - .save(new SessionContext(56L, 22L, 123L, "demo@example.com", 0L, null, 0L, "R-7", null)); + .save(new SessionContext(56L, 22L, "123", "demo@example.com", 0L, null, 0L, "R-7", null)); TextCommandInterpretationResult interpretation = interpreter.interpret("56", "LOOK", false); @@ -1104,7 +1104,7 @@ private static SessionContext bootstrapShell(long sessionId, long bootstrapGameI return new SessionContext( sessionId, 22L, - 0L, + null, null, 0L, null, diff --git a/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/command/text/WhoCommandHandlerTest.java b/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/command/text/WhoCommandHandlerTest.java index 3e893d2545..b3ed4f874b 100644 --- a/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/command/text/WhoCommandHandlerTest.java +++ b/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/command/text/WhoCommandHandlerTest.java @@ -33,7 +33,7 @@ void whoShowsBoundedEmptyStateWhenNobodyIsConnected() { TextCommandInterpretationResult result = handler.handle( new TextCommand(TextCommandType.WHO, java.util.List.of(), "who"), - new SessionContext(2L, 22L, 2L, "second@example.com", 102L, "Ben", 7L, "R-1", null)); + new SessionContext(2L, 22L, "2", "second@example.com", 102L, "Ben", 7L, "R-1", null)); assertThat(result.commandResult().accepted()).isTrue(); assertThat(render(result)).isEqualTo("Gods [0]: \nPlayers [0]: "); @@ -65,7 +65,7 @@ void whoGroupsElevatedPlayersFirstAndPlayersAfterward() { java.util.Map.of())); gameplayPresenceService.registerConnected( - new SessionContext(1L, 22L, 1L, "god@example.com", 101L, "Aster", 7L, "R-1", godJwt)); + new SessionContext(1L, 22L, "1", "god@example.com", 101L, "Aster", 7L, "R-1", godJwt)); String moderatorJwt = jwtUtil.generateToken( "4", @@ -76,16 +76,16 @@ void whoGroupsElevatedPlayersFirstAndPlayersAfterward() { java.util.Map.of("22", java.util.List.of("moderator")))); gameplayPresenceService.registerConnected( new SessionContext( - 4L, 22L, 4L, "moderator@example.com", 104L, "Dara", 7L, "R-1", moderatorJwt)); + 4L, 22L, "4", "moderator@example.com", 104L, "Dara", 7L, "R-1", moderatorJwt)); gameplayPresenceService.registerConnected( - new SessionContext(2L, 22L, 2L, "second@example.com", 102L, "Ben", 7L, "R-1", null)); + new SessionContext(2L, 22L, "2", "second@example.com", 102L, "Ben", 7L, "R-1", null)); gameplayPresenceService.registerConnected( - new SessionContext(3L, 22L, 3L, "third@example.com", 103L, "Cara", 7L, "R-1", null)); + new SessionContext(3L, 22L, "3", "third@example.com", 103L, "Cara", 7L, "R-1", null)); TextCommandInterpretationResult result = handler.handle( new TextCommand(TextCommandType.WHO, java.util.List.of(), "WHO"), - new SessionContext(2L, 22L, 2L, "second@example.com", 102L, "Ben", 7L, "R-1", null)); + new SessionContext(2L, 22L, "2", "second@example.com", 102L, "Ben", 7L, "R-1", null)); assertThat(result.commandResult().accepted()).isTrue(); assertThat(render(result)).isEqualTo("Gods [2]: Aster, Dara\nPlayers [2]: Ben, Cara"); @@ -98,15 +98,15 @@ void whoOmitsRemovedPresenceAfterLogoutLikeCleanup() { new WhoCommandHandler(gameplayPresenceService, activityResolver, scriptEventPublisher); gameplayPresenceService.registerConnected( - new SessionContext(1L, 22L, 1L, "first@example.com", 101L, "Aster", 7L, "R-1", null)); + new SessionContext(1L, 22L, "1", "first@example.com", 101L, "Aster", 7L, "R-1", null)); gameplayPresenceService.registerConnected( - new SessionContext(2L, 22L, 2L, "second@example.com", 102L, "Ben", 7L, "R-1", null)); + new SessionContext(2L, 22L, "2", "second@example.com", 102L, "Ben", 7L, "R-1", null)); gameplayPresenceService.removeBySessionId(1L); TextCommandInterpretationResult result = handler.handle( new TextCommand(TextCommandType.WHO, java.util.List.of(), "WHO"), - new SessionContext(2L, 22L, 2L, "second@example.com", 102L, "Ben", 7L, "R-1", null)); + new SessionContext(2L, 22L, "2", "second@example.com", 102L, "Ben", 7L, "R-1", null)); assertThat(result.commandResult().accepted()).isTrue(); assertThat(render(result)).isEqualTo("Gods [0]: \nPlayers [1]: Ben"); @@ -121,9 +121,9 @@ void whoAnnotatesExplicitAndAutoAfkPlayers() { new WhoCommandHandler(gameplayPresenceService, resolver, scriptEventPublisher); gameplayPresenceService.registerConnected( - new SessionContext(1L, 22L, 1L, "active@example.com", 101L, "Aster", 7L, "R-1", null)); + new SessionContext(1L, 22L, "1", "active@example.com", 101L, "Aster", 7L, "R-1", null)); gameplayPresenceService.registerConnected( - new SessionContext(2L, 22L, 2L, "idle@example.com", 102L, "Ben", 7L, "R-1", null)); + new SessionContext(2L, 22L, "2", "idle@example.com", 102L, "Ben", 7L, "R-1", null)); when(resolver.resolve(gameplayPresenceService.findConnectedBySessionId(1L).orElseThrow())) .thenReturn(GameplayPresenceActivityState.ACTIVE); when(resolver.resolve(gameplayPresenceService.findConnectedBySessionId(2L).orElseThrow())) @@ -132,7 +132,7 @@ void whoAnnotatesExplicitAndAutoAfkPlayers() { TextCommandInterpretationResult result = handler.handle( new TextCommand(TextCommandType.WHO, java.util.List.of(), "WHO"), - new SessionContext(1L, 22L, 1L, "active@example.com", 101L, "Aster", 7L, "R-1", null)); + new SessionContext(1L, 22L, "1", "active@example.com", 101L, "Aster", 7L, "R-1", null)); assertThat(result.commandResult().accepted()).isTrue(); assertThat(result.outputs()) diff --git a/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/command/text/WorldsCommandHandlerTest.java b/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/command/text/WorldsCommandHandlerTest.java index a046ccc09a..82658aba07 100644 --- a/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/command/text/WorldsCommandHandlerTest.java +++ b/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/command/text/WorldsCommandHandlerTest.java @@ -108,7 +108,7 @@ void browseCharactersReturnsStructuredCharacterList() { WorldsCommandHandler.CharacterBrowseResult result = handler.browseCharacters( - new SessionContext(1L, 22L, 123L, "demo@example.com", 0L, null, 0L, "jwt"), + new SessionContext(1L, 22L, "123", "demo@example.com", 0L, null, 0L, "jwt"), "demo", null); @@ -159,7 +159,7 @@ void browseCharactersUsesIsolatedStateRealmRoster() { WorldsCommandHandler.CharacterBrowseResult result = handler.browseCharacters( - new SessionContext(1L, 22L, 123L, "demo@example.com", 0L, null, 0L, "jwt"), + new SessionContext(1L, 22L, "123", "demo@example.com", 0L, null, 0L, "jwt"), "demo", null); @@ -191,7 +191,7 @@ void browseCharactersFallsBackToUnspecifiedRosterScopeForNullRealmScope() { WorldsCommandHandler.CharacterBrowseResult result = localHandler.browseCharacters( - new SessionContext(1L, 22L, 123L, "demo@example.com", 0L, null, 0L, "jwt"), + new SessionContext(1L, 22L, "123", "demo@example.com", 0L, null, 0L, "jwt"), "demo", null); diff --git a/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/command/text/WorldsTextCommandDispatchHandlerTest.java b/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/command/text/WorldsTextCommandDispatchHandlerTest.java index e37e07fc6d..680573bef1 100644 --- a/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/command/text/WorldsTextCommandDispatchHandlerTest.java +++ b/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/command/text/WorldsTextCommandDispatchHandlerTest.java @@ -36,7 +36,7 @@ class WorldsTextCommandDispatchHandlerTest { void publishesCommandEventForGameplayScopedWorldsBrowse() { SessionContext context = new SessionContext( - 7L, 22L, 41L, "emberline@example.com", 7001L, "Emberline", 9L, "R-1", "jwt"); + 7L, 22L, "41", "emberline@example.com", 7001L, "Emberline", 9L, "R-1", "jwt"); TextCommandInterpretationResult result = handler.handle( @@ -67,7 +67,7 @@ void publishesCommandEventForGameplayScopedRealmsBrowse() { gameplayCatalogProperties.setWorlds(List.of(world("demo", 22L, 41L, false))); SessionContext context = new SessionContext( - 7L, 22L, 41L, "emberline@example.com", 7001L, "Emberline", 9L, "R-1", "jwt"); + 7L, 22L, "41", "emberline@example.com", 7001L, "Emberline", 9L, "R-1", "jwt"); TextCommandInterpretationResult result = handler.handle( @@ -110,7 +110,7 @@ void publishesCommandEventForGameplayScopedCharsBrowse() { .build()); SessionContext context = new SessionContext( - 7L, 22L, 123L, "emberline@example.com", 7001L, "Emberline", 9L, "R-1", "jwt"); + 7L, 22L, "123", "emberline@example.com", 7001L, "Emberline", 9L, "R-1", "jwt"); TextCommandInterpretationResult result = handler.handle( diff --git a/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/config/EffectiveCommandHistorySettingsResolverTest.java b/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/config/EffectiveCommandHistorySettingsResolverTest.java index e4fa99b3a4..8941adc987 100644 --- a/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/config/EffectiveCommandHistorySettingsResolverTest.java +++ b/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/config/EffectiveCommandHistorySettingsResolverTest.java @@ -42,7 +42,7 @@ void resolvesTenantThenGameInstanceCommandHistoryOverrides() { resolved = resolver.resolvedCommandHistory( new SessionContext( - 1L, 22L, 123L, "demo@example.com", 911L, "Ember", 7L, "R-1", null)); + 1L, 22L, "123", "demo@example.com", 911L, "Ember", 7L, "R-1", null)); assertThat(resolved.effective()).isEqualTo(new FiremudCommandHistoryProperties(20)); assertThat(resolved.sources()) diff --git a/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/config/EffectiveReconnectionSettingsResolverTest.java b/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/config/EffectiveReconnectionSettingsResolverTest.java index 758e1a504e..07ee466823 100644 --- a/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/config/EffectiveReconnectionSettingsResolverTest.java +++ b/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/config/EffectiveReconnectionSettingsResolverTest.java @@ -53,7 +53,7 @@ void absentPersistedReconnectionOverrideFallsBackToOperatorDefaults() { FiremudReconnectionProperties effective = resolver.reconnection( - new SessionContext(1L, 22L, 123L, "demo@example.com", 911L, "Ember", 7L, "R-1", null)); + new SessionContext(1L, 22L, "123", "demo@example.com", 911L, "Ember", 7L, "R-1", null)); assertThat(effective.policy().resumeWindowMs()).isEqualTo(45_000L); assertThat(effective.policy().staleResumeFallsThroughToFreshEntry()).isTrue(); @@ -114,7 +114,7 @@ void disregardsInvalidSparseOverrideAndFallsBackToOperatorDefaultsWithDiagnostic EffectiveReconnectionSettingsResolver.ResolvedValue resolved = resolver.resolvedReconnection( - new SessionContext(1L, 22L, 123L, "demo@example.com", 911L, "Ember", 7L, "R-1", null)); + new SessionContext(1L, 22L, "123", "demo@example.com", 911L, "Ember", 7L, "R-1", null)); assertThat(resolved.effective().buffer().softMaxBytes()).isEqualTo(16_384); assertThat(resolved.effective().buffer().hardMaxBytes()).isEqualTo(65_536); @@ -159,7 +159,7 @@ void invalidGameInstanceOverrideFallsBackToValidTenantLayer() { EffectiveReconnectionSettingsResolver.ResolvedValue resolved = resolver.resolvedReconnection( - new SessionContext(1L, 22L, 123L, "demo@example.com", 911L, "Ember", 7L, "R-1", null)); + new SessionContext(1L, 22L, "123", "demo@example.com", 911L, "Ember", 7L, "R-1", null)); assertThat(resolved.effective().buffer().softMaxBytes()).isEqualTo(16_384); assertThat(resolved.effective().buffer().hardMaxBytes()).isEqualTo(80_000); diff --git a/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/config/EffectiveSettingsResolverTest.java b/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/config/EffectiveSettingsResolverTest.java index 47f6751780..4e6f7cdd59 100644 --- a/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/config/EffectiveSettingsResolverTest.java +++ b/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/config/EffectiveSettingsResolverTest.java @@ -53,7 +53,7 @@ void presentationOverridesMergeTenantThenGameInstance() { PresentationProperties effective = resolver.presentation( - new SessionContext(1L, 22L, 123L, "demo@example.com", 911L, "Ember", 7L, "R-1", null)); + new SessionContext(1L, 22L, "123", "demo@example.com", 911L, "Ember", 7L, "R-1", null)); assertThat(effective.defaultLocaleTag()).isEqualTo("fr"); assertThat(effective.defaultColorMode()).isEqualTo(PresentationProperties.ColorMode.BASIC); @@ -87,7 +87,7 @@ void movementAndTopologyOverridesResolveAgainstBootstrapGameInstanceBeforePlay() authorityReader); SessionContext prePlay = - new SessionContext(1L, 22L, 123L, "demo@example.com", 0L, null, 0L, null, null, null, 41L); + new SessionContext(1L, 22L, "123", "demo@example.com", 0L, null, 0L, null, null, null, 41L); assertThat(resolver.movement(prePlay).postMoveLookEnabled()).isFalse(); assertThat(resolver.worldTopology(prePlay).scopeModel()) diff --git a/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/controller/EffectiveSettingsControllerTest.java b/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/controller/EffectiveSettingsControllerTest.java index 6f9b8aa094..57dd7ffe30 100644 --- a/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/controller/EffectiveSettingsControllerTest.java +++ b/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/controller/EffectiveSettingsControllerTest.java @@ -55,7 +55,7 @@ void setUp() { void effectiveSettingsUsesNormalizedPersistedSessionContext() { SessionContext cleared = new SessionContext( - 41L, 22L, 123L, "demo@example.com", 0L, null, 0L, null, "jwt", "en-NZ", 1L); + 41L, 22L, "123", "demo@example.com", 0L, null, 0L, null, "jwt", "en-NZ", 1L); PresentationProperties presentation = new PresentationProperties(); MovementProperties movement = new MovementProperties(); WorldTopologyProperties worldTopology = new WorldTopologyProperties(); diff --git a/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/health/GameplayLocalPathReadinessProbeTest.java b/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/health/GameplayLocalPathReadinessProbeTest.java index 29b751ed25..c970c7cfe7 100644 --- a/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/health/GameplayLocalPathReadinessProbeTest.java +++ b/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/health/GameplayLocalPathReadinessProbeTest.java @@ -37,7 +37,7 @@ void sessionContextProbeReturnsUpWhenContextRoundTrips() { new SessionContext( sessionId, 0L, - PROBE_ACCOUNT_ID, + Long.toString(PROBE_ACCOUNT_ID), PROBE_CHARACTER_ID, 0L, "readiness-room-" + probeSequence, diff --git a/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/presentation/PromptBurstCoordinatorTest.java b/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/presentation/PromptBurstCoordinatorTest.java index a53b8fdb29..ad93801bef 100644 --- a/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/presentation/PromptBurstCoordinatorTest.java +++ b/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/presentation/PromptBurstCoordinatorTest.java @@ -102,7 +102,7 @@ void scopedOverrideControlsPromptWindowWhenContextKnown() { List outputs = List.of(PlayerOutput.message("You say, \"hello\""), PlayerOutput.prompt("demo> ")); SessionContext context = - new SessionContext(1L, 22L, 123L, "demo@example.com", 911L, "Sora", 7L, "R-1", null); + new SessionContext(1L, 22L, "123", "demo@example.com", 911L, "Sora", 7L, "R-1", null); coordinator.recordPromptEmission("1", outputs); diff --git a/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/presentation/PromptComposerTest.java b/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/presentation/PromptComposerTest.java index 8eaed1f1ea..a40c459f32 100644 --- a/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/presentation/PromptComposerTest.java +++ b/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/presentation/PromptComposerTest.java @@ -11,7 +11,7 @@ class PromptComposerTest { @Test void composeIncludesStructuredFieldsAlongsideClassicPromptText() { SessionContext context = - new SessionContext(41L, 22L, 77L, "demo@example.com", 123L, "Sora", 9L, "R-1021", "jwt"); + new SessionContext(41L, 22L, "77", "demo@example.com", 123L, "Sora", 9L, "R-1021", "jwt"); PlayerOutput prompt = composer.compose(context).orElseThrow(); @@ -29,7 +29,7 @@ void composeIncludesStructuredFieldsAlongsideClassicPromptText() { @Test void composeFallsBackToBarePromptWhileStillPublishingIdentifiers() { SessionContext context = - new SessionContext(41L, 22L, 77L, null, 123L, null, 9L, "R-1021", "jwt"); + new SessionContext(41L, 22L, "77", null, 123L, null, 9L, "R-1021", "jwt"); PlayerOutput prompt = composer.compose(context).orElseThrow(); diff --git a/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/service/CommunicationRecipientDeliveryServiceTest.java b/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/service/CommunicationRecipientDeliveryServiceTest.java index e9cdeade50..73a376a5e1 100644 --- a/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/service/CommunicationRecipientDeliveryServiceTest.java +++ b/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/service/CommunicationRecipientDeliveryServiceTest.java @@ -66,10 +66,11 @@ void tearDown() { @Test void deliverDropsStaleRecipientResolvedByGameplayIdentity() { SessionContext actor = - new SessionContext(41L, 22L, 123L, "demo@example.com", 123L, "Emberline", 1L, "R-1", "jwt"); + new SessionContext( + 41L, 22L, "123", "demo@example.com", 123L, "Emberline", 1L, "R-1", "jwt"); SessionContext clearedRecipient = new SessionContext( - 42L, 22L, 456L, "friend@example.com", 0L, null, 0L, null, "jwt", "en-NZ", 1L); + 42L, 22L, "456", "friend@example.com", 0L, null, 0L, null, "jwt", "en-NZ", 1L); CommunicationRecipientView view = CommunicationRecipientView.newBuilder() .setRole(CommunicationRecipientRole.COMMUNICATION_RECIPIENT_ROLE_TARGET) @@ -95,10 +96,11 @@ void deliverDropsStaleRecipientResolvedByGameplayIdentity() { @Test void deliverDropsStaleRecipientResolvedByGameplayName() { SessionContext actor = - new SessionContext(41L, 22L, 123L, "demo@example.com", 123L, "Emberline", 1L, "R-1", "jwt"); + new SessionContext( + 41L, 22L, "123", "demo@example.com", 123L, "Emberline", 1L, "R-1", "jwt"); SessionContext clearedRecipient = new SessionContext( - 42L, 22L, 456L, "friend@example.com", 0L, null, 0L, null, "jwt", "en-NZ", 1L); + 42L, 22L, "456", "friend@example.com", 0L, null, 0L, null, "jwt", "en-NZ", 1L); CommunicationRecipientView view = CommunicationRecipientView.newBuilder() .setRole(CommunicationRecipientRole.COMMUNICATION_RECIPIENT_ROLE_TARGET) @@ -124,7 +126,8 @@ void deliverDropsStaleRecipientResolvedByGameplayName() { @Test void deliverDoesNotFallbackToNameWhenRecipientIdIsMalformed() { SessionContext actor = - new SessionContext(41L, 22L, 123L, "demo@example.com", 123L, "Emberline", 1L, "R-1", "jwt"); + new SessionContext( + 41L, 22L, "123", "demo@example.com", 123L, "Emberline", 1L, "R-1", "jwt"); CommunicationRecipientView view = CommunicationRecipientView.newBuilder() .setRole(CommunicationRecipientRole.COMMUNICATION_RECIPIENT_ROLE_TARGET) @@ -150,7 +153,8 @@ void deliverDoesNotFallbackToNameWhenRecipientIdIsMalformed() { @Test void deliverDoesNotFallbackToNameWhenRecipientIdIsNonPositive() { SessionContext actor = - new SessionContext(41L, 22L, 123L, "demo@example.com", 123L, "Emberline", 1L, "R-1", "jwt"); + new SessionContext( + 41L, 22L, "123", "demo@example.com", 123L, "Emberline", 1L, "R-1", "jwt"); CommunicationRecipientView view = CommunicationRecipientView.newBuilder() .setRole(CommunicationRecipientRole.COMMUNICATION_RECIPIENT_ROLE_TARGET) @@ -174,7 +178,8 @@ void deliverDoesNotFallbackToNameWhenRecipientIdIsNonPositive() { @Test void deliverDoesNotFallbackToNameWhenStructuredRecipientIdDoesNotResolve() { SessionContext actor = - new SessionContext(41L, 22L, 123L, "demo@example.com", 123L, "Emberline", 1L, "R-1", "jwt"); + new SessionContext( + 41L, 22L, "123", "demo@example.com", 123L, "Emberline", 1L, "R-1", "jwt"); CommunicationRecipientView view = CommunicationRecipientView.newBuilder() .setRole(CommunicationRecipientRole.COMMUNICATION_RECIPIENT_ROLE_TARGET) @@ -203,10 +208,11 @@ void deliverDoesNotFallbackToNameWhenStructuredRecipientIdDoesNotResolve() { @SuppressWarnings("unchecked") void deliverBuffersStructuredReplayEntryForRecipientCommunication() { SessionContext actor = - new SessionContext(41L, 22L, 123L, "demo@example.com", 123L, "Emberline", 1L, "R-1", "jwt"); + new SessionContext( + 41L, 22L, "123", "demo@example.com", 123L, "Emberline", 1L, "R-1", "jwt"); SessionContext recipient = new SessionContext( - 42L, 22L, 456L, "friend@example.com", 456L, "Sora", 1L, "R-2", "jwt", "en-NZ", 1L); + 42L, 22L, "456", "friend@example.com", 456L, "Sora", 1L, "R-2", "jwt", "en-NZ", 1L); CommunicationRecipientView view = CommunicationRecipientView.newBuilder() .setRole(CommunicationRecipientRole.COMMUNICATION_RECIPIENT_ROLE_TARGET) @@ -252,10 +258,11 @@ void deliverBuffersStructuredReplayEntryForRecipientCommunication() { @Test void deliverDoesNotBufferNonReplayableRecipientOutput() { SessionContext actor = - new SessionContext(41L, 22L, 123L, "demo@example.com", 123L, "Emberline", 1L, "R-1", "jwt"); + new SessionContext( + 41L, 22L, "123", "demo@example.com", 123L, "Emberline", 1L, "R-1", "jwt"); SessionContext recipient = new SessionContext( - 42L, 22L, 456L, "friend@example.com", 456L, "Sora", 1L, "R-2", "jwt", "en-NZ", 1L); + 42L, 22L, "456", "friend@example.com", 456L, "Sora", 1L, "R-2", "jwt", "en-NZ", 1L); CommunicationRecipientView view = CommunicationRecipientView.newBuilder() .setRole(CommunicationRecipientRole.COMMUNICATION_RECIPIENT_ROLE_TARGET) diff --git a/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/service/FirstPartyConnectContextServiceTest.java b/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/service/FirstPartyConnectContextServiceTest.java index 814797a0f9..100177c024 100644 --- a/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/service/FirstPartyConnectContextServiceTest.java +++ b/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/service/FirstPartyConnectContextServiceTest.java @@ -40,7 +40,7 @@ void parseReadsJwtClaimsThroughInjectedUtil() { assertTrue(service.parse("token").isPresent()); FirstPartyConnectContext context = service.parse("token").orElseThrow(); - assertEquals(42L, context.accountId()); + assertEquals("42", context.accountId()); assertEquals(7L, context.tenantId()); assertEquals("demo", context.worldSlug()); assertEquals("production", context.realmSlug()); diff --git a/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/service/GameplayAdmissionPointerSnapshotsTest.java b/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/service/GameplayAdmissionPointerSnapshotsTest.java index 095ceed114..2413e52a29 100644 --- a/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/service/GameplayAdmissionPointerSnapshotsTest.java +++ b/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/service/GameplayAdmissionPointerSnapshotsTest.java @@ -15,7 +15,7 @@ class GameplayAdmissionPointerSnapshotsTest { void admittedRoutingBundleReturnsNormalizedBundleWhenRoutingClaimsAreComplete() { SessionContext completeContext = new SessionContext( - 22L, 41L, 0L, null, 123L, null, 1L, "R-1021", null, null, 1L, "world", "realm", 17L, + 22L, 41L, null, null, 123L, null, 1L, "R-1021", null, null, 1L, "world", "realm", 17L, null); GameplayAdmissionPointerSnapshots.AdmittedRoutingBundle bundle = @@ -33,7 +33,8 @@ void admittedRoutingBundleReturnsNormalizedBundleWhenRoutingClaimsAreComplete() void admittedRoutingBundleReturnsEmptyForPartialRoutingClaims() { SessionContext partialRouting = new SessionContext( - 22L, 41L, 0L, null, 123L, null, 1L, "R-1021", null, null, 1L, "world", null, 17L, null); + 22L, 41L, null, null, 123L, null, 1L, "R-1021", null, null, 1L, "world", null, 17L, + null); GameplayAdmissionPointerSnapshots.AdmittedRoutingBundle bundle = GameplayAdmissionPointerSnapshots.admittedRoutingBundle(partialRouting); @@ -48,7 +49,7 @@ void admittedRoutingBundleReturnsEmptyForPartialRoutingClaims() { void admittedRoutingBundleReturnsEmptyWhenRoutingClaimsAreAbsent() { SessionContext missingRouting = new SessionContext( - 22L, 41L, 0L, null, 123L, null, 1L, "R-1021", null, null, 1L, null, null, 0L, null); + 22L, 41L, null, null, 123L, null, 1L, "R-1021", null, null, 1L, null, null, 0L, null); GameplayAdmissionPointerSnapshots.AdmittedRoutingBundle bundle = GameplayAdmissionPointerSnapshots.admittedRoutingBundle(missingRouting); @@ -63,7 +64,8 @@ void admittedRoutingBundleReturnsEmptyWhenRoutingClaimsAreAbsent() { void requireAdmittedRoutingBundleRejectsPartialRoutingClaimsWithCallerSpecificMessage() { SessionContext partialRouting = new SessionContext( - 22L, 41L, 0L, null, 123L, null, 1L, "R-1021", null, null, 1L, "world", null, 17L, null); + 22L, 41L, null, null, 123L, null, 1L, "R-1021", null, null, 1L, "world", null, 17L, + null); assertThatThrownBy( () -> @@ -77,7 +79,7 @@ void requireAdmittedRoutingBundleRejectsPartialRoutingClaimsWithCallerSpecificMe void requireAdmittedRoutingBundleRejectsMissingRoutingClaimsWithCallerSpecificMessage() { SessionContext missingRouting = new SessionContext( - 22L, 41L, 0L, null, 123L, null, 1L, "R-1021", null, null, 1L, null, null, 0L, null); + 22L, 41L, null, null, 123L, null, 1L, "R-1021", null, null, 1L, null, null, 0L, null); assertThatThrownBy( () -> @@ -452,7 +454,7 @@ void sameBootstrapRouteRejectsPlayableStateScopeChanges() { void sameBootstrapRouteRejectsFirstPartyConnectContextWhenRoutingIdentityChanges() { FirstPartyConnectContext existing = new FirstPartyConnectContext( - 123L, 22L, "demo", "production", 1L, 7L, "scope-1", "jti-1", "req-1", "gw-1"); + "123", 22L, "demo", "production", 1L, 7L, "scope-1", "jti-1", "req-1", "gw-1"); assertThat( GameplayAdmissionPointerSnapshots.sameBootstrapRoute( @@ -480,7 +482,7 @@ void sameBootstrapRouteAcceptsTwoContextsWithNoRoutingValues() { void sameBootstrapRouteAcceptsFirstPartyConnectContextWithCaseInsensitiveRoutingIdentity() { FirstPartyConnectContext existing = new FirstPartyConnectContext( - 123L, 22L, "demo", "production", 1L, 7L, "scope-1", "jti-1", "req-1", "gw-1"); + "123", 22L, "demo", "production", 1L, 7L, "scope-1", "jti-1", "req-1", "gw-1"); assertThat( GameplayAdmissionPointerSnapshots.sameBootstrapRoute( @@ -508,7 +510,7 @@ private static SessionContext bootstrapShell( return new SessionContext( 1L, tenantId, - 0L, + null, null, 0L, null, diff --git a/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/service/GameplayPresenceActivityResolverTest.java b/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/service/GameplayPresenceActivityResolverTest.java index f572ac2758..d37ce08304 100644 --- a/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/service/GameplayPresenceActivityResolverTest.java +++ b/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/service/GameplayPresenceActivityResolverTest.java @@ -23,7 +23,7 @@ void explicitAfkWinsOverDerivedAutoAfk() { 7L, "demo", "production", - 2L, + "2", 102L, "Ben", GameplayPresenceRole.PLAYER, @@ -51,7 +51,7 @@ void autoAfkIgnoresAcceptedNonGameplayActivity() { 7L, "demo", "production", - 2L, + "2", 102L, "Ben", GameplayPresenceRole.PLAYER, @@ -68,7 +68,7 @@ void autoAfkIgnoresAcceptedNonGameplayActivity() { 7L, "demo", "production", - 2L, + "2", 102L, "Ben", GameplayPresenceRole.PLAYER, @@ -85,7 +85,7 @@ void autoAfkIgnoresAcceptedNonGameplayActivity() { 7L, "demo", "production", - 2L, + "2", 102L, "Ben", GameplayPresenceRole.PLAYER, @@ -111,7 +111,7 @@ void autoAfkFallsBackToConnectionTimeWhenNoGameplayActivityExists() { 7L, "demo", "production", - 2L, + "2", 102L, "Ben", GameplayPresenceRole.PLAYER, diff --git a/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/service/SessionAuthenticationServiceTest.java b/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/service/SessionAuthenticationServiceTest.java index 208be9144e..638e0b2623 100644 --- a/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/service/SessionAuthenticationServiceTest.java +++ b/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/service/SessionAuthenticationServiceTest.java @@ -45,7 +45,7 @@ void resolveSessionContextClearsStaleGameplayBindingButKeepsLogin() { new SessionContext( 41L, 22L, - 123L, + "123", "demo@example.com", 7001L, "Emberline", @@ -66,13 +66,13 @@ void resolveSessionContextClearsStaleGameplayBindingButKeepsLogin() { Optional resolved = service.resolveSessionContext("41"); assertTrue(resolved.isPresent()); - assertEquals(123L, resolved.orElseThrow().accountId()); + assertEquals("123", resolved.orElseThrow().accountId()); assertEquals(0L, resolved.orElseThrow().gameInstanceId()); assertEquals(0L, resolved.orElseThrow().characterId()); ArgumentCaptor captor = ArgumentCaptor.forClass(SessionContext.class); verify(sessionContextService).save(captor.capture()); verify(gameplayPresenceLifecycleService).clearGameplayBinding(stale, "STALE_ADMISSION_POINTER"); - assertEquals(123L, captor.getValue().accountId()); + assertEquals("123", captor.getValue().accountId()); assertEquals(0L, captor.getValue().gameInstanceId()); assertEquals(0L, captor.getValue().pointerVersion()); } @@ -81,7 +81,7 @@ void resolveSessionContextClearsStaleGameplayBindingButKeepsLogin() { void resolveSessionContextClearsGameplayBindingWhenRoutingBundleIsIncomplete() { SessionContext incomplete = new SessionContext( - 41L, 22L, 123L, "demo@example.com", 7001L, "Emberline", 1L, "R-1", "jwt"); + 41L, 22L, "123", "demo@example.com", 7001L, "Emberline", 1L, "R-1", "jwt"); when(sessionContextService.findBySessionId(41L)).thenReturn(Optional.of(incomplete)); when(sessionContextService.findByTenantAndSessionId(22L, 41L)) .thenReturn(Optional.of(incomplete)); @@ -89,7 +89,7 @@ void resolveSessionContextClearsGameplayBindingWhenRoutingBundleIsIncomplete() { Optional resolved = service.resolveSessionContext("41"); assertTrue(resolved.isPresent()); - assertEquals(123L, resolved.orElseThrow().accountId()); + assertEquals("123", resolved.orElseThrow().accountId()); assertEquals(0L, resolved.orElseThrow().gameInstanceId()); verify(sessionContextService).save(Mockito.any(SessionContext.class)); verify(gameplayPresenceLifecycleService) @@ -102,7 +102,7 @@ void resolveSessionContextClearsGameplayBindingWhenRuntimeTargetAuthorityIsAmbig new SessionContext( 41L, 22L, - 123L, + "123", "demo@example.com", 7001L, "Emberline", @@ -139,7 +139,7 @@ void resolveSessionContextKeepsCurrentGameplayBindingWhenPointerMatches() { new SessionContext( 41L, 22L, - 123L, + "123", "demo@example.com", 7001L, "Emberline", @@ -172,7 +172,7 @@ void resolveUnverifiedSessionContextWithTenantIdNormalizesResolvedContext() { new SessionContext( 41L, 22L, - 123L, + "123", "demo@example.com", 7001L, "Emberline", @@ -192,7 +192,7 @@ void resolveUnverifiedSessionContextWithTenantIdNormalizesResolvedContext() { Optional resolved = service.resolveUnverifiedSessionContext(22L, 41L); assertTrue(resolved.isPresent()); - assertEquals(123L, resolved.orElseThrow().accountId()); + assertEquals("123", resolved.orElseThrow().accountId()); assertEquals(0L, resolved.orElseThrow().gameInstanceId()); verify(sessionContextService).save(Mockito.any(SessionContext.class)); verify(gameplayPresenceLifecycleService).clearGameplayBinding(stale, "STALE_ADMISSION_POINTER"); @@ -204,7 +204,7 @@ void resolveUnverifiedSessionContextFailsClosedWhenTenantScopedSessionIsMissing( new SessionContext( 41L, 22L, - 123L, + "123", "demo@example.com", 7001L, "Emberline", @@ -260,7 +260,7 @@ void resolveByGameplayIdentityNormalizesResolvedContext() { new SessionContext( 41L, 22L, - 123L, + "123", "demo@example.com", 7001L, "Emberline", @@ -292,7 +292,7 @@ void resolveByGameplayNameKeepsCurrentContextWhenPointerMatches() { new SessionContext( 41L, 22L, - 123L, + "123", "demo@example.com", 7001L, "Emberline", diff --git a/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/service/SessionContextTest.java b/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/service/SessionContextTest.java index fee7ca2ce4..b9bc2b7024 100644 --- a/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/service/SessionContextTest.java +++ b/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/service/SessionContextTest.java @@ -11,16 +11,16 @@ class SessionContextTest { @Test void preservesLegacyAndSyntheticRuntimeRoomIdsVerbatim() { SessionContext legacyNumeric = - new SessionContext(1L, 22L, 123L, "demo@example.com", 7001L, "Emberline", 41L, "1", "jwt"); + new SessionContext(1L, 22L, "123", "demo@example.com", 7001L, "Emberline", 41L, "1", "jwt"); SessionContext legacyPrefixed = new SessionContext( - 1L, 22L, 123L, "demo@example.com", 7001L, "Emberline", 41L, "room-1", "jwt"); + 1L, 22L, "123", "demo@example.com", 7001L, "Emberline", 41L, "room-1", "jwt"); SessionContext legacyUppercasePrefixed = new SessionContext( - 1L, 22L, 123L, "demo@example.com", 7001L, "Emberline", 41L, "ROOM-1", "jwt"); + 1L, 22L, "123", "demo@example.com", 7001L, "Emberline", 41L, "ROOM-1", "jwt"); SessionContext syntheticProbe = new SessionContext( - 1L, 22L, 123L, "demo@example.com", 7001L, "Emberline", 41L, "readiness-room-1", "jwt"); + 1L, 22L, "123", "demo@example.com", 7001L, "Emberline", 41L, "readiness-room-1", "jwt"); assertEquals("1", legacyNumeric.roomInstanceId()); assertEquals("room-1", legacyPrefixed.roomInstanceId()); @@ -34,7 +34,7 @@ void hasPartialPersistedFirstPartyConnectContextDetectsMissingConnectRequest() { new SessionContext( 1L, 22L, - 123L, + "123", "first-party:123", 0L, null, @@ -60,7 +60,7 @@ void hasPartialPersistedFirstPartyConnectContextIgnoresStandardGameplaySession() new SessionContext( 1L, 22L, - 123L, + "123", "demo@example.com", 7001L, "Emberline", @@ -85,7 +85,7 @@ void hasPartialPersistedFirstPartyConnectContextDetectsMissingConnectScope() { new SessionContext( 1L, 22L, - 123L, + "123", "first-party:123", 0L, null, @@ -111,7 +111,7 @@ void hasPartialPersistedFirstPartyConnectContextRequiresPositiveAccountIdentity( new SessionContext( 1L, 22L, - 0L, + null, "first-party:123", 0L, null, @@ -135,11 +135,12 @@ void hasPartialPersistedFirstPartyConnectContextRequiresPositiveAccountIdentity( void hasGameplayRegionBindingRequiresGameInstanceCharacterAndRoom() { SessionContext complete = new SessionContext( - 1L, 22L, 123L, "demo@example.com", 7001L, "Emberline", 41L, "R-1", "jwt"); + 1L, 22L, "123", "demo@example.com", 7001L, "Emberline", 41L, "R-1", "jwt"); SessionContext missingRoom = - new SessionContext(1L, 22L, 123L, "demo@example.com", 7001L, "Emberline", 41L, null, "jwt"); + new SessionContext( + 1L, 22L, "123", "demo@example.com", 7001L, "Emberline", 41L, null, "jwt"); SessionContext missingCharacter = - new SessionContext(1L, 22L, 123L, "demo@example.com", 0L, null, 41L, "R-1", "jwt"); + new SessionContext(1L, 22L, "123", "demo@example.com", 0L, null, 41L, "R-1", "jwt"); assertTrue(complete.hasGameplayRegionBinding()); assertFalse(missingRoom.hasGameplayRegionBinding()); @@ -149,13 +150,13 @@ void hasGameplayRegionBindingRequiresGameInstanceCharacterAndRoom() { @Test void hasGameplayBindingTreatsPartialGameplayShellsAsBound() { SessionContext gameOnly = - new SessionContext(1L, 22L, 123L, "demo@example.com", 0L, null, 41L, null, "jwt"); + new SessionContext(1L, 22L, "123", "demo@example.com", 0L, null, 41L, null, "jwt"); SessionContext characterOnly = - new SessionContext(1L, 22L, 123L, "demo@example.com", 7001L, "Emberline", 0L, null, "jwt"); + new SessionContext(1L, 22L, "123", "demo@example.com", 7001L, "Emberline", 0L, null, "jwt"); SessionContext roomOnly = - new SessionContext(1L, 22L, 123L, "demo@example.com", 0L, null, 0L, "R-1", "jwt"); + new SessionContext(1L, 22L, "123", "demo@example.com", 0L, null, 0L, "R-1", "jwt"); SessionContext blank = - new SessionContext(1L, 22L, 123L, "demo@example.com", 0L, null, 0L, null, "jwt"); + new SessionContext(1L, 22L, "123", "demo@example.com", 0L, null, 0L, null, "jwt"); assertTrue(gameOnly.hasGameplayBinding()); assertTrue(characterOnly.hasGameplayBinding()); @@ -167,11 +168,12 @@ void hasGameplayBindingTreatsPartialGameplayShellsAsBound() { void hasGameplayIdentityRequiresPositiveGameInstanceAndCharacter() { SessionContext complete = new SessionContext( - 1L, 22L, 123L, "demo@example.com", 7001L, "Emberline", 41L, "R-1", "jwt"); + 1L, 22L, "123", "demo@example.com", 7001L, "Emberline", 41L, "R-1", "jwt"); SessionContext missingGameInstance = - new SessionContext(1L, 22L, 123L, "demo@example.com", 7001L, "Emberline", 0L, "R-1", "jwt"); + new SessionContext( + 1L, 22L, "123", "demo@example.com", 7001L, "Emberline", 0L, "R-1", "jwt"); SessionContext missingCharacter = - new SessionContext(1L, 22L, 123L, "demo@example.com", 0L, null, 41L, "R-1", "jwt"); + new SessionContext(1L, 22L, "123", "demo@example.com", 0L, null, 41L, "R-1", "jwt"); assertTrue(complete.hasGameplayIdentity()); assertFalse(missingGameInstance.hasGameplayIdentity()); diff --git a/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/service/SessionRoutingNormalizationServiceTest.java b/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/service/SessionRoutingNormalizationServiceTest.java index 04c9c0108b..baf818cd02 100644 --- a/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/service/SessionRoutingNormalizationServiceTest.java +++ b/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/service/SessionRoutingNormalizationServiceTest.java @@ -31,7 +31,7 @@ void resolveProjectedSessionContextFailsClosedWhenTenantScopedSessionIsMissing() new SessionContext( 41L, 22L, - 123L, + "123", "demo@example.com", 7001L, "Emberline", @@ -77,7 +77,7 @@ void normalizeProjectedContextClearsPartialGameplayShellWhenAdmissionPointerCann new SessionContext( 41L, 22L, - 123L, + "123", "demo@example.com", 7001L, "Emberline", @@ -109,7 +109,7 @@ void normalizeProjectedContextClearsLegacyRuntimeRoomBindingBeforePointerChecks( new SessionContext( 41L, 22L, - 123L, + "123", "demo@example.com", 7001L, "Emberline", diff --git a/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/service/impl/AccountPresenceQueryServiceImplTest.java b/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/service/impl/AccountPresenceQueryServiceImplTest.java index 929f616c8c..f71d635e40 100644 --- a/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/service/impl/AccountPresenceQueryServiceImplTest.java +++ b/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/service/impl/AccountPresenceQueryServiceImplTest.java @@ -35,13 +35,13 @@ void queryAccountPresenceReturnsOnlineAndOfflineSnapshotsInRequestOrder() { when(recentPresenceService.findByAccountIds( org.mockito.Mockito.eq(1L), org.mockito.ArgumentMatchers.argThat( - ids -> ids != null && ids.containsAll(List.of(3L, 4L)) && ids.size() == 2))) + ids -> ids != null && ids.containsAll(List.of("3", "4")) && ids.size() == 2))) .thenReturn( java.util.Map.of( - 4L, + "4", new AccountRecentPresenceState( 1L, - 4L, + "4", 2L, "SHARED", "sandbox", @@ -52,10 +52,10 @@ void queryAccountPresenceReturnsOnlineAndOfflineSnapshotsInRequestOrder() { when(presenceService.listConnectedByAccountIds( org.mockito.Mockito.eq(1L), org.mockito.ArgumentMatchers.argThat( - ids -> ids != null && ids.containsAll(List.of(3L, 4L)) && ids.size() == 2))) + ids -> ids != null && ids.containsAll(List.of("3", "4")) && ids.size() == 2))) .thenReturn( Map.of( - 3L, + "3", List.of( new GameplayPresence( 97L, @@ -65,7 +65,7 @@ void queryAccountPresenceReturnsOnlineAndOfflineSnapshotsInRequestOrder() { "sandbox", "production", 17L, - 3L, + "3", 99L, "Ben", GameplayPresenceRole.PLAYER, @@ -78,10 +78,10 @@ void queryAccountPresenceReturnsOnlineAndOfflineSnapshotsInRequestOrder() { List.of( pointer("sandbox", "Builder Sandbox", "production", "Live Realm", 1L, 2L, 17L))); - var result = service.queryAccountPresence(1L, 2L, List.of(3L, 4L)); + var result = service.queryAccountPresence(1L, "2", List.of("3", "4")); assertEquals(2, result.size()); - assertEquals(3L, result.get(0).accountId()); + assertEquals("3", result.get(0).accountId()); assertEquals(true, result.get(0).online()); assertEquals(2L, result.get(0).gameInstanceId()); assertEquals("sandbox", result.get(0).worldSlug()); @@ -94,7 +94,7 @@ void queryAccountPresenceReturnsOnlineAndOfflineSnapshotsInRequestOrder() { net.firedevops.firemud.gamesession.service.GameplayPresenceActivityState.EXPLICIT_AFK, result.get(0).activityState()); assertEquals(null, result.get(0).recentDisposition()); - assertEquals(4L, result.get(1).accountId()); + assertEquals("4", result.get(1).accountId()); assertEquals(false, result.get(1).online()); assertEquals(2L, result.get(1).gameInstanceId()); assertEquals("sandbox", result.get(1).worldSlug()); @@ -122,13 +122,13 @@ void queryAccountPresenceIgnoresStaleLivePresenceAndKeepsOfflineSnapshot() { when(recentPresenceService.findByAccountIds( org.mockito.Mockito.eq(1L), org.mockito.ArgumentMatchers.argThat( - ids -> ids != null && ids.contains(3L) && ids.size() == 1))) + ids -> ids != null && ids.contains("3") && ids.size() == 1))) .thenReturn( Map.of( - 3L, + "3", new AccountRecentPresenceState( 1L, - 3L, + "3", 9L, "SHARED", "sandbox", @@ -139,10 +139,10 @@ void queryAccountPresenceIgnoresStaleLivePresenceAndKeepsOfflineSnapshot() { when(presenceService.listConnectedByAccountIds( org.mockito.Mockito.eq(1L), org.mockito.ArgumentMatchers.argThat( - ids -> ids != null && ids.contains(3L) && ids.size() == 1))) + ids -> ids != null && ids.contains("3") && ids.size() == 1))) .thenReturn( Map.of( - 3L, + "3", List.of( new GameplayPresence( 97L, @@ -152,7 +152,7 @@ void queryAccountPresenceIgnoresStaleLivePresenceAndKeepsOfflineSnapshot() { "sandbox", "production", 18L, - 3L, + "3", 99L, "Ben", GameplayPresenceRole.PLAYER, @@ -165,7 +165,7 @@ void queryAccountPresenceIgnoresStaleLivePresenceAndKeepsOfflineSnapshot() { List.of( pointer("sandbox", "Builder Sandbox", "production", "Live Realm", 1L, 2L, 17L))); - var result = service.queryAccountPresence(1L, 2L, List.of(3L)); + var result = service.queryAccountPresence(1L, "2", List.of("3")); assertEquals(1, result.size()); assertEquals(false, result.get(0).online()); @@ -188,13 +188,13 @@ void queryAccountPresenceIgnoresLivePresenceWithZeroPointerVersionAndKeepsOfflin when(recentPresenceService.findByAccountIds( org.mockito.Mockito.eq(1L), org.mockito.ArgumentMatchers.argThat( - ids -> ids != null && ids.contains(3L) && ids.size() == 1))) + ids -> ids != null && ids.contains("3") && ids.size() == 1))) .thenReturn( Map.of( - 3L, + "3", new AccountRecentPresenceState( 1L, - 3L, + "3", 2L, "SHARED", "sandbox", @@ -205,10 +205,10 @@ void queryAccountPresenceIgnoresLivePresenceWithZeroPointerVersionAndKeepsOfflin when(presenceService.listConnectedByAccountIds( org.mockito.Mockito.eq(1L), org.mockito.ArgumentMatchers.argThat( - ids -> ids != null && ids.contains(3L) && ids.size() == 1))) + ids -> ids != null && ids.contains("3") && ids.size() == 1))) .thenReturn( Map.of( - 3L, + "3", List.of( new GameplayPresence( 97L, @@ -218,7 +218,7 @@ void queryAccountPresenceIgnoresLivePresenceWithZeroPointerVersionAndKeepsOfflin "sandbox", "production", 0L, - 3L, + "3", 99L, "Ben", GameplayPresenceRole.PLAYER, @@ -231,7 +231,7 @@ void queryAccountPresenceIgnoresLivePresenceWithZeroPointerVersionAndKeepsOfflin List.of( pointer("sandbox", "Builder Sandbox", "production", "Live Realm", 1L, 2L, 17L))); - var result = service.queryAccountPresence(1L, 2L, List.of(3L)); + var result = service.queryAccountPresence(1L, "2", List.of("3")); assertEquals(1, result.size()); assertEquals(false, result.get(0).online()); @@ -257,13 +257,13 @@ void queryAccountPresenceIgnoresLivePresenceWithBlankWorldSlugAndKeepsOfflineSna when(recentPresenceService.findByAccountIds( org.mockito.Mockito.eq(1L), org.mockito.ArgumentMatchers.argThat( - ids -> ids != null && ids.contains(3L) && ids.size() == 1))) + ids -> ids != null && ids.contains("3") && ids.size() == 1))) .thenReturn( Map.of( - 3L, + "3", new AccountRecentPresenceState( 1L, - 3L, + "3", 2L, "SHARED", "sandbox", @@ -274,10 +274,10 @@ void queryAccountPresenceIgnoresLivePresenceWithBlankWorldSlugAndKeepsOfflineSna when(presenceService.listConnectedByAccountIds( org.mockito.Mockito.eq(1L), org.mockito.ArgumentMatchers.argThat( - ids -> ids != null && ids.contains(3L) && ids.size() == 1))) + ids -> ids != null && ids.contains("3") && ids.size() == 1))) .thenReturn( Map.of( - 3L, + "3", List.of( new GameplayPresence( 97L, @@ -287,7 +287,7 @@ void queryAccountPresenceIgnoresLivePresenceWithBlankWorldSlugAndKeepsOfflineSna " ", "production", 17L, - 3L, + "3", 99L, "Ben", GameplayPresenceRole.PLAYER, @@ -300,7 +300,7 @@ void queryAccountPresenceIgnoresLivePresenceWithBlankWorldSlugAndKeepsOfflineSna List.of( pointer("sandbox", "Builder Sandbox", "production", "Live Realm", 1L, 2L, 17L))); - var result = service.queryAccountPresence(1L, 2L, List.of(3L)); + var result = service.queryAccountPresence(1L, "2", List.of("3")); assertEquals(1, result.size()); assertEquals(false, result.get(0).online()); @@ -326,15 +326,15 @@ void queryAccountPresencePrefersCurrentPresenceOverMoreRecentStaleSession() { when(recentPresenceService.findByAccountIds( org.mockito.Mockito.eq(1L), org.mockito.ArgumentMatchers.argThat( - ids -> ids != null && ids.contains(3L) && ids.size() == 1))) + ids -> ids != null && ids.contains("3") && ids.size() == 1))) .thenReturn(Map.of()); when(presenceService.listConnectedByAccountIds( org.mockito.Mockito.eq(1L), org.mockito.ArgumentMatchers.argThat( - ids -> ids != null && ids.contains(3L) && ids.size() == 1))) + ids -> ids != null && ids.contains("3") && ids.size() == 1))) .thenReturn( Map.of( - 3L, + "3", List.of( new GameplayPresence( 97L, @@ -344,7 +344,7 @@ void queryAccountPresencePrefersCurrentPresenceOverMoreRecentStaleSession() { "sandbox", "production", 18L, - 3L, + "3", 99L, "Ben", GameplayPresenceRole.PLAYER, @@ -360,7 +360,7 @@ void queryAccountPresencePrefersCurrentPresenceOverMoreRecentStaleSession() { "sandbox", "production", 17L, - 3L, + "3", 100L, "Ben", GameplayPresenceRole.PLAYER, @@ -373,7 +373,7 @@ void queryAccountPresencePrefersCurrentPresenceOverMoreRecentStaleSession() { List.of( pointer("sandbox", "Builder Sandbox", "production", "Live Realm", 1L, 2L, 17L))); - var result = service.queryAccountPresence(1L, 2L, List.of(3L)); + var result = service.queryAccountPresence(1L, "2", List.of("3")); assertEquals(1, result.size()); assertEquals(true, result.get(0).online()); @@ -397,13 +397,13 @@ void queryAccountPresenceFailsClosedWhenRuntimeAuthorityIsAmbiguous() { when(recentPresenceService.findByAccountIds( org.mockito.Mockito.eq(1L), org.mockito.ArgumentMatchers.argThat( - ids -> ids != null && ids.contains(3L) && ids.size() == 1))) + ids -> ids != null && ids.contains("3") && ids.size() == 1))) .thenReturn( Map.of( - 3L, + "3", new AccountRecentPresenceState( 1L, - 3L, + "3", 2L, "SHARED", "sandbox", @@ -414,10 +414,10 @@ void queryAccountPresenceFailsClosedWhenRuntimeAuthorityIsAmbiguous() { when(presenceService.listConnectedByAccountIds( org.mockito.Mockito.eq(1L), org.mockito.ArgumentMatchers.argThat( - ids -> ids != null && ids.contains(3L) && ids.size() == 1))) + ids -> ids != null && ids.contains("3") && ids.size() == 1))) .thenReturn( Map.of( - 3L, + "3", List.of( new GameplayPresence( 97L, @@ -427,7 +427,7 @@ void queryAccountPresenceFailsClosedWhenRuntimeAuthorityIsAmbiguous() { "sandbox", "production", 17L, - 3L, + "3", 99L, "Ben", GameplayPresenceRole.PLAYER, @@ -441,7 +441,7 @@ void queryAccountPresenceFailsClosedWhenRuntimeAuthorityIsAmbiguous() { pointer("sandbox", "Builder Sandbox", "production", "Live Realm", 1L, 2L, 17L), pointer("sandbox", "Builder Sandbox", "preview", "Preview Realm", 1L, 2L, 18L))); - var result = service.queryAccountPresence(1L, 2L, List.of(3L)); + var result = service.queryAccountPresence(1L, "2", List.of("3")); assertEquals(1, result.size()); assertEquals(false, result.get(0).online()); @@ -467,13 +467,13 @@ void queryAccountPresenceFailsClosedWhenSingularRuntimeAuthorityIsIncomplete() { when(recentPresenceService.findByAccountIds( org.mockito.Mockito.eq(1L), org.mockito.ArgumentMatchers.argThat( - ids -> ids != null && ids.contains(3L) && ids.size() == 1))) + ids -> ids != null && ids.contains("3") && ids.size() == 1))) .thenReturn( Map.of( - 3L, + "3", new AccountRecentPresenceState( 1L, - 3L, + "3", 2L, "SHARED", "sandbox", @@ -484,10 +484,10 @@ void queryAccountPresenceFailsClosedWhenSingularRuntimeAuthorityIsIncomplete() { when(presenceService.listConnectedByAccountIds( org.mockito.Mockito.eq(1L), org.mockito.ArgumentMatchers.argThat( - ids -> ids != null && ids.contains(3L) && ids.size() == 1))) + ids -> ids != null && ids.contains("3") && ids.size() == 1))) .thenReturn( Map.of( - 3L, + "3", List.of( new GameplayPresence( 97L, @@ -497,7 +497,7 @@ void queryAccountPresenceFailsClosedWhenSingularRuntimeAuthorityIsIncomplete() { "sandbox", "production", 17L, - 3L, + "3", 99L, "Ben", GameplayPresenceRole.PLAYER, @@ -522,7 +522,7 @@ void queryAccountPresenceFailsClosedWhenSingularRuntimeAuthorityIsIncomplete() { "", "ALLOW_NEW"))); - var result = service.queryAccountPresence(1L, 2L, List.of(3L)); + var result = service.queryAccountPresence(1L, "2", List.of("3")); assertEquals(1, result.size()); assertEquals(false, result.get(0).online()); @@ -548,15 +548,15 @@ void queryAccountPresenceTreatsCaseInsensitiveLiveRoutingIdentityAsCurrent() { when(recentPresenceService.findByAccountIds( org.mockito.Mockito.eq(1L), org.mockito.ArgumentMatchers.argThat( - ids -> ids != null && ids.contains(3L) && ids.size() == 1))) + ids -> ids != null && ids.contains("3") && ids.size() == 1))) .thenReturn(Map.of()); when(presenceService.listConnectedByAccountIds( org.mockito.Mockito.eq(1L), org.mockito.ArgumentMatchers.argThat( - ids -> ids != null && ids.contains(3L) && ids.size() == 1))) + ids -> ids != null && ids.contains("3") && ids.size() == 1))) .thenReturn( Map.of( - 3L, + "3", List.of( new GameplayPresence( 97L, @@ -566,7 +566,7 @@ void queryAccountPresenceTreatsCaseInsensitiveLiveRoutingIdentityAsCurrent() { "Sandbox", "Production", 17L, - 3L, + "3", 99L, "Ben", GameplayPresenceRole.PLAYER, @@ -579,7 +579,7 @@ void queryAccountPresenceTreatsCaseInsensitiveLiveRoutingIdentityAsCurrent() { List.of( pointer("sandbox", "Builder Sandbox", "production", "Live Realm", 1L, 2L, 17L))); - var result = service.queryAccountPresence(1L, 2L, List.of(3L)); + var result = service.queryAccountPresence(1L, "2", List.of("3")); assertEquals(1, result.size()); assertEquals(true, result.get(0).online()); @@ -604,13 +604,13 @@ void queryAccountPresenceTreatsCaseInsensitiveRecentRoutingIdentityAsCurrent() { when(recentPresenceService.findByAccountIds( org.mockito.Mockito.eq(1L), org.mockito.ArgumentMatchers.argThat( - ids -> ids != null && ids.contains(4L) && ids.size() == 1))) + ids -> ids != null && ids.contains("4") && ids.size() == 1))) .thenReturn( Map.of( - 4L, + "4", new AccountRecentPresenceState( 1L, - 4L, + "4", 2L, "SHARED", "Sandbox", @@ -621,14 +621,14 @@ void queryAccountPresenceTreatsCaseInsensitiveRecentRoutingIdentityAsCurrent() { when(presenceService.listConnectedByAccountIds( org.mockito.Mockito.eq(1L), org.mockito.ArgumentMatchers.argThat( - ids -> ids != null && ids.contains(4L) && ids.size() == 1))) + ids -> ids != null && ids.contains("4") && ids.size() == 1))) .thenReturn(Map.of()); when(pointerAuthorityService.listByRuntimeTarget(1L, 2L)) .thenReturn( List.of( pointer("sandbox", "Builder Sandbox", "production", "Live Realm", 1L, 2L, 17L))); - var result = service.queryAccountPresence(1L, 2L, List.of(4L)); + var result = service.queryAccountPresence(1L, "2", List.of("4")); assertEquals(1, result.size()); assertEquals(false, result.get(0).online()); diff --git a/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/service/impl/AutomationScriptEventPublisherTest.java b/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/service/impl/AutomationScriptEventPublisherTest.java index ed1e38edbf..ff127124c2 100644 --- a/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/service/impl/AutomationScriptEventPublisherTest.java +++ b/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/service/impl/AutomationScriptEventPublisherTest.java @@ -846,7 +846,7 @@ private static SessionContext gameplayContext(String roomId, String playableStat return new SessionContext( 17L, 9L, - 3L, + "3", "demo", 44L, "char", diff --git a/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/service/impl/CommandServiceImplTest.java b/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/service/impl/CommandServiceImplTest.java index 7cac76b022..445226cea6 100644 --- a/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/service/impl/CommandServiceImplTest.java +++ b/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/service/impl/CommandServiceImplTest.java @@ -7,6 +7,7 @@ import static org.mockito.Mockito.times; import static org.mockito.Mockito.verify; +import java.util.List; import java.util.Optional; import java.util.concurrent.atomic.AtomicLong; import net.firedevops.firemud.gamesession.dto.CommandEnqueueResult; @@ -179,6 +180,49 @@ void enqueueRejectsNegativeSessionIdBeforeSessionLookup() { Mockito.anyBoolean()); } + @Test + void enqueueRejectsUnsupportedAccountIdBeforePersistenceOrQueueing() { + for (String accountId : List.of("6ba7b810-9dad-11d1-80b4-00c04fd430c8", "0", "-1")) { + TickService tickService = Mockito.mock(TickService.class); + SessionRateLimiter rateLimiter = Mockito.mock(SessionRateLimiter.class); + GameInstanceRepository repository = Mockito.mock(GameInstanceRepository.class); + GameplayCommandRepository commandRepository = Mockito.mock(GameplayCommandRepository.class); + SessionAuthenticationService sessionAuthenticationService = + identitySessionAuthenticationService(); + Mockito.when(sessionAuthenticationService.resolveUnverifiedSessionContext("17")) + .thenReturn( + Optional.of( + new SessionContext(17L, 9L, accountId, "demo", 44L, "char", 99L, "R-1", "jwt"))); + CommandServiceImpl service = + newCommandService( + tickService, + rateLimiter, + repository, + commandRepository, + sessionAuthenticationService, + Mockito.mock(GameplayAdmissionPointerAuthorityService.class), + Mockito.mock(ScriptEventPublisher.class)); + + CommandEnqueueResult result = service.enqueue("17", "look", false); + + assertTrue(result.hasError()); + assertEquals("INVALID_ARGUMENT", result.errorCode()); + assertEquals( + accountId.equals("0") || accountId.equals("-1") + ? "accountId must be positive" + : "accountId must be numeric", + result.errorMessage()); + verify(commandRepository, never()).save(Mockito.any()); + verify(tickService, never()) + .enqueueCommand( + Mockito.anyLong(), + Mockito.anyLong(), + Mockito.anyString(), + Mockito.anyString(), + Mockito.anyBoolean()); + } + } + @Test void enqueuePassesThroughWhenAllowed() { TickService tickService = Mockito.mock(TickService.class); @@ -311,7 +355,7 @@ void gameplayCommandsQueueAgainstGameInstanceWhenSessionContextHasOne() { Mockito.mock(GameplayAdmissionPointerAuthorityService.class); Mockito.when(sessionAuthenticationService.resolveUnverifiedSessionContext("17")) .thenReturn( - Optional.of(new SessionContext(17L, 9L, 3L, "demo", 44L, "char", 99L, "R-1", "jwt"))); + Optional.of(new SessionContext(17L, 9L, "3", "demo", 44L, "char", 99L, "R-1", "jwt"))); GameplayCommandRepository commandRepository = commandRepositorySavingArgument(); ScriptEventPublisher scriptEventPublisher = Mockito.mock(ScriptEventPublisher.class); CommandServiceImpl service = @@ -327,11 +371,48 @@ void gameplayCommandsQueueAgainstGameInstanceWhenSessionContextHasOne() { CommandEnqueueResult result = service.enqueue("17", "look", false); assertTrue(result.accepted()); + org.mockito.ArgumentCaptor commandCaptor = + org.mockito.ArgumentCaptor.forClass(GameplayCommand.class); + verify(commandRepository).save(commandCaptor.capture()); + assertEquals(3L, commandCaptor.getValue().getAccountId()); + assertNull(commandCaptor.getValue().getAccountUuid()); verify(tickService, times(1)).enqueueCommand(9L, 99L, result.commandId(), "look", false); verify(scriptEventPublisher, times(1)) .publishCommandEvent(Mockito.any(SessionContext.class), Mockito.any(GameplayCommand.class)); } + @Test + void gameplayCommandWithoutAccountIdKeepsNumericHistoryAbsent() { + TickService tickService = Mockito.mock(TickService.class); + SessionRateLimiter rateLimiter = Mockito.mock(SessionRateLimiter.class); + Mockito.when(rateLimiter.allow(17L)).thenReturn(true); + GameInstanceRepository repository = Mockito.mock(GameInstanceRepository.class); + SessionAuthenticationService sessionAuthenticationService = + identitySessionAuthenticationService(); + Mockito.when(sessionAuthenticationService.resolveUnverifiedSessionContext("17")) + .thenReturn( + Optional.of(new SessionContext(17L, 9L, null, "demo", 44L, "char", 99L, "R-1", "jwt"))); + GameplayCommandRepository commandRepository = commandRepositorySavingArgument(); + CommandServiceImpl service = + newCommandService( + tickService, + rateLimiter, + repository, + commandRepository, + sessionAuthenticationService, + Mockito.mock(GameplayAdmissionPointerAuthorityService.class), + Mockito.mock(ScriptEventPublisher.class)); + + CommandEnqueueResult result = service.enqueue("17", "look", false); + + assertTrue(result.accepted()); + org.mockito.ArgumentCaptor commandCaptor = + org.mockito.ArgumentCaptor.forClass(GameplayCommand.class); + verify(commandRepository).save(commandCaptor.capture()); + assertNull(commandCaptor.getValue().getAccountId()); + assertNull(commandCaptor.getValue().getAccountUuid()); + } + @Test void gameplayCommandsPersistCurrentRuntimeScopeForDurableCommandEventFallback() { TickService tickService = Mockito.mock(TickService.class); @@ -350,7 +431,7 @@ void gameplayCommandsPersistCurrentRuntimeScopeForDurableCommandEventFallback() new SessionContext( 17L, 9L, - 3L, + "3", "demo", 44L, "char", @@ -403,7 +484,7 @@ void gameplayCommandFailsBeforePersistenceWhenRuntimeOwnershipIsNotEstablished() Mockito.when(sessionAuthenticationService.resolveUnverifiedSessionContext("17")) .thenReturn( Optional.of( - new SessionContext(17L, 9L, 3L, "demo", 44L, "char", 99L, "region-99", "jwt"))); + new SessionContext(17L, 9L, "3", "demo", 44L, "char", 99L, "region-99", "jwt"))); Mockito.when(runtimeRegionStatusRepository.findByTenantIdAndGameInstanceId(9L, 99L)) .thenReturn(Optional.empty()); CommandServiceImpl service = @@ -445,7 +526,7 @@ void gameplayCommandFailsClosedWhenRuntimeOwnershipReadFails() { Mockito.when(sessionAuthenticationService.resolveUnverifiedSessionContext("17")) .thenReturn( Optional.of( - new SessionContext(17L, 9L, 3L, "demo", 44L, "char", 99L, "region-99", "jwt"))); + new SessionContext(17L, 9L, "3", "demo", 44L, "char", 99L, "region-99", "jwt"))); Mockito.when(runtimeRegionStatusRepository.findByTenantIdAndGameInstanceId(9L, 99L)) .thenThrow(new IllegalStateException("runtime ownership unavailable")); CommandServiceImpl service = @@ -489,7 +570,7 @@ void bootstrapShellQueuesAgainstBootstrapRuntimeWhenSessionIdDiffers() { new SessionContext( 17L, 9L, - 0L, + null, null, 0L, null, @@ -536,7 +617,7 @@ void staleNormalizedGameplaySessionFailsClosedWithoutBootstrapRoutingBundle() { Mockito.mock(GameplayAdmissionPointerAuthorityService.class); SessionContext cleared = new SessionContext( - 17L, 9L, 3L, "demo", 0L, null, 0L, null, "jwt", null, 99L, null, null, 0L, null); + 17L, 9L, "3", "demo", 0L, null, 0L, null, "jwt", null, 99L, null, null, 0L, null); Mockito.when(sessionAuthenticationService.resolveUnverifiedSessionContext("17")) .thenReturn(Optional.of(cleared)); GameplayCommandRepository commandRepository = commandRepositorySavingArgument(); @@ -579,7 +660,7 @@ void enqueueAddsGameplayLoggingContextWhenSessionIsBound() { Mockito.mock(GameplayAdmissionPointerAuthorityService.class); Mockito.when(sessionAuthenticationService.resolveUnverifiedSessionContext("17")) .thenReturn( - Optional.of(new SessionContext(17L, 9L, 3L, "demo", 44L, "char", 99L, "R-1", "jwt"))); + Optional.of(new SessionContext(17L, 9L, "3", "demo", 44L, "char", 99L, "R-1", "jwt"))); GameplayCommandRepository commandRepository = commandRepositorySavingArgument(); Mockito.doAnswer( invocation -> { @@ -629,7 +710,7 @@ void loginCommandsAreRedactedFromLogs(CapturedOutput output) { Mockito.mock(GameplayAdmissionPointerAuthorityService.class); Mockito.when(sessionAuthenticationService.resolveUnverifiedSessionContext("17")) .thenReturn( - Optional.of(new SessionContext(17L, 9L, 3L, "demo", 44L, "char", 99L, "R-1", "jwt"))); + Optional.of(new SessionContext(17L, 9L, "3", "demo", 44L, "char", 99L, "R-1", "jwt"))); GameplayCommandRepository commandRepository = commandRepositorySavingArgument(); CommandServiceImpl service = newCommandService( @@ -668,7 +749,7 @@ void loginCommandPersistsBootstrapRoutingMetadataFromAuthority() { new SessionContext( 17L, 9L, - 3L, + "3", "demo", 0L, null, @@ -732,7 +813,7 @@ void loginCommandPersistsBootstrapRoutingMetadataFromUnambiguousRuntimeAuthority GameplayAdmissionPointerAuthorityService pointerAuthorityService = Mockito.mock(GameplayAdmissionPointerAuthorityService.class); Mockito.when(sessionAuthenticationService.resolveUnverifiedSessionContext("17")) - .thenReturn(Optional.of(bootstrapShell(17L, 9L, 99L, 3L, "demo", "jwt"))); + .thenReturn(Optional.of(bootstrapShell(17L, 9L, 99L, "3", "demo", "jwt"))); Mockito.when(pointerAuthorityService.listByRuntimeTarget(9L, 99L)) .thenReturn( java.util.List.of( @@ -784,7 +865,7 @@ void loginCommandDropsBootstrapRoutingMetadataWhenRuntimeAuthorityIsAmbiguous() GameplayAdmissionPointerAuthorityService pointerAuthorityService = Mockito.mock(GameplayAdmissionPointerAuthorityService.class); Mockito.when(sessionAuthenticationService.resolveUnverifiedSessionContext("17")) - .thenReturn(Optional.of(bootstrapShell(17L, 9L, 99L, 3L, "demo", "jwt"))); + .thenReturn(Optional.of(bootstrapShell(17L, 9L, 99L, "3", "demo", "jwt"))); Mockito.when(pointerAuthorityService.listByRuntimeTarget(9L, 99L)) .thenReturn( java.util.List.of( @@ -849,7 +930,7 @@ void loginCommandDropsBootstrapRoutingMetadataWhenSingularRuntimeAuthorityIsInco GameplayAdmissionPointerAuthorityService pointerAuthorityService = Mockito.mock(GameplayAdmissionPointerAuthorityService.class); Mockito.when(sessionAuthenticationService.resolveUnverifiedSessionContext("17")) - .thenReturn(Optional.of(bootstrapShell(17L, 9L, 99L, 3L, "demo", "jwt"))); + .thenReturn(Optional.of(bootstrapShell(17L, 9L, 99L, "3", "demo", "jwt"))); Mockito.when(pointerAuthorityService.listByRuntimeTarget(9L, 99L)) .thenReturn( java.util.List.of( @@ -906,7 +987,7 @@ void gameplayCommandRepairsPartialSessionRoutingMetadataFromAuthority() { new SessionContext( 17L, 9L, - 3L, + "3", "demo", 44L, "char", @@ -973,8 +1054,8 @@ void gameplayCommandRepairsPointerOnlySessionRoutingMetadataFromRuntimeAuthority .thenReturn( Optional.of( new SessionContext( - 17L, 9L, 3L, "demo", 44L, "char", 99L, "R-1", "jwt", null, 99L, null, null, 17L, - "SHARED"))); + 17L, 9L, "3", "demo", 44L, "char", 99L, "R-1", "jwt", null, 99L, null, null, + 17L, "SHARED"))); Mockito.when(pointerAuthorityService.listByRuntimeTarget(9L, 99L)) .thenReturn( java.util.List.of( @@ -1031,7 +1112,7 @@ void gameplayCommandUsesActiveGameplayRuntimeAuthorityBeforeBootstrapRuntime() { new SessionContext( 17L, 9L, - 3L, + "3", "demo", 44L, "char", @@ -1103,7 +1184,7 @@ void gameplayCommandRepairsStaleCompleteSessionRoutingMetadataFromCurrentAuthori new SessionContext( 17L, 9L, - 3L, + "3", "demo", 0L, null, @@ -1172,7 +1253,7 @@ void gameplayCommandDropsStaleCompleteSessionRoutingMetadataWhenCurrentAuthority new SessionContext( 17L, 9L, - 3L, + "3", "demo", 0L, null, @@ -1227,7 +1308,7 @@ void gameplayCommandDropsPartialSessionRoutingMetadataWhenAuthorityCannotRepairI new SessionContext( 17L, 9L, - 3L, + "3", "demo", 44L, "char", @@ -1282,7 +1363,7 @@ void gameplayCommandDropsSessionRoutingMetadataWhenCurrentSelectorPointerIsIncom new SessionContext( 17L, 9L, - 3L, + "3", "demo", 44L, "char", @@ -1347,7 +1428,7 @@ void queueValidationFailureMarksPersistedCommandFailed() { Mockito.mock(GameplayAdmissionPointerAuthorityService.class); Mockito.when(sessionAuthenticationService.resolveUnverifiedSessionContext("17")) .thenReturn( - Optional.of(new SessionContext(17L, 9L, 3L, "demo", 44L, "char", 99L, "R-1", "jwt"))); + Optional.of(new SessionContext(17L, 9L, "3", "demo", 44L, "char", 99L, "R-1", "jwt"))); GameplayCommandRepository commandRepository = commandRepositorySavingArgument(); Mockito.doThrow(new IllegalArgumentException("bad command")) .when(tickService) @@ -1471,14 +1552,14 @@ private SessionAuthenticationService identitySessionAuthenticationService() { private SessionContext bootstrapShell( long sessionId, long tenantId, long bootstrapGameInstanceId) { - return bootstrapShell(sessionId, tenantId, bootstrapGameInstanceId, 0L, null, null); + return bootstrapShell(sessionId, tenantId, bootstrapGameInstanceId, null, null, null); } private SessionContext bootstrapShell( long sessionId, long tenantId, long bootstrapGameInstanceId, - long accountId, + String accountId, String loginName, String jwt) { return new SessionContext( diff --git a/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/service/impl/DefaultDurableGameplayCommandExecutionServiceTest.java b/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/service/impl/DefaultDurableGameplayCommandExecutionServiceTest.java index ee91785206..b1512de3ce 100644 --- a/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/service/impl/DefaultDurableGameplayCommandExecutionServiceTest.java +++ b/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/service/impl/DefaultDurableGameplayCommandExecutionServiceTest.java @@ -167,9 +167,9 @@ void executeDoesNotInferActionStateFromCombatMetadata() { @Test void executeReturnsReplayNoOpForIdempotentMoveReplay() { SessionContext context = - new SessionContext(42L, 22L, 7L, "demo@example.com", 91L, "Demo", 5L, "R-1", "jwt-token"); + new SessionContext(42L, 22L, "7", "demo@example.com", 91L, "Demo", 5L, "R-1", "jwt-token"); SessionContext moved = - new SessionContext(42L, 22L, 7L, "demo@example.com", 91L, "Demo", 5L, "R-2", "jwt-token"); + new SessionContext(42L, 22L, "7", "demo@example.com", 91L, "Demo", 5L, "R-2", "jwt-token"); GameplayCommand command = gameplayCommand("MOVE", "north"); TickEffect effect = tickEffect("tfx-1", "cmd-1"); PlayerOutput output = PlayerOutput.message("You move north."); @@ -203,9 +203,9 @@ void executeReturnsReplayNoOpForIdempotentMoveReplay() { @Test void executePublishesMovementLifecycleEventsAfterFirstApply() { SessionContext context = - new SessionContext(42L, 22L, 7L, "demo@example.com", 91L, "Demo", 5L, "R-1", "jwt-token"); + new SessionContext(42L, 22L, "7", "demo@example.com", 91L, "Demo", 5L, "R-1", "jwt-token"); SessionContext moved = - new SessionContext(42L, 22L, 7L, "demo@example.com", 91L, "Demo", 5L, "R-2", "jwt-token"); + new SessionContext(42L, 22L, "7", "demo@example.com", 91L, "Demo", 5L, "R-2", "jwt-token"); GameplayCommand command = gameplayCommand("MOVE", "north"); TickEffect effect = tickEffect("tfx-9", "cmd-9"); when(parser.parse("north")) @@ -228,7 +228,7 @@ void executePublishesMovementLifecycleEventsAfterFirstApply() { @Test void executeAppliesDurableItemMutationAndDeliversOutput() { SessionContext context = - new SessionContext(42L, 22L, 7L, "demo@example.com", 91L, "Demo", 5L, "R-1", "jwt-token"); + new SessionContext(42L, 22L, "7", "demo@example.com", 91L, "Demo", 5L, "R-1", "jwt-token"); GameplayCommand command = gameplayCommand("GET", "GET torch"); TickEffect effect = tickEffect("tfx-2", "cmd-2"); TextCommand parsed = @@ -263,7 +263,7 @@ void executeAppliesDurableItemMutationAndDeliversOutput() { @Test void executeRejectsDurableItemMutationAndDeliversOutput() { SessionContext context = - new SessionContext(42L, 22L, 7L, "demo@example.com", 91L, "Demo", 5L, "R-1", "jwt-token"); + new SessionContext(42L, 22L, "7", "demo@example.com", 91L, "Demo", 5L, "R-1", "jwt-token"); GameplayCommand command = gameplayCommand("PUT", "PUT ration INTO torch"); TickEffect effect = tickEffect("tfx-3", "cmd-3"); TextCommand parsed = @@ -309,7 +309,7 @@ void executeRejectsDurableItemMutationAndDeliversOutput() { @Test void executeAppliesDurableCommunicationAndDeliversOutput() { SessionContext context = - new SessionContext(42L, 22L, 7L, "demo@example.com", 91L, "Demo", 5L, "R-1", "jwt-token"); + new SessionContext(42L, 22L, "7", "demo@example.com", 91L, "Demo", 5L, "R-1", "jwt-token"); GameplayCommand command = gameplayCommand("SAY", "SAY Hello there"); TickEffect effect = tickEffect("tfx-4", "cmd-4"); TextCommand parsed = @@ -338,7 +338,7 @@ void executeAppliesDurableCommunicationAndDeliversOutput() { @Test void executeNormalizesStaleSessionContextBeforeDurableGameplayHandling() { SessionContext cleared = - new SessionContext(42L, 22L, 7L, "demo@example.com", 0L, null, 0L, null, "jwt-token"); + new SessionContext(42L, 22L, "7", "demo@example.com", 0L, null, 0L, null, "jwt-token"); GameplayCommand command = gameplayCommand("GET", "GET torch"); TickEffect effect = tickEffect("tfx-stale", "cmd-stale"); TextCommand parsed = @@ -369,7 +369,7 @@ void executeNormalizesStaleSessionContextBeforeDurableGameplayHandling() { @Test void executeResolvesAutomationCommandByGameplayIdentityWhenSessionIdIsUnset() { SessionContext context = - new SessionContext(42L, 22L, 7L, "demo@example.com", 91L, "Demo", 5L, "R-1", "jwt-token"); + new SessionContext(42L, 22L, "7", "demo@example.com", 91L, "Demo", 5L, "R-1", "jwt-token"); GameplayCommand command = gameplayCommand("SAY", "SAY Hello there"); command.setSessionId(0L); command.setTenantId(22L); @@ -445,7 +445,7 @@ void executeRejectsSessionlessCommandWhenTargetEntityIdIsNonPositive() { @Test void executeAppliesDurableAfkAndDeliversOutput() { SessionContext context = - new SessionContext(42L, 22L, 7L, "demo@example.com", 91L, "Demo", 5L, "R-1", "jwt-token"); + new SessionContext(42L, 22L, "7", "demo@example.com", 91L, "Demo", 5L, "R-1", "jwt-token"); GameplayCommand command = gameplayCommand("BRB", "BRB"); TickEffect effect = tickEffect("tfx-5", "cmd-5"); TextCommand parsed = @@ -480,7 +480,7 @@ void executeAppliesDurableAfkAndDeliversOutput() { @Test void executeAppliesDurableBlockAndStoresReplay() { SessionContext context = - new SessionContext(42L, 22L, 7L, "demo@example.com", 91L, "Demo", 5L, "R-1", "jwt-token"); + new SessionContext(42L, 22L, "7", "demo@example.com", 91L, "Demo", 5L, "R-1", "jwt-token"); GameplayCommand command = gameplayCommand("GUARD", "GUARD"); TickEffect effect = tickEffect("tfx-6", "cmd-6"); TextCommand parsed = @@ -509,7 +509,7 @@ void executeAppliesDurableBlockAndStoresReplay() { @Test void executeReplaysStoredCommunicationWithoutInvokingHandler() { SessionContext context = - new SessionContext(42L, 22L, 7L, "demo@example.com", 91L, "Demo", 5L, "R-1", "jwt-token"); + new SessionContext(42L, 22L, "7", "demo@example.com", 91L, "Demo", 5L, "R-1", "jwt-token"); GameplayCommand command = gameplayCommand("SAY", "SAY Hello there"); TickEffect effect = tickEffect("tfx-6", "cmd-6"); TextCommand parsed = @@ -537,7 +537,7 @@ void executeReplaysStoredCommunicationWithoutInvokingHandler() { @Test void executeReplaysStoredRejectedAfkWithoutInvokingHandler() { SessionContext context = - new SessionContext(42L, 22L, 7L, "demo@example.com", 91L, "Demo", 5L, "R-1", "jwt-token"); + new SessionContext(42L, 22L, "7", "demo@example.com", 91L, "Demo", 5L, "R-1", "jwt-token"); GameplayCommand command = gameplayCommand("AFK", "AFK"); TickEffect effect = tickEffect("tfx-7", "cmd-7"); TextCommand parsed = @@ -572,7 +572,7 @@ void executeReplaysStoredRejectedAfkWithoutInvokingHandler() { @Test void executeReplaysStoredBlockWithoutInvokingHandler() { SessionContext context = - new SessionContext(42L, 22L, 7L, "demo@example.com", 91L, "Demo", 5L, "R-1", "jwt-token"); + new SessionContext(42L, 22L, "7", "demo@example.com", 91L, "Demo", 5L, "R-1", "jwt-token"); GameplayCommand command = gameplayCommand("BLOCK", "BLOCK"); TickEffect effect = tickEffect("tfx-7b", "cmd-7b"); TextCommand parsed = new TextCommand(TextCommandType.BLOCK, java.util.List.of(), "BLOCK"); @@ -600,7 +600,7 @@ void executeReplaysStoredBlockWithoutInvokingHandler() { @Test void executeAppliesPersistedAuthoredActionSnapshotWithoutLiveMetadata() { SessionContext context = - new SessionContext(42L, 22L, 7L, "demo@example.com", 91L, "Demo", 5L, "R-1", "jwt-token"); + new SessionContext(42L, 22L, "7", "demo@example.com", 91L, "Demo", 5L, "R-1", "jwt-token"); GameplayCommand command = gameplayCommand("wave", "wave captain"); command.setAdmittedReleaseBundleId(300L); command.setAdmittedVersionId(41L); @@ -642,7 +642,7 @@ void executeAppliesPersistedAuthoredActionSnapshotWithoutLiveMetadata() { @Test void executeReplaysPersistedAuthoredActionWithoutApplyingItsSnapshotAgain() { SessionContext context = - new SessionContext(42L, 22L, 7L, "demo@example.com", 91L, "Demo", 5L, "R-1", "jwt-token"); + new SessionContext(42L, 22L, "7", "demo@example.com", 91L, "Demo", 5L, "R-1", "jwt-token"); GameplayCommand command = gameplayCommand("wave", "wave captain"); command.setAdmittedReleaseBundleId(300L); command.setAdmittedVersionId(41L); @@ -695,7 +695,7 @@ void executeReplaysAuthoredSnapshotAgainstItsOriginalSessionAfterSessionResumpti playerOutputDeliveryService, scriptEventPublisher); SessionContext resumedContext = - new SessionContext(43L, 22L, 7L, "demo@example.com", 91L, "Demo", 5L, "R-1", "jwt-token"); + new SessionContext(43L, 22L, "7", "demo@example.com", 91L, "Demo", 5L, "R-1", "jwt-token"); GameplayCommand command = gameplayCommand("wave", "wave captain"); command.setAdmittedReleaseBundleId(300L); command.setAdmittedVersionId(41L); @@ -735,7 +735,7 @@ void executeReplaysAuthoredSnapshotAgainstItsOriginalSessionAfterSessionResumpti @Test void executeRejectsAuthoredActionWhenTheSessionSwitchedGameplayIdentity() { SessionContext switchedContext = - new SessionContext(42L, 22L, 7L, "demo@example.com", 92L, "Other", 5L, "R-1", "jwt-token"); + new SessionContext(42L, 22L, "7", "demo@example.com", 92L, "Other", 5L, "R-1", "jwt-token"); GameplayCommand command = gameplayCommand("wave", "wave captain"); command.setAdmittedReleaseBundleId(300L); command.setAdmittedVersionId(41L); @@ -757,7 +757,7 @@ void executeRejectsAuthoredActionWhenTheSessionSwitchedGameplayIdentity() { @Test void executeRejectsMalformedAuthoredSnapshotBeforeReplayOrScriptPublication() { SessionContext context = - new SessionContext(42L, 22L, 7L, "demo@example.com", 91L, "Demo", 5L, "R-1", "jwt-token"); + new SessionContext(42L, 22L, "7", "demo@example.com", 91L, "Demo", 5L, "R-1", "jwt-token"); GameplayCommand command = gameplayCommand("wave", "wave captain"); command.setAdmittedReleaseBundleId(300L); command.setAdmittedVersionId(41L); @@ -781,7 +781,7 @@ void executeRejectsMalformedAuthoredSnapshotBeforeReplayOrScriptPublication() { @Test void executeRejectsAuthoredSnapshotWithAnInvalidModifierBeforeReplay() { SessionContext context = - new SessionContext(42L, 22L, 7L, "demo@example.com", 91L, "Demo", 5L, "R-1", "jwt-token"); + new SessionContext(42L, 22L, "7", "demo@example.com", 91L, "Demo", 5L, "R-1", "jwt-token"); GameplayCommand command = gameplayCommand("wave", "wave captain"); command.setAdmittedReleaseBundleId(300L); command.setAdmittedVersionId(41L); @@ -823,7 +823,7 @@ void executeRejectsAuthoredSnapshotWithAnInvalidModifierBeforeReplay() { @Test void executeRejectsAuthoredSnapshotAboveTheSharedDurationLimitBeforeReplay() { SessionContext context = - new SessionContext(42L, 22L, 7L, "demo@example.com", 91L, "Demo", 5L, "R-1", "jwt-token"); + new SessionContext(42L, 22L, "7", "demo@example.com", 91L, "Demo", 5L, "R-1", "jwt-token"); GameplayCommand command = gameplayCommand("wave", "wave captain"); command.setAdmittedReleaseBundleId(300L); command.setAdmittedVersionId(41L); diff --git a/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/service/impl/DefaultGameplayPresenceLifecycleServiceTest.java b/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/service/impl/DefaultGameplayPresenceLifecycleServiceTest.java index 5ec7026256..e6567e6906 100644 --- a/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/service/impl/DefaultGameplayPresenceLifecycleServiceTest.java +++ b/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/service/impl/DefaultGameplayPresenceLifecycleServiceTest.java @@ -34,7 +34,7 @@ class DefaultGameplayPresenceLifecycleServiceTest { void registerConnectedUpdatesLiveAndRecentPresence() { SessionContext context = new SessionContext( - 41L, 22L, 123L, "demo@example.com", 7001L, "Emberline", 1L, "R-1021", ""); + 41L, 22L, "123", "demo@example.com", 7001L, "Emberline", 1L, "R-1021", ""); service.registerConnected(context); @@ -54,7 +54,7 @@ void recordActivityUpdatesLiveAndRecentPresence() { void clearGameplayBindingPublishesExitAndRemovesLivePresenceWithoutDisconnecting() { SessionContext context = new SessionContext( - 41L, 22L, 123L, "demo@example.com", 7001L, "Emberline", 1L, "R-1021", ""); + 41L, 22L, "123", "demo@example.com", 7001L, "Emberline", 1L, "R-1021", ""); service.clearGameplayBinding(context, "STALE_ADMISSION_POINTER"); @@ -71,7 +71,7 @@ void clearGameplayBindingPublishesExitAndRemovesLivePresenceWithoutDisconnecting @Test void clearGameplayBindingSkipsExitWithoutGameplayRegionBinding() { SessionContext context = - new SessionContext(41L, 22L, 123L, "demo@example.com", 0L, null, 0L, null, ""); + new SessionContext(41L, 22L, "123", "demo@example.com", 0L, null, 0L, null, ""); service.clearGameplayBinding(context, "LOGIN_FAILED"); @@ -86,7 +86,7 @@ void clearGameplayBindingSkipsExitWithoutGameplayRegionBinding() { void recordDisconnectedWritesRecentPresenceBeforeRemovingLivePresence() { whenGameplayContextPresent( new SessionContext( - 41L, 22L, 123L, "demo@example.com", 7001L, "Emberline", 1L, "R-1021", "")); + 41L, 22L, "123", "demo@example.com", 7001L, "Emberline", 1L, "R-1021", "")); service.recordDisconnected(41L, AccountRecentPresenceDisposition.TRANSPORT_LOSS); @@ -109,7 +109,7 @@ void recordDisconnectedWritesRecentPresenceBeforeRemovingLivePresence() { void recordDisconnectedPreservesCanonicalLogoutEventId() { SessionContext context = new SessionContext( - 41L, 22L, 123L, "demo@example.com", 7001L, "Emberline", 1L, "R-1021", ""); + 41L, 22L, "123", "demo@example.com", 7001L, "Emberline", 1L, "R-1021", ""); whenGameplayContextPresent(context); service.recordDisconnected(41L, AccountRecentPresenceDisposition.LOGOUT); @@ -120,7 +120,7 @@ void recordDisconnectedPreservesCanonicalLogoutEventId() { @Test void recordDisconnectedSkipsLifecycleEventWithoutGameplayRegionBinding() { whenGameplayContextPresent( - new SessionContext(41L, 22L, 0L, "demo@example.com", 7001L, "Emberline", 0L, "", "")); + new SessionContext(41L, 22L, null, "demo@example.com", 7001L, "Emberline", 0L, "", "")); service.recordDisconnected(41L, AccountRecentPresenceDisposition.TRANSPORT_LOSS); @@ -141,7 +141,7 @@ private void whenGameplayContextPresent(SessionContext context) { @Test void recordDisconnectedSkipsExitWhenNormalizationClearsStaleGameplayBinding() { SessionContext cleared = - new SessionContext(41L, 22L, 123L, "demo@example.com", 0L, null, 0L, null, ""); + new SessionContext(41L, 22L, "123", "demo@example.com", 0L, null, 0L, null, ""); Mockito.when(sessionRoutingNormalizationService.resolveProjectedSessionContext("41")) .thenReturn(Optional.of(cleared)); diff --git a/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/service/impl/GameAuthoredHelpReaderImplTest.java b/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/service/impl/GameAuthoredHelpReaderImplTest.java index 3c5b060849..e1ac92cd34 100644 --- a/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/service/impl/GameAuthoredHelpReaderImplTest.java +++ b/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/service/impl/GameAuthoredHelpReaderImplTest.java @@ -56,6 +56,6 @@ private void whenInstance(long gameInstanceId, GameInstance instance) { private SessionContext gameplayContext() { return new SessionContext( - 41L, 22L, 123L, "demo@example.com", 7001L, "Emberline", 7L, "R-1", "jwt"); + 41L, 22L, "123", "demo@example.com", 7001L, "Emberline", 7L, "R-1", "jwt"); } } 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 1db89fc77a..1987b15f4f 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 @@ -248,11 +248,11 @@ void queryAccountPresenceReturnsMappedSnapshots() { IpConnectionLimiter ipLimiter = Mockito.mock(IpConnectionLimiter.class); SimpleMeterRegistry meterRegistry = new SimpleMeterRegistry(); SessionContext.setContext("42", List.of(), Map.of()); - Mockito.when(accountPresenceQueryService.queryAccountPresence(1L, 42L, List.of(7L))) + Mockito.when(accountPresenceQueryService.queryAccountPresence(1L, "42", List.of("7"))) .thenReturn( List.of( new AccountPresenceSnapshot( - 7L, + "7", true, 9L, "ISOLATED", diff --git a/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/service/impl/GameplayPresenceRoleClassifierTest.java b/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/service/impl/GameplayPresenceRoleClassifierTest.java index dcc166d305..e270124423 100644 --- a/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/service/impl/GameplayPresenceRoleClassifierTest.java +++ b/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/service/impl/GameplayPresenceRoleClassifierTest.java @@ -22,7 +22,7 @@ void classifyRoleReturnsPlayerWhenJwtParserThrowsIllegalArgumentException() { GameplayPresenceRole role = GameplayPresenceRoleClassifier.classifyRole( new SessionContext( - 1L, 22L, 102L, "player@example.com", 202L, "Ben", 7L, "R-1", "boom-token"), + 1L, 22L, "102", "player@example.com", 202L, "Ben", 7L, "R-1", "boom-token"), jwtUtil, logger); @@ -43,7 +43,7 @@ void classifyRoleReturnsModeratorForScopedModeratorRole() { GameplayPresenceRole role = GameplayPresenceRoleClassifier.classifyRole( - new SessionContext(1L, 22L, 202L, "player@example.com", 202L, "Ben", 7L, "R-1", jwt), + new SessionContext(1L, 22L, "202", "player@example.com", 202L, "Ben", 7L, "R-1", jwt), JWT_UTIL, logger); @@ -59,7 +59,7 @@ void classifyRoleReturnsGodForGlobalGodRole() { GameplayPresenceRole role = GameplayPresenceRoleClassifier.classifyRole( - new SessionContext(1L, 22L, 202L, "player@example.com", 202L, "Ben", 7L, "R-1", jwt), + new SessionContext(1L, 22L, "202", "player@example.com", 202L, "Ben", 7L, "R-1", jwt), JWT_UTIL, logger); @@ -80,7 +80,7 @@ void classifyRoleReturnsAdminForTenantAdminRole() { GameplayPresenceRole role = GameplayPresenceRoleClassifier.classifyRole( - new SessionContext(1L, 22L, 202L, "player@example.com", 202L, "Ben", 7L, "R-1", jwt), + new SessionContext(1L, 22L, "202", "player@example.com", 202L, "Ben", 7L, "R-1", jwt), JWT_UTIL, logger); @@ -103,7 +103,7 @@ void classifyRoleUsesTheHighestAvailableGameplayRole() { GameplayPresenceRole role = GameplayPresenceRoleClassifier.classifyRole( - new SessionContext(1L, 22L, 202L, "player@example.com", 202L, "Ben", 7L, "R-1", jwt), + new SessionContext(1L, 22L, "202", "player@example.com", 202L, "Ben", 7L, "R-1", jwt), JWT_UTIL, logger); @@ -118,7 +118,7 @@ void classifyRoleReturnsPlayerWhenScopedRolesClaimIsMalformed() { GameplayPresenceRole role = GameplayPresenceRoleClassifier.classifyRole( - new SessionContext(1L, 22L, 202L, "player@example.com", 202L, "Ben", 7L, "R-1", jwt), + new SessionContext(1L, 22L, "202", "player@example.com", 202L, "Ben", 7L, "R-1", jwt), JWT_UTIL, logger); diff --git a/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/service/impl/RedisAccountRecentPresenceServiceTest.java b/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/service/impl/RedisAccountRecentPresenceServiceTest.java index 750152a7c9..b8ec61c099 100644 --- a/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/service/impl/RedisAccountRecentPresenceServiceTest.java +++ b/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/service/impl/RedisAccountRecentPresenceServiceTest.java @@ -3,11 +3,18 @@ import static org.junit.jupiter.api.Assertions.assertEquals; import static org.junit.jupiter.api.Assertions.assertInstanceOf; import static org.junit.jupiter.api.Assertions.assertNull; +import static org.junit.jupiter.api.Assertions.assertThrows; +import static org.mockito.ArgumentMatchers.any; +import static org.mockito.ArgumentMatchers.anyString; import static org.mockito.ArgumentMatchers.eq; +import static org.mockito.Mockito.never; +import static org.mockito.Mockito.times; import static org.mockito.Mockito.verify; import static org.mockito.Mockito.when; import java.time.Duration; +import java.util.List; +import java.util.Map; import java.util.Optional; import net.firedevops.firemud.gamesession.config.PresenceProperties; import net.firedevops.firemud.gamesession.service.AccountRecentPresenceDisposition; @@ -20,8 +27,11 @@ import org.junit.jupiter.api.Test; import org.mockito.ArgumentCaptor; import org.mockito.Mockito; +import org.springframework.data.redis.core.RedisOperations; import org.springframework.data.redis.core.RedisTemplate; +import org.springframework.data.redis.core.SessionCallback; import org.springframework.data.redis.core.ValueOperations; +import org.springframework.data.redis.serializer.SerializationException; class RedisAccountRecentPresenceServiceTest { @@ -32,6 +42,7 @@ void recordDisconnectPersistsRoutingBundleFromLivePresence() { @SuppressWarnings("unchecked") ValueOperations valueOperations = Mockito.mock(ValueOperations.class); when(redisTemplate.opsForValue()).thenReturn(valueOperations); + stubTransactionExecution(redisTemplate); SessionRoutingNormalizationService sessionRoutingNormalizationService = Mockito.mock(SessionRoutingNormalizationService.class); @@ -43,7 +54,7 @@ void recordDisconnectPersistsRoutingBundleFromLivePresence() { new SessionContext( 41L, 22L, - 123L, + "123", "demo@example.com", 7001L, "Emberline", @@ -65,7 +76,7 @@ void recordDisconnectPersistsRoutingBundleFromLivePresence() { "demo", "production", 17L, - 123L, + "123", 7001L, "Emberline", GameplayPresenceRole.PLAYER, @@ -91,11 +102,14 @@ void recordDisconnectPersistsRoutingBundleFromLivePresence() { ArgumentCaptor stateCaptor = ArgumentCaptor.forClass(Object.class); verify(valueOperations) .set(eq("accountrecentpresence:22:123"), stateCaptor.capture(), eq(Duration.ofMinutes(5))); + verify(redisTemplate).watch("accountrecentpresence:22:123"); + verify(redisTemplate).multi(); + verify(redisTemplate).exec(); AccountRecentPresenceState state = assertInstanceOf(AccountRecentPresenceState.class, stateCaptor.getValue()); assertEquals(22L, state.tenantId()); - assertEquals(123L, state.accountId()); + assertEquals("123", state.accountId()); assertEquals(101L, state.gameInstanceId()); assertEquals("demo", state.worldSlug()); assertEquals("production", state.realmSlug()); @@ -111,6 +125,7 @@ void recordDisconnectIgnoresLivePresenceWhenNormalizationClearsGameplayBinding() @SuppressWarnings("unchecked") ValueOperations valueOperations = Mockito.mock(ValueOperations.class); when(redisTemplate.opsForValue()).thenReturn(valueOperations); + stubTransactionExecution(redisTemplate); SessionRoutingNormalizationService sessionRoutingNormalizationService = Mockito.mock(SessionRoutingNormalizationService.class); @@ -122,7 +137,7 @@ void recordDisconnectIgnoresLivePresenceWhenNormalizationClearsGameplayBinding() new SessionContext( 41L, 22L, - 123L, + "123", "demo@example.com", 0L, null, @@ -144,7 +159,7 @@ void recordDisconnectIgnoresLivePresenceWhenNormalizationClearsGameplayBinding() "demo", "production", 17L, - 123L, + "123", 7001L, "Emberline", GameplayPresenceRole.PLAYER, @@ -187,6 +202,7 @@ void recordDisconnectIgnoresLivePresenceWhenContextOnlyRetainsPartialGameplayShe @SuppressWarnings("unchecked") ValueOperations valueOperations = Mockito.mock(ValueOperations.class); when(redisTemplate.opsForValue()).thenReturn(valueOperations); + stubTransactionExecution(redisTemplate); SessionRoutingNormalizationService sessionRoutingNormalizationService = Mockito.mock(SessionRoutingNormalizationService.class); @@ -198,7 +214,7 @@ void recordDisconnectIgnoresLivePresenceWhenContextOnlyRetainsPartialGameplayShe new SessionContext( 41L, 22L, - 123L, + "123", "demo@example.com", 0L, null, @@ -220,7 +236,7 @@ void recordDisconnectIgnoresLivePresenceWhenContextOnlyRetainsPartialGameplayShe "demo", "production", 17L, - 123L, + "123", 7001L, "Emberline", GameplayPresenceRole.PLAYER, @@ -263,6 +279,7 @@ void recordDisconnectUsesContextRoutingWhenLivePresenceRoutingFieldsArePartial() @SuppressWarnings("unchecked") ValueOperations valueOperations = Mockito.mock(ValueOperations.class); when(redisTemplate.opsForValue()).thenReturn(valueOperations); + stubTransactionExecution(redisTemplate); SessionRoutingNormalizationService sessionRoutingNormalizationService = Mockito.mock(SessionRoutingNormalizationService.class); @@ -274,7 +291,7 @@ void recordDisconnectUsesContextRoutingWhenLivePresenceRoutingFieldsArePartial() new SessionContext( 41L, 22L, - 123L, + "123", "demo@example.com", 7001L, "Emberline", @@ -296,7 +313,7 @@ void recordDisconnectUsesContextRoutingWhenLivePresenceRoutingFieldsArePartial() "demo", null, 17L, - 123L, + "123", 7001L, "Emberline", GameplayPresenceRole.PLAYER, @@ -332,4 +349,250 @@ void recordDisconnectUsesContextRoutingWhenLivePresenceRoutingFieldsArePartial() assertEquals("fallback-realm", state.realmSlug()); assertEquals(3L, state.pointerVersion()); } + + @Test + void unreadableRecentPresenceFailsClosedWithoutOverwritingRetainedEvidence() { + @SuppressWarnings("unchecked") + RedisTemplate redisTemplate = Mockito.mock(RedisTemplate.class); + @SuppressWarnings("unchecked") + ValueOperations valueOperations = Mockito.mock(ValueOperations.class); + when(redisTemplate.opsForValue()).thenReturn(valueOperations); + stubTransactionExecution(redisTemplate); + when(valueOperations.get("accountrecentpresence:22:123")) + .thenThrow(new SerializationException("old AccountRecentPresenceState record shape")); + + GameplayPresenceService gameplayPresenceService = Mockito.mock(GameplayPresenceService.class); + when(gameplayPresenceService.findConnectedBySessionId(41L)).thenReturn(Optional.empty()); + PresenceProperties presenceProperties = new PresenceProperties(); + presenceProperties.setRecentPresenceTtlMs(Duration.ofMinutes(5).toMillis()); + RedisAccountRecentPresenceService service = + new RedisAccountRecentPresenceService( + redisTemplate, + Mockito.mock(SessionRoutingNormalizationService.class), + gameplayPresenceService, + presenceProperties, + () -> 1_700_000_000_000L); + SessionContext context = + new SessionContext(41L, 22L, "123", "demo@example.com", 0L, null, 0L, null, "jwt"); + + assertEquals(Map.of(), service.findByAccountIds(22L, List.of("123"))); + service.recordConnected(context); + + verify(valueOperations, never()).set(anyString(), any(), any(Duration.class)); + verify(redisTemplate, never()).multi(); + verify(redisTemplate, never()).exec(); + verify(redisTemplate, never()).delete(anyString()); + } + + @Test + void recordConnectedRetriesAfterWatchedValueChanges() { + @SuppressWarnings("unchecked") + RedisTemplate redisTemplate = Mockito.mock(RedisTemplate.class); + @SuppressWarnings("unchecked") + ValueOperations valueOperations = Mockito.mock(ValueOperations.class); + when(redisTemplate.opsForValue()).thenReturn(valueOperations); + stubTransactionExecution(redisTemplate); + AccountRecentPresenceState retained = + new AccountRecentPresenceState( + 22L, "123", 1_699_999_999_000L, AccountRecentPresenceDisposition.TRANSPORT_LOSS); + AccountRecentPresenceState concurrentReplacement = + new AccountRecentPresenceState( + 22L, "123", 1_699_999_999_500L, AccountRecentPresenceDisposition.LOGOUT); + when(valueOperations.get("accountrecentpresence:22:123")) + .thenReturn(retained, concurrentReplacement); + when(redisTemplate.exec()).thenReturn(null, List.of("OK")); + + GameplayPresenceService gameplayPresenceService = Mockito.mock(GameplayPresenceService.class); + when(gameplayPresenceService.findConnectedBySessionId(41L)).thenReturn(Optional.empty()); + RedisAccountRecentPresenceService service = newService(redisTemplate, gameplayPresenceService); + + service.recordConnected(testContext()); + + verify(redisTemplate, times(2)).watch("accountrecentpresence:22:123"); + verify(redisTemplate, times(2)).multi(); + verify(redisTemplate, times(2)).exec(); + verify(valueOperations, times(2)).get("accountrecentpresence:22:123"); + verify(valueOperations, times(2)) + .set(eq("accountrecentpresence:22:123"), any(), eq(Duration.ofMinutes(5))); + } + + @Test + void recordConnectedStopsAfterEightWatchedConflictsWithoutCommittingTheProjection() { + @SuppressWarnings("unchecked") + RedisTemplate redisTemplate = Mockito.mock(RedisTemplate.class); + @SuppressWarnings("unchecked") + ValueOperations valueOperations = Mockito.mock(ValueOperations.class); + when(redisTemplate.opsForValue()).thenReturn(valueOperations); + stubTransactionExecution(redisTemplate); + AccountRecentPresenceState retained = + new AccountRecentPresenceState( + 22L, "123", 1_699_999_999_000L, AccountRecentPresenceDisposition.TRANSPORT_LOSS); + when(valueOperations.get("accountrecentpresence:22:123")).thenReturn(retained); + when(redisTemplate.exec()).thenReturn(null); + + GameplayPresenceService gameplayPresenceService = Mockito.mock(GameplayPresenceService.class); + when(gameplayPresenceService.findConnectedBySessionId(41L)).thenReturn(Optional.empty()); + RedisAccountRecentPresenceService service = newService(redisTemplate, gameplayPresenceService); + + service.recordConnected(testContext()); + + verify(redisTemplate, times(8)).watch("accountrecentpresence:22:123"); + verify(redisTemplate, times(8)).multi(); + verify(redisTemplate, times(8)).exec(); + verify(valueOperations, times(8)).get("accountrecentpresence:22:123"); + // Each null EXEC represents a WATCH conflict, so none of the queued replacement writes + // committed. + verify(valueOperations, times(8)) + .set(eq("accountrecentpresence:22:123"), any(), eq(Duration.ofMinutes(5))); + verify(redisTemplate, never()).delete(anyString()); + } + + @Test + void recordActivityStopsAfterEightWatchedConflictsWithoutCommittingTheProjection() { + @SuppressWarnings("unchecked") + RedisTemplate redisTemplate = Mockito.mock(RedisTemplate.class); + @SuppressWarnings("unchecked") + ValueOperations valueOperations = Mockito.mock(ValueOperations.class); + when(redisTemplate.opsForValue()).thenReturn(valueOperations); + stubTransactionExecution(redisTemplate); + AccountRecentPresenceState retained = + new AccountRecentPresenceState( + 22L, "123", 1_699_999_999_000L, AccountRecentPresenceDisposition.TRANSPORT_LOSS); + when(valueOperations.get("accountrecentpresence:22:123")).thenReturn(retained); + when(redisTemplate.exec()).thenReturn(null); + + SessionRoutingNormalizationService sessionRoutingNormalizationService = + Mockito.mock(SessionRoutingNormalizationService.class); + when(sessionRoutingNormalizationService.resolveProjectedSessionContext("41")) + .thenReturn(Optional.of(testContext())); + GameplayPresenceService gameplayPresenceService = Mockito.mock(GameplayPresenceService.class); + when(gameplayPresenceService.findConnectedBySessionId(41L)).thenReturn(Optional.empty()); + RedisAccountRecentPresenceService service = + newService(redisTemplate, gameplayPresenceService, sessionRoutingNormalizationService); + + service.recordActivity(41L); + + verify(redisTemplate, times(8)).watch("accountrecentpresence:22:123"); + verify(redisTemplate, times(8)).multi(); + verify(redisTemplate, times(8)).exec(); + verify(valueOperations, times(8)).get("accountrecentpresence:22:123"); + // Each null EXEC represents a WATCH conflict, so none of the queued replacement writes + // committed. + verify(valueOperations, times(8)) + .set(eq("accountrecentpresence:22:123"), any(), eq(Duration.ofMinutes(5))); + verify(redisTemplate, never()).delete(anyString()); + } + + @Test + void recordConnectedDoesNotRetryWriteWhenConflictRevealsUnreadableReplacement() { + @SuppressWarnings("unchecked") + RedisTemplate redisTemplate = Mockito.mock(RedisTemplate.class); + @SuppressWarnings("unchecked") + ValueOperations valueOperations = Mockito.mock(ValueOperations.class); + when(redisTemplate.opsForValue()).thenReturn(valueOperations); + stubTransactionExecution(redisTemplate); + AccountRecentPresenceState retained = + new AccountRecentPresenceState( + 22L, "123", 1_699_999_999_000L, AccountRecentPresenceDisposition.TRANSPORT_LOSS); + when(valueOperations.get("accountrecentpresence:22:123")) + .thenReturn(retained) + .thenThrow(new SerializationException("concurrent replacement has old record shape")); + when(redisTemplate.exec()).thenReturn(null); + + GameplayPresenceService gameplayPresenceService = Mockito.mock(GameplayPresenceService.class); + when(gameplayPresenceService.findConnectedBySessionId(41L)).thenReturn(Optional.empty()); + RedisAccountRecentPresenceService service = newService(redisTemplate, gameplayPresenceService); + + service.recordConnected(testContext()); + + verify(redisTemplate, times(2)).watch("accountrecentpresence:22:123"); + verify(redisTemplate).multi(); + verify(redisTemplate).exec(); + verify(redisTemplate).unwatch(); + // The first queued SET was rejected by EXEC; the unreadable replacement prevents a retry SET. + verify(valueOperations) + .set(eq("accountrecentpresence:22:123"), any(), eq(Duration.ofMinutes(5))); + } + + @Test + void recordConnectedPreservesTypeMismatchedRetainedValue() { + @SuppressWarnings("unchecked") + RedisTemplate redisTemplate = Mockito.mock(RedisTemplate.class); + @SuppressWarnings("unchecked") + ValueOperations valueOperations = Mockito.mock(ValueOperations.class); + when(redisTemplate.opsForValue()).thenReturn(valueOperations); + stubTransactionExecution(redisTemplate); + when(valueOperations.get("accountrecentpresence:22:123")).thenReturn("legacy value"); + + GameplayPresenceService gameplayPresenceService = Mockito.mock(GameplayPresenceService.class); + when(gameplayPresenceService.findConnectedBySessionId(41L)).thenReturn(Optional.empty()); + RedisAccountRecentPresenceService service = newService(redisTemplate, gameplayPresenceService); + + service.recordConnected(testContext()); + + verify(redisTemplate).watch("accountrecentpresence:22:123"); + verify(redisTemplate).unwatch(); + verify(redisTemplate, never()).multi(); + verify(redisTemplate, never()).exec(); + verify(valueOperations, never()).set(anyString(), any(), any(Duration.class)); + verify(redisTemplate, never()).delete(anyString()); + } + + @Test + void recordConnectedPropagatesRedisReadOutage() { + @SuppressWarnings("unchecked") + RedisTemplate redisTemplate = Mockito.mock(RedisTemplate.class); + @SuppressWarnings("unchecked") + ValueOperations valueOperations = Mockito.mock(ValueOperations.class); + when(redisTemplate.opsForValue()).thenReturn(valueOperations); + stubTransactionExecution(redisTemplate); + when(valueOperations.get("accountrecentpresence:22:123")) + .thenThrow(new IllegalStateException("Redis unavailable")); + + GameplayPresenceService gameplayPresenceService = Mockito.mock(GameplayPresenceService.class); + when(gameplayPresenceService.findConnectedBySessionId(41L)).thenReturn(Optional.empty()); + RedisAccountRecentPresenceService service = newService(redisTemplate, gameplayPresenceService); + + assertThrows(IllegalStateException.class, () -> service.recordConnected(testContext())); + verify(redisTemplate, never()).multi(); + verify(valueOperations, never()).set(anyString(), any(), any(Duration.class)); + } + + private static RedisAccountRecentPresenceService newService( + RedisTemplate redisTemplate, + GameplayPresenceService gameplayPresenceService) { + return newService( + redisTemplate, + gameplayPresenceService, + Mockito.mock(SessionRoutingNormalizationService.class)); + } + + private static RedisAccountRecentPresenceService newService( + RedisTemplate redisTemplate, + GameplayPresenceService gameplayPresenceService, + SessionRoutingNormalizationService sessionRoutingNormalizationService) { + PresenceProperties presenceProperties = new PresenceProperties(); + presenceProperties.setRecentPresenceTtlMs(Duration.ofMinutes(5).toMillis()); + return new RedisAccountRecentPresenceService( + redisTemplate, + sessionRoutingNormalizationService, + gameplayPresenceService, + presenceProperties, + () -> 1_700_000_000_000L); + } + + private static SessionContext testContext() { + return new SessionContext(41L, 22L, "123", "demo@example.com", 0L, null, 0L, null, "jwt"); + } + + @SuppressWarnings("unchecked") + private static void stubTransactionExecution(RedisTemplate redisTemplate) { + when(redisTemplate.execute(Mockito.any(SessionCallback.class))) + .thenAnswer( + invocation -> { + SessionCallback callback = invocation.getArgument(0); + return callback.execute((RedisOperations) redisTemplate); + }); + when(redisTemplate.exec()).thenReturn(List.of("OK")); + } } diff --git a/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/service/impl/RedisFirstPartyConnectContextRegistryTest.java b/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/service/impl/RedisFirstPartyConnectContextRegistryTest.java index 3ceca2deb6..8656e71570 100644 --- a/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/service/impl/RedisFirstPartyConnectContextRegistryTest.java +++ b/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/service/impl/RedisFirstPartyConnectContextRegistryTest.java @@ -1,10 +1,12 @@ 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.any; import static org.mockito.ArgumentMatchers.anyString; import static org.mockito.Mockito.doAnswer; import static org.mockito.Mockito.mock; +import static org.mockito.Mockito.never; import static org.mockito.Mockito.verify; import static org.mockito.Mockito.when; @@ -19,6 +21,7 @@ import org.mockito.ArgumentCaptor; import org.springframework.data.redis.core.RedisTemplate; import org.springframework.data.redis.core.ValueOperations; +import org.springframework.data.redis.serializer.SerializationException; @SuppressWarnings("unchecked") class RedisFirstPartyConnectContextRegistryTest { @@ -56,7 +59,7 @@ void setUp() { void registerStoresContextWithShortTtl() { FirstPartyConnectContext context = new FirstPartyConnectContext( - 77L, 22L, "demo", "production", 41L, 17L, "scope-1", "jti-1", "req-1", "gateway-1"); + "77", 22L, "demo", "production", 41L, 17L, "scope-1", "jti-1", "req-1", "gateway-1"); registry.register(91L, context); @@ -73,7 +76,7 @@ void registerStoresContextWithShortTtl() { void unregisterRemovesStoredContext() { FirstPartyConnectContext context = new FirstPartyConnectContext( - 77L, 22L, "demo", "production", 41L, 17L, "scope-1", "jti-1", "req-1", "gateway-1"); + "77", 22L, "demo", "production", 41L, 17L, "scope-1", "jti-1", "req-1", "gateway-1"); registry.register(91L, context); registry.unregister(91L); @@ -81,4 +84,64 @@ void unregisterRemovesStoredContext() { assertEquals(Optional.empty(), registry.find(91L)); verify(redisTemplate).delete("sessionctx:first-party:91:connect-context"); } + + @Test + void unreadableRetainedContextFailsClosedWithoutDeletingOrOverwritingEvidence() { + String key = "sessionctx:first-party:91:connect-context"; + when(valueOperations.get(key)).thenThrow(new SerializationException("old record shape")); + + assertEquals(Optional.empty(), registry.find(91L)); + + assertThrows( + IllegalStateException.class, + () -> + registry.register( + 91L, + new FirstPartyConnectContext( + "77", + 22L, + "demo", + "production", + 41L, + 17L, + "scope-1", + "jti-2", + "req-2", + "gateway-1"))); + registry.unregister(91L); + + verify(redisTemplate, never()).delete(key); + verify(valueOperations, never()).set(anyString(), any(), any(Duration.class)); + } + + @Test + void wrongRetainedValueFailsClosedWithoutOverwritingEvidence() { + String key = "sessionctx:first-party:91:connect-context"; + Object retainedEvidence = "serialized record from an incompatible shape"; + store.put(key, retainedEvidence); + + assertEquals(Optional.empty(), registry.find(91L)); + + assertThrows( + IllegalStateException.class, + () -> + registry.register( + 91L, + new FirstPartyConnectContext( + "77", + 22L, + "demo", + "production", + 41L, + 17L, + "scope-1", + "jti-2", + "req-2", + "gateway-1"))); + registry.unregister(91L); + + assertEquals(retainedEvidence, store.get(key)); + verify(redisTemplate, never()).delete(key); + verify(valueOperations, never()).set(anyString(), any(), any(Duration.class)); + } } diff --git a/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/service/impl/RedisGameplayPresenceServiceTest.java b/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/service/impl/RedisGameplayPresenceServiceTest.java index 2d391f44db..424f99490f 100644 --- a/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/service/impl/RedisGameplayPresenceServiceTest.java +++ b/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/service/impl/RedisGameplayPresenceServiceTest.java @@ -1,7 +1,11 @@ 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.any; +import static org.mockito.ArgumentMatchers.anyString; import static org.mockito.ArgumentMatchers.argThat; +import static org.mockito.Mockito.never; import static org.mockito.Mockito.verify; import static org.mockito.Mockito.when; @@ -19,6 +23,7 @@ import org.springframework.data.redis.core.RedisTemplate; import org.springframework.data.redis.core.SetOperations; import org.springframework.data.redis.core.ValueOperations; +import org.springframework.data.redis.serializer.SerializationException; @SuppressWarnings("unchecked") class RedisGameplayPresenceServiceTest { @@ -41,7 +46,7 @@ void setUp() { @Test void registerConnectedStoresPresenceAndIndexesByGameInstance() { SessionContext context = - new SessionContext(1L, 22L, 102L, "player@example.com", 202L, "Ben", 7L, "R-1", null); + new SessionContext(1L, 22L, "102", "player@example.com", 202L, "Ben", 7L, "R-1", null); service.registerConnected(context); @@ -65,7 +70,7 @@ void registerConnectedStoresPresenceAndIndexesByGameInstance() { void registerConnectedClassifiesInvalidJwtAsPlayer() { SessionContext context = new SessionContext( - 1L, 22L, 102L, "player@example.com", 202L, "Ben", 7L, "R-1", "not-a-jwt"); + 1L, 22L, "102", "player@example.com", 202L, "Ben", 7L, "R-1", "not-a-jwt"); service.registerConnected(context); @@ -94,7 +99,7 @@ void listConnectedByGameInstanceSortsGodsFirstAndPrunesMissingSessions() { "scopedRoles", Map.of())); SessionContext godContext = - new SessionContext(1L, 22L, 1L, "god@example.com", 101L, "Aster", 7L, "R-1", godJwt); + new SessionContext(1L, 22L, "1", "god@example.com", 101L, "Aster", 7L, "R-1", godJwt); service.registerConnected(godContext); when(setOperations.members("gameplaypresence:22:7:sessions")) @@ -107,7 +112,7 @@ void listConnectedByGameInstanceSortsGodsFirstAndPrunesMissingSessions() { 7L, "demo", "production", - 1L, + "1", 101L, "Aster", GameplayPresenceRole.GOD, @@ -137,7 +142,7 @@ void listConnectedByGameInstancePrunesMalformedSessionIndexEntry() { 7L, "demo", "production", - 1L, + "1", 101L, "Aster", GameplayPresenceRole.GOD, @@ -163,7 +168,7 @@ void removeBySessionIdRemovesValueAndSetMembership() { 7L, "demo", "production", - 102L, + "102", 202L, "Ben", GameplayPresenceRole.PLAYER, @@ -189,7 +194,7 @@ void findConnectedBySessionIdReadsPresenceRecordDirectly() { 7L, "demo", "production", - 2L, + "2", 102L, "Ben", GameplayPresenceRole.PLAYER, @@ -216,7 +221,7 @@ void recordCommandActivityRefreshesPresenceAndMeaningfulTimestampOnlyWhenRequest 7L, "demo", "production", - 102L, + "102", 202L, "Ben", GameplayPresenceRole.PLAYER, @@ -259,7 +264,7 @@ void setExplicitAfkRefreshesPresenceRecord() { 7L, "demo", "production", - 102L, + "102", 202L, "Ben", GameplayPresenceRole.PLAYER, @@ -301,7 +306,7 @@ void listConnectedByAccountIdsUsesAccountIndexAndReturnsAllMatches() { "demo", "production", 17L, - 102L, + "102", 202L, "Ben", GameplayPresenceRole.PLAYER, @@ -319,7 +324,7 @@ void listConnectedByAccountIdsUsesAccountIndexAndReturnsAllMatches() { "demo", "production", 17L, - 102L, + "102", 202L, "Ben", GameplayPresenceRole.PLAYER, @@ -328,12 +333,44 @@ void listConnectedByAccountIdsUsesAccountIndexAndReturnsAllMatches() { 110L, 120L)); - var result = service.listConnectedByAccountIds(22L, List.of(102L)); + var result = service.listConnectedByAccountIds(22L, List.of("102")); assertEquals(1, result.size()); - assertEquals(2, result.get(102L).size()); - assertEquals(4L, result.get(102L).get(0).sessionId()); - assertEquals(3L, result.get(102L).get(1).sessionId()); + assertEquals(2, result.get("102").size()); + assertEquals(4L, result.get("102").get(0).sessionId()); + assertEquals(3L, result.get("102").get(1).sessionId()); + } + + @Test + void listConnectedByAccountIdsUsesOpaqueAccountTextForIndexAndResultKey() { + String accountId = "account-uuid-opaque-v1"; + String accountIndexKey = "gameplaypresence:22:account:account-uuid-opaque-v1:sessions"; + String presenceKey = "gameplaypresence:session:9"; + var presence = + new net.firedevops.firemud.gamesession.service.GameplayPresence( + 9L, + 22L, + 7L, + "SHARED", + "demo", + "production", + 17L, + accountId, + 202L, + "Ben", + GameplayPresenceRole.PLAYER, + 80L, + null, + 100L, + null); + when(setOperations.members(accountIndexKey)).thenReturn(new LinkedHashSet<>(List.of("9"))); + when(valueOperations.get(presenceKey)).thenReturn(presence); + + var result = service.listConnectedByAccountIds(22L, List.of(accountId)); + + assertEquals(Map.of(accountId, List.of(presence)), result); + verify(setOperations).members(accountIndexKey); + verify(valueOperations).get(presenceKey); } @Test @@ -350,7 +387,7 @@ void listConnectedByAccountIdsPrunesMalformedSessionIndexEntry() { "demo", "production", 17L, - 102L, + "102", 202L, "Ben", GameplayPresenceRole.PLAYER, @@ -359,11 +396,90 @@ void listConnectedByAccountIdsPrunesMalformedSessionIndexEntry() { 110L, 120L)); - var result = service.listConnectedByAccountIds(22L, List.of(102L)); + var result = service.listConnectedByAccountIds(22L, List.of("102")); assertEquals(1, result.size()); - assertEquals(1, result.get(102L).size()); - assertEquals(4L, result.get(102L).get(0).sessionId()); + assertEquals(1, result.get("102").size()); + assertEquals(4L, result.get("102").get(0).sessionId()); verify(setOperations).remove("gameplaypresence:22:account:102:sessions", "bad-session"); } + + @Test + void unreadablePresenceIsNotReturnedOrPrunedFromIndexesDuringFailureCleanup() { + String presenceKey = "gameplaypresence:session:3"; + String accountIndexKey = "gameplaypresence:22:account:102:sessions"; + when(setOperations.members(accountIndexKey)).thenReturn(new LinkedHashSet<>(List.of("3"))); + when(valueOperations.get(presenceKey)) + .thenThrow(new SerializationException("old GameplayPresence record shape")); + + assertEquals(Map.of(), service.listConnectedByAccountIds(22L, List.of("102"))); + assertEquals(java.util.Optional.empty(), service.findConnectedBySessionId(3L)); + assertThrows(IllegalStateException.class, () -> service.removeBySessionId(3L)); + + verify(setOperations, Mockito.never()).remove(accountIndexKey, "3"); + verify(redisTemplate, Mockito.never()).delete(presenceKey); + verifyNoPresenceMutation(); + } + + @Test + void removeBySessionIdRejectsUnreadableAndWrongTypePresenceWithoutMutation() { + String presenceKey = "gameplaypresence:session:3"; + when(valueOperations.get(presenceKey)) + .thenThrow(new SerializationException("old GameplayPresence record shape")) + .thenReturn("incompatible retained presence"); + + assertThrows(IllegalStateException.class, () -> service.removeBySessionId(3L)); + assertThrows(IllegalStateException.class, () -> service.removeBySessionId(3L)); + + verifyNoPresenceMutation(); + } + + @Test + void setExplicitAfkRejectsUnreadableAndWrongTypePresenceWithoutMutation() { + String presenceKey = "gameplaypresence:session:3"; + when(valueOperations.get(presenceKey)) + .thenThrow(new SerializationException("old GameplayPresence record shape")) + .thenReturn("incompatible retained presence"); + + assertThrows(IllegalStateException.class, () -> service.setExplicitAfk(3L, true)); + assertThrows(IllegalStateException.class, () -> service.setExplicitAfk(3L, true)); + + verifyNoPresenceMutation(); + } + + @Test + void recordCommandActivityRejectsUnreadableAndWrongTypePresenceWithoutMutation() { + String presenceKey = "gameplaypresence:session:3"; + when(valueOperations.get(presenceKey)) + .thenThrow(new SerializationException("old GameplayPresence record shape")) + .thenReturn("incompatible retained presence"); + + assertThrows(IllegalStateException.class, () -> service.recordCommandActivity(3L, true)); + assertThrows(IllegalStateException.class, () -> service.recordCommandActivity(3L, true)); + + verifyNoPresenceMutation(); + } + + @Test + void registerConnectedRejectsUnreadableAndWrongTypePresenceBeforeWriting() { + String presenceKey = "gameplaypresence:session:3"; + when(valueOperations.get(presenceKey)) + .thenThrow(new SerializationException("old GameplayPresence record shape")) + .thenReturn("incompatible retained presence"); + SessionContext context = + new SessionContext(3L, 22L, "102", "player@example.com", 202L, "Ben", 7L, "R-1", null); + + assertThrows(IllegalStateException.class, () -> service.registerConnected(context)); + assertThrows(IllegalStateException.class, () -> service.registerConnected(context)); + + verifyNoPresenceMutation(); + } + + private void verifyNoPresenceMutation() { + verify(redisTemplate, never()).delete(anyString()); + verify(redisTemplate, never()).expire(anyString(), any(Duration.class)); + verify(valueOperations, never()).set(anyString(), any(), any(Duration.class)); + verify(setOperations, never()).add(anyString(), any()); + verify(setOperations, never()).remove(anyString(), any()); + } } diff --git a/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/service/impl/RedisMovementEffectIdempotencyServiceTest.java b/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/service/impl/RedisMovementEffectIdempotencyServiceTest.java index 8af487c378..f5757a4a1f 100644 --- a/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/service/impl/RedisMovementEffectIdempotencyServiceTest.java +++ b/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/service/impl/RedisMovementEffectIdempotencyServiceTest.java @@ -49,7 +49,7 @@ void applyPreservesRoutingBundleWhenUpdatingRoom() { new SessionContext( 41L, 22L, - 123L, + "123", "demo@example.com", 7001L, "demo", @@ -151,7 +151,7 @@ private SessionContext baselineContext() { return new SessionContext( 41L, 22L, - 123L, + "123", "demo@example.com", 7001L, "demo", @@ -170,7 +170,7 @@ private SessionContext withAccountId(SessionContext context, long accountId) { return new SessionContext( context.sessionId(), context.tenantId(), - accountId, + Long.toString(accountId), context.loginName(), context.characterId(), context.characterName(), diff --git a/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/service/impl/RedisSessionContextServiceTest.java b/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/service/impl/RedisSessionContextServiceTest.java index 4c8ae9403c..18517fb38e 100644 --- a/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/service/impl/RedisSessionContextServiceTest.java +++ b/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/service/impl/RedisSessionContextServiceTest.java @@ -1,10 +1,14 @@ 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.Mockito.never; +import static org.mockito.Mockito.times; import static org.mockito.Mockito.verify; import static org.mockito.Mockito.when; import java.time.Duration; +import java.util.Collection; import java.util.List; import java.util.Optional; import net.firedevops.firemud.gamesession.service.SessionContext; @@ -15,6 +19,7 @@ import org.springframework.data.redis.core.RedisTemplate; import org.springframework.data.redis.core.SessionCallback; import org.springframework.data.redis.core.ValueOperations; +import org.springframework.data.redis.serializer.SerializationException; @SuppressWarnings("unchecked") class RedisSessionContextServiceTest { @@ -40,7 +45,7 @@ void setUp() { @Test void saveStoresContextInSessionAndIdentityKeys() { - SessionContext context = new SessionContext(1L, 10L, 20L, 30L, 40L, "jwt"); + SessionContext context = new SessionContext(1L, 10L, "20", 30L, 40L, "jwt"); service.save(context); @@ -52,8 +57,8 @@ void saveStoresContextInSessionAndIdentityKeys() { @Test void saveRemovesStaleSessionKeyBeforeWritingNewIdentityBinding() { - SessionContext existing = new SessionContext(1L, 10L, 20L, 30L, 40L, "old-jwt"); - SessionContext replacement = new SessionContext(2L, 10L, 20L, 30L, 40L, "new-jwt"); + SessionContext existing = new SessionContext(1L, 10L, "20", 30L, 40L, "old-jwt"); + SessionContext replacement = new SessionContext(2L, 10L, "20", 30L, 40L, "new-jwt"); when(valueOperations.get("sessionctx:10:identity:40:30:context")).thenReturn(existing); service.save(replacement); @@ -63,9 +68,76 @@ void saveRemovesStaleSessionKeyBeforeWritingNewIdentityBinding() { verify(valueOperations).set("sessionctx:10:identity:40:30:context", replacement, TTL); } + @Test + void savePreservesForeignTenantIndexesFromSessionAlias() { + SessionContext incoming = + new SessionContext(1L, 10L, "88", "new-login", 60L, "Current", 50L, "R-1", "new-jwt"); + SessionContext foreignTenant = + new SessionContext(1L, 99L, "30", "other-login", 31L, "Foreign", 41L, "R-2", "old-jwt"); + when(valueOperations.get("sessionctx:session:1:context")).thenReturn(foreignTenant); + + service.save(incoming); + + verify(redisTemplate, never()).delete("sessionctx:99:1:context"); + verify(redisTemplate, never()).delete("sessionctx:99:identity:41:31:context"); + verify(redisTemplate, never()).delete("sessionctx:99:identity:41:name:foreign:context"); + verify(redisTemplate, never()).delete("sessionctx:session:1:context"); + verify(redisTemplate, never()) + .watch( + Mockito.argThat((Collection keys) -> keys.contains("sessionctx:99:1:context"))); + verify(valueOperations).set("sessionctx:10:1:context", incoming, TTL); + verify(valueOperations).set("sessionctx:session:1:context", incoming, TTL); + } + + @Test + void savePreservesForeignSessionIndexesFromSessionAlias() { + SessionContext incoming = + new SessionContext(1L, 10L, "88", "new-login", 60L, "Current", 50L, "R-1", "new-jwt"); + SessionContext foreignSession = + new SessionContext(2L, 10L, "30", "other-login", 31L, "Foreign", 41L, "R-2", "old-jwt"); + when(valueOperations.get("sessionctx:session:1:context")).thenReturn(foreignSession); + + service.save(incoming); + + verify(redisTemplate, never()).delete("sessionctx:10:2:context"); + verify(redisTemplate, never()).delete("sessionctx:10:identity:41:31:context"); + verify(redisTemplate, never()).delete("sessionctx:10:identity:41:name:foreign:context"); + verify(redisTemplate, never()).delete("sessionctx:session:2:context"); + verify(redisTemplate, never()) + .watch( + Mockito.argThat((Collection keys) -> keys.contains("sessionctx:10:2:context"))); + verify(valueOperations).set("sessionctx:10:1:context", incoming, TTL); + verify(valueOperations).set("sessionctx:session:1:context", incoming, TTL); + } + + @Test + void saveCleansDistinctSessionAliasIndexesForSameTenantAndSession() { + SessionContext incoming = + new SessionContext(1L, 10L, "88", "new-login", 60L, "Current", 50L, "R-1", "new-jwt"); + SessionContext existingContext = + new SessionContext( + 1L, 10L, "30", "context-login", 31L, "ContextOld", 41L, "R-2", "ctx-jwt"); + SessionContext existingSessionAlias = + new SessionContext(1L, 10L, "31", "alias-login", 32L, "AliasOld", 42L, "R-3", "alias-jwt"); + when(valueOperations.get("sessionctx:10:1:context")).thenReturn(existingContext); + when(valueOperations.get("sessionctx:session:1:context")).thenReturn(existingSessionAlias); + + service.save(incoming); + + verify(redisTemplate).delete("sessionctx:10:identity:42:32:context"); + verify(redisTemplate).delete("sessionctx:10:identity:42:name:aliasold:context"); + verify(redisTemplate, Mockito.atLeastOnce()) + .watch( + Mockito.argThat( + (Collection keys) -> + keys.contains("sessionctx:10:identity:42:32:context"))); + verify(valueOperations).set("sessionctx:10:1:context", incoming, TTL); + verify(valueOperations).set("sessionctx:session:1:context", incoming, TTL); + } + @Test void findByTenantAndSessionIdReturnsPersistedContext() { - SessionContext context = new SessionContext(1L, 10L, 20L, 30L, 40L, "jwt"); + SessionContext context = new SessionContext(1L, 10L, "20", 30L, 40L, "jwt"); when(valueOperations.get("sessionctx:10:1:context")).thenReturn(context); Optional result = service.findByTenantAndSessionId(10L, 1L); @@ -75,7 +147,7 @@ void findByTenantAndSessionIdReturnsPersistedContext() { @Test void findByGameplayIdentityReturnsPersistedContext() { - SessionContext context = new SessionContext(1L, 10L, 20L, 30L, 40L, "jwt"); + SessionContext context = new SessionContext(1L, 10L, "20", 30L, 40L, "jwt"); when(valueOperations.get("sessionctx:10:identity:40:30:context")).thenReturn(context); Optional result = service.findByGameplayIdentity(10L, 40L, 30L); @@ -83,9 +155,49 @@ void findByGameplayIdentityReturnsPersistedContext() { assertEquals(Optional.of(context), result); } + @Test + void unreadableRetainedContextFailsClosedAndDoesNotBlockFreshReauthentication() { + String retainedKey = "sessionctx:10:1:context"; + when(valueOperations.get(retainedKey)) + .thenThrow(new SerializationException("old SessionContext record shape")); + + assertEquals(Optional.empty(), service.findByTenantAndSessionId(10L, 1L)); + assertThrows( + SerializationException.class, + () -> service.deleteBySessionId(10L, 1L), + "unreadable retained state must stop cleanup before its evidence can be deleted"); + + SessionContext reauthenticated = + new SessionContext(2L, 10L, "77", "demo@example.com", 0L, null, 0L, null, "fresh-jwt"); + service.save(reauthenticated); + + verify(valueOperations).set("sessionctx:10:2:context", reauthenticated, TTL); + verify(valueOperations).set("sessionctx:session:2:context", reauthenticated, TTL); + verify(redisTemplate, never()).delete(retainedKey); + verify(redisTemplate, never()).delete("sessionctx:1"); + } + + @Test + void unreadableSessionAliasIsNotOverwrittenOrDeletedWhenTenantContextIsAbsent() { + when(valueOperations.get("sessionctx:10:1:context")).thenReturn(null); + when(valueOperations.get("sessionctx:session:1:context")) + .thenThrow(new SerializationException("old session alias record shape")); + + assertThrows(SerializationException.class, () -> service.deleteBySessionId(10L, 1L)); + assertThrows( + SerializationException.class, + () -> service.save(new SessionContext(1L, 10L, "77", null, 0L, null, 0L, null, null))); + + verify(redisTemplate, never()).multi(); + verify(redisTemplate, never()).exec(); + verify(redisTemplate, never()).delete("sessionctx:session:1:context"); + verify(valueOperations, never()) + .set(Mockito.anyString(), Mockito.any(), Mockito.any(Duration.class)); + } + @Test void deleteBySessionIdRemovesBothKeys() { - SessionContext context = new SessionContext(1L, 10L, 20L, 30L, 40L, "jwt"); + SessionContext context = new SessionContext(1L, 10L, "20", 30L, 40L, "jwt"); when(valueOperations.get("sessionctx:10:1:context")).thenReturn(context); service.deleteBySessionId(10L, 1L); @@ -96,10 +208,54 @@ void deleteBySessionIdRemovesBothKeys() { verify(redisTemplate).delete("sessionctx:10:identity:40:30:context"); } + @Test + void deleteBySessionIdPreservesDifferentTenantAliasIndexes() { + SessionContext differentTenant = new SessionContext(1L, 99L, "30", 31L, 41L, "other-jwt"); + when(valueOperations.get("sessionctx:10:1:context")).thenReturn(null); + when(valueOperations.get("sessionctx:session:1:context")).thenReturn(differentTenant); + + service.deleteBySessionId(10L, 1L); + + verify(redisTemplate, never()).delete("sessionctx:99:1:context"); + verify(redisTemplate, never()).delete("sessionctx:session:1:context"); + verify(redisTemplate, never()).delete("sessionctx:99:identity:41:31:context"); + } + + @Test + void deleteBySessionIdPreservesDifferentSessionAliasIndexes() { + SessionContext requested = new SessionContext(1L, 10L, "20", 30L, 40L, "requested-jwt"); + SessionContext differentSession = new SessionContext(2L, 10L, "21", 31L, 41L, "other-jwt"); + when(valueOperations.get("sessionctx:10:1:context")).thenReturn(requested); + when(valueOperations.get("sessionctx:session:1:context")).thenReturn(differentSession); + + service.deleteBySessionId(10L, 1L); + + verify(redisTemplate).delete("sessionctx:10:1:context"); + verify(redisTemplate).delete("sessionctx:10:identity:40:30:context"); + verify(redisTemplate, never()).delete("sessionctx:10:2:context"); + verify(redisTemplate, never()).delete("sessionctx:session:2:context"); + verify(redisTemplate, never()).delete("sessionctx:10:identity:41:31:context"); + } + + @Test + void deleteBySessionIdCleansDistinctContextForSameTenantAndSession() { + SessionContext requested = new SessionContext(1L, 10L, "20", 30L, 40L, "requested-jwt"); + SessionContext sameOwner = new SessionContext(1L, 10L, "20", 31L, 41L, "other-jwt"); + when(valueOperations.get("sessionctx:10:1:context")).thenReturn(requested); + when(valueOperations.get("sessionctx:session:1:context")).thenReturn(sameOwner); + + service.deleteBySessionId(10L, 1L); + + verify(redisTemplate, times(2)).delete("sessionctx:10:1:context"); + verify(redisTemplate, times(2)).delete("sessionctx:session:1:context"); + verify(redisTemplate).delete("sessionctx:10:identity:40:30:context"); + verify(redisTemplate).delete("sessionctx:10:identity:41:31:context"); + } + @Test void savePreservesLocaleTagInStoredContext() { SessionContext context = - new SessionContext(1L, 10L, 20L, null, 30L, null, 40L, "R-1", "jwt", "fr", 40L); + new SessionContext(1L, 10L, "20", null, 30L, null, 40L, "R-1", "jwt", "fr", 40L); service.save(context); diff --git a/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/service/impl/TickQueueControlServiceTest.java b/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/service/impl/TickQueueControlServiceTest.java index 1a01de632f..6f12e16184 100644 --- a/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/service/impl/TickQueueControlServiceTest.java +++ b/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/service/impl/TickQueueControlServiceTest.java @@ -717,7 +717,7 @@ void pauseAndResumeTicksForGameInstanceBumpOwnershipEpochAndPauseFlag() { @Test void queryStateUsesSessionContextTenantFromSessionAuthority() { when(sessionAuthenticationService.resolveUnverifiedSessionContext("7")) - .thenReturn(Optional.of(new SessionContext(7L, 11L, 0L, 0L, 0L, null))); + .thenReturn(Optional.of(new SessionContext(7L, 11L, null, 0L, 0L, null))); when(valueOps.get("session:11:7")).thenReturn("{\"status\":\"ready\"}"); String state = service.queryState(7L); @@ -739,7 +739,7 @@ void queryStateFailsClosedWhenSessionContextMissing() { @Test void queryStateFailsClosedWhenSessionContextHasNoTenantAuthority() { when(sessionAuthenticationService.resolveUnverifiedSessionContext("7")) - .thenReturn(Optional.of(new SessionContext(7L, 0L, 0L, 0L, 0L, null))); + .thenReturn(Optional.of(new SessionContext(7L, 0L, null, 0L, 0L, null))); IllegalArgumentException exception = assertThrows(IllegalArgumentException.class, () -> service.queryState(7L)); diff --git a/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/websocket/GameSessionWebSocketHandlerTest.java b/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/websocket/GameSessionWebSocketHandlerTest.java index 2f00f84011..15fd6594b9 100644 --- a/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/websocket/GameSessionWebSocketHandlerTest.java +++ b/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/websocket/GameSessionWebSocketHandlerTest.java @@ -136,7 +136,7 @@ void afterConnectionEstablishedRegistersValidFirstPartyConnectContext() { "token")); FirstPartyConnectContext connectContext = new FirstPartyConnectContext( - 123L, 22L, "demo", "production", 7L, 3L, "scope-1", "jti", "req-1", "gw-1"); + "123", 22L, "demo", "production", 7L, 3L, "scope-1", "jti", "req-1", "gw-1"); when(firstPartyConnectContextService.parse("token")).thenReturn(Optional.of(connectContext)); when(gameplayAdmissionPointerAuthorityService.listByRuntimeTarget(22L, 7L)) .thenReturn( @@ -199,6 +199,55 @@ void afterConnectionEstablishedRejectsInvalidFirstPartyConnectContextAsExpected( verify(sessionContextService, never()).save(Mockito.any()); } + @Test + void afterConnectionEstablishedRejectsFirstPartyContextWhenRetainedStateCannotBeRegistered() + throws Exception { + when(session.getAttributes()) + .thenReturn( + Map.of( + GameSessionWebSocketHandshakeInterceptor.SESSION_ID_ATTR, + "41", + GameSessionWebSocketHandshakeInterceptor.CONNECTION_MODE_ATTR, + "first_party_web", + GameSessionWebSocketHandshakeInterceptor.CONNECT_CONTEXT_ATTR, + "token")); + FirstPartyConnectContext connectContext = + new FirstPartyConnectContext( + "123", 22L, "demo", "production", 7L, 3L, "scope-1", "jti", "req-1", "gw-1"); + when(firstPartyConnectContextService.parse("token")).thenReturn(Optional.of(connectContext)); + when(gameplayAdmissionPointerAuthorityService.listByRuntimeTarget(22L, 7L)) + .thenReturn( + List.of( + pointer( + "demo", + "Demo", + "production", + "Production", + 22L, + 7L, + 3L, + true, + true, + false, + "SHARED", + "ALLOW_NEW"))); + Mockito.doThrow(new IllegalStateException("retained context is unreadable")) + .when(firstPartyConnectContextRegistry) + .register(41L, connectContext); + + handler.afterConnectionEstablished(session); + + verify(session) + .close( + argThat( + status -> + status.getCode() == CloseStatus.POLICY_VIOLATION.getCode() + && "CONNECT_CONTEXT_INVALID".equals(status.getReason()))); + verify(sessionAuthenticationService, never()).resolveUnverifiedSessionContext(22L, 41L); + verify(sessionContextService, never()).save(Mockito.any()); + verify(firstPartyConnectContextRegistry).register(41L, connectContext); + } + @Test void afterConnectionEstablishedClosesWithServiceUnavailableWhenPointerAuthorityFails() throws Exception { @@ -213,7 +262,7 @@ void afterConnectionEstablishedClosesWithServiceUnavailableWhenPointerAuthorityF "token")); FirstPartyConnectContext connectContext = new FirstPartyConnectContext( - 123L, 22L, "demo", "production", 7L, 3L, "scope-1", "jti", "req-1", "gw-1"); + "123", 22L, "demo", "production", 7L, 3L, "scope-1", "jti", "req-1", "gw-1"); when(firstPartyConnectContextService.parse("token")).thenReturn(Optional.of(connectContext)); when(gameplayAdmissionPointerAuthorityService.listByRuntimeTarget(22L, 7L)) .thenThrow(new IllegalStateException("database unavailable")); @@ -469,7 +518,7 @@ void afterConnectionEstablishedDropsPartialRoutingTupleWhenRuntimeAuthorityIsAmb .save( eq( new SessionContext( - 41L, 22L, 0L, null, 0L, null, 0L, null, null, null, 7L, null, null, 0L, null, + 41L, 22L, null, null, 0L, null, 0L, null, null, null, 7L, null, null, 0L, null, null, null))); } @@ -600,7 +649,7 @@ void afterConnectionEstablishedClearsGenericBootstrapRoutingWhenRuntimeAuthority new SessionContext( 41L, 22L, - 123L, + "123", "demo@example.com", 123L, "Emberline", @@ -649,7 +698,7 @@ void afterConnectionEstablishedClearsGenericBootstrapRoutingWhenRuntimeAuthority context -> context.sessionId() == 41L && context.tenantId() == 22L - && context.accountId() == 0L + && context.accountId() == null && context.bootstrapGameInstanceId() == 7L && "demo".equals(context.worldSlug()) && "production".equals(context.realmSlug()) @@ -664,7 +713,7 @@ void afterConnectionEstablishedClearsGenericBootstrapRoutingWhenRuntimeAuthority new SessionContext( 41L, 22L, - 123L, + "123", "demo@example.com", 123L, "Emberline", @@ -726,7 +775,7 @@ void afterConnectionEstablishedClearsGenericBootstrapRoutingWhenRuntimeAuthority context -> context.sessionId() == 41L && context.tenantId() == 22L - && context.accountId() == 0L + && context.accountId() == null && context.bootstrapGameInstanceId() == 7L && context.worldSlug() == null && context.realmSlug() == null @@ -739,7 +788,7 @@ void handleMessageDoesNotAppendScreenBufferForNormalizedLoggedInShell() throws E PlayerOutput output = PlayerOutput.message("Recent room line"); SessionContext clearedShell = new SessionContext( - 41L, 22L, 123L, "demo@example.com", 0L, null, 0L, null, "jwt", "en-NZ", 1L); + 41L, 22L, "123", "demo@example.com", 0L, null, 0L, null, "jwt", "en-NZ", 1L); when(parser.parse("LOOK")).thenReturn(command); when(interpreter.interpret("41", command, false)) .thenReturn( @@ -774,7 +823,7 @@ void handleMessageDoesNotAppendScreenBufferForPartialGameplayIdentityShell() thr PlayerOutput output = PlayerOutput.message("Recent room line"); SessionContext partialShell = new SessionContext( - 41L, 22L, 123L, "demo@example.com", 7001L, "Emberline", 0L, null, "jwt", "en-NZ", 1L); + 41L, 22L, "123", "demo@example.com", 7001L, "Emberline", 0L, null, "jwt", "en-NZ", 1L); when(parser.parse("LOOK")).thenReturn(command); when(interpreter.interpret("41", command, false)) .thenReturn( @@ -809,7 +858,7 @@ void handleMessageForcesPromptBurstByUiActionMetadata() throws Exception { PlayerOutput output = PlayerOutput.message("Presence: online in Demo World / Live Realm"); SessionContext context = new SessionContext( - 41L, 22L, 123L, "demo@example.com", 7001L, "Emberline", 7L, "R-1", "jwt", "en-NZ", 1L); + 41L, 22L, "123", "demo@example.com", 7001L, "Emberline", 7L, "R-1", "jwt", "en-NZ", 1L); when(parser.parse("WHO")).thenReturn(command); when(interpreter.interpret("41", command, false)) .thenReturn( @@ -846,7 +895,7 @@ void handleMessageForcesPromptBurstForGameplayEntryMetadata() throws Exception { PlayerOutput output = PlayerOutput.message("Entering Demo World"); SessionContext context = new SessionContext( - 41L, 22L, 123L, "demo@example.com", 7001L, "Emberline", 7L, "R-1", "jwt", "en-NZ", 1L); + 41L, 22L, "123", "demo@example.com", 7001L, "Emberline", 7L, "R-1", "jwt", "en-NZ", 1L); when(parser.parse("PLAY demo")).thenReturn(command); when(interpreter.interpret("41", command, false)) .thenReturn( @@ -890,7 +939,7 @@ void handleMessageDoesNotForcePromptBurstForPlayTypeWithoutGameplayEntryMetadata PlayerOutput output = PlayerOutput.message("Custom session response"); SessionContext context = new SessionContext( - 41L, 22L, 123L, "demo@example.com", 7001L, "Emberline", 7L, "R-1", "jwt", "en-NZ", 1L); + 41L, 22L, "123", "demo@example.com", 7001L, "Emberline", 7L, "R-1", "jwt", "en-NZ", 1L); when(parser.parse("CUSTOM-PLAY demo")).thenReturn(command); when(interpreter.interpret("41", command, false)) .thenReturn( @@ -927,7 +976,7 @@ void handleMessageKeepsNonUiCommunicationUnderNormalPromptBurstPolicy() throws E WebSocketSession decoratedSession = Mockito.mock(WebSocketSession.class); SessionContext context = new SessionContext( - 41L, 22L, 123L, "demo@example.com", 7001L, "Emberline", 7L, "R-1", "jwt", "en-NZ", 1L); + 41L, 22L, "123", "demo@example.com", 7001L, "Emberline", 7L, "R-1", "jwt", "en-NZ", 1L); when(session.getId()).thenReturn("session-41"); when(decoratedSession.getId()).thenReturn("session-41"); when(activeTransportSessionRegistry.find(41L)).thenReturn(Optional.of(decoratedSession)); @@ -975,7 +1024,7 @@ void handleMessageDoesNotReplayReconnectBufferForNormalizedLoggedInShell() throw TextCommand command = new TextCommand(TextCommandType.PLAY, List.of("demo"), "PLAY demo"); SessionContext clearedShell = new SessionContext( - 41L, 22L, 123L, "demo@example.com", 0L, null, 0L, null, "jwt", "en-NZ", 1L); + 41L, 22L, "123", "demo@example.com", 0L, null, 0L, null, "jwt", "en-NZ", 1L); when(parser.parse("PLAY demo")).thenReturn(command); when(interpreter.interpret("41", command, false)) .thenReturn( @@ -1006,7 +1055,7 @@ void handleMessageDoesNotReplayReconnectBufferForPartialGameplayIdentityShell() TextCommand command = new TextCommand(TextCommandType.PLAY, List.of("demo"), "PLAY demo"); SessionContext partialShell = new SessionContext( - 41L, 22L, 123L, "demo@example.com", 0L, null, 1L, null, "jwt", "en-NZ", 1L); + 41L, 22L, "123", "demo@example.com", 0L, null, 1L, null, "jwt", "en-NZ", 1L); when(parser.parse("PLAY demo")).thenReturn(command); when(interpreter.interpret("41", command, false)) .thenReturn( @@ -1045,7 +1094,7 @@ void handleMessageUsesTenantScopedSessionContextWhenTenantAttributePresent() thr PlayerOutput output = PlayerOutput.message("Recent room line"); SessionContext clearedShell = new SessionContext( - 41L, 22L, 123L, "demo@example.com", 0L, null, 0L, null, "jwt", "en-NZ", 1L); + 41L, 22L, "123", "demo@example.com", 0L, null, 0L, null, "jwt", "en-NZ", 1L); when(parser.parse("LOOK")).thenReturn(command); when(interpreter.interpret("41", command, false)) .thenReturn( @@ -1233,7 +1282,21 @@ void handleMessageRebootsGenericSessionContextWhenSessionIndexLookupIsMissing() "LOGIN demo@example.com swordfish"); SessionContext tenantScoped = new SessionContext( - 41L, 22L, 0L, null, 0L, null, 0L, null, null, null, 7L, "demo", "production", 3L, null); + 41L, + 22L, + null, + null, + 0L, + null, + 0L, + null, + null, + null, + 7L, + "demo", + "production", + 3L, + null); when(parser.parse("LOGIN demo@example.com swordfish")).thenReturn(command); when(sessionAuthenticationService.resolveUnverifiedSessionContext(22L, 41L)) .thenReturn(Optional.of(tenantScoped)); diff --git a/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/websocket/WebSocketOutputProjectorTest.java b/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/websocket/WebSocketOutputProjectorTest.java index e6d4c63271..bf36dd9d4d 100644 --- a/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/websocket/WebSocketOutputProjectorTest.java +++ b/services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/websocket/WebSocketOutputProjectorTest.java @@ -156,7 +156,7 @@ void firstPartyWebUsesAdmittedMetadataForAuthoredCommand() throws Exception { GameSessionWebSocketHandshakeInterceptor.CONNECTION_MODE_ATTR, "first_party_web")); SessionContext context = new SessionContext( - 7L, 22L, 41L, "emberline@example.com", 7001L, "Emberline", 9L, "R-1", "jwt"); + 7L, 22L, "41", "emberline@example.com", 7001L, "Emberline", 9L, "R-1", "jwt"); AdmittedTextCommandRegistryResolver admittedResolver = mock(AdmittedTextCommandRegistryResolver.class); when(admittedResolver.resolveMetadata(context, "wave", "wave")) diff --git a/services/game-session-service/src/testFixtures/java/net/firedevops/firemud/gamesession/testsupport/GameplayCrossServiceStack.java b/services/game-session-service/src/testFixtures/java/net/firedevops/firemud/gamesession/testsupport/GameplayCrossServiceStack.java index 0ff9fc897c..03b453aef3 100644 --- a/services/game-session-service/src/testFixtures/java/net/firedevops/firemud/gamesession/testsupport/GameplayCrossServiceStack.java +++ b/services/game-session-service/src/testFixtures/java/net/firedevops/firemud/gamesession/testsupport/GameplayCrossServiceStack.java @@ -864,7 +864,7 @@ public void seedLiveSession( new SessionContext( sessionId, tenantId, - accountId, + Long.toString(accountId), loginName, characterId, characterName, @@ -891,7 +891,7 @@ public void seedLiveSession( new SessionContext( sessionId, tenantId, - accountId, + Long.toString(accountId), loginName, characterId, characterName,