diff --git a/design/architecture/microservices/account-service/api-contracts.md b/design/architecture/microservices/account-service/api-contracts.md
index a4198bb82e..fc4f372d2d 100644
--- a/design/architecture/microservices/account-service/api-contracts.md
+++ b/design/architecture/microservices/account-service/api-contracts.md
@@ -308,6 +308,8 @@ The shared codec preserves the existing 64 KiB lease and 15-second lifetime boun
The never-admitted abort uses separate negative-purpose messages and the reverse `GetOriginalNewNeverAdmittedDecision` Game Session RPC. Account independently reads Game Session’s qualified exact-original closure before retaining a negative resolution; no provisional or committed decision is synthesized. The [interrupted original NEW contract](../../system-architecture-session-behavior.md#canonical-public-production-new-admission) owns irreversible selection, continuous qualification and cleanup requirements. The ordinary positive decision readers reject this purpose. The reverse negative read returns bounded `FAILED_PRECONDITION` for definitive retained-source or selector conflicts, `UNAVAILABLE` for missing or withdrawn closure qualification and transient SQL/Redis outages, and `INTERNAL` for unexpected or response-encoding failures. Caller and malformed-request refusals remain `PERMISSION_DENIED` and `INVALID_ARGUMENT`. These manual receivers remain unregistered.
+The local lease owner accepts explicit `AccountGameplayAdmissionPaidSource` composition for paid NEW sources. Its existing DEMO-only constructor cannot acquire or first-finalize a paid lease. It can replay an exact committed paid finalization after validating the current caller and matching the retained acknowledgement receipt, without querying the paid source. This adds no wire field, caller source selector or registered method. Source and proof limits are recorded in [canonical NEW admission components](../../../project-management/implementation-tracking/player-access-and-session.md#canonical-new-admission-components).
+
#### Unknown-decision abort resolution
An `ABORTED` original operation whose decision was unknown retains its null decision, original lease bytes and cleanup reference permanently. A later transition-selected Abort may return separate Account-owned resolution evidence; it never changes that original terminal result. Account verifies the exact existing provisional Game Session decision through its protected reverse read outside SQL, then rechecks the current authenticated caller and unchanged original abort under a fresh writable serializable transaction before recording one immutable resolution. The resolution binds its own identity, the original lease UUID, fence and canonical digest, the original cleanup UUID and the verified transition UUID. It grants neither admission nor completed Game Session cleanup.
diff --git a/design/architecture/microservices/account-service/runtime-and-data.md b/design/architecture/microservices/account-service/runtime-and-data.md
index d24eb4fa4b..8410016035 100644
--- a/design/architecture/microservices/account-service/runtime-and-data.md
+++ b/design/architecture/microservices/account-service/runtime-and-data.md
@@ -22,7 +22,7 @@ Ordinary control-UI, gameplay password/email-OTP, and player-bootstrap issuance
The global Account REST selectors resolve public UUIDs to private numeric rows before Account-local service calls. Private numeric row keys remain local to storage; the [Account API contract](./api-contracts.md#rest-apis) owns caller authorization, selector, and failure behavior. The final receiving composition carries UUID identity through shared context, gRPC and Logging consumers. Tenant representations follow the [Account tenant identifier boundary](./api-contracts.md#account-tenant-identifier-boundary), which distinguishes canonical public/direct-text scopes and JOIN results from legacy numeric runtime reads. [Player Access and Session](../../../project-management/implementation-tracking/player-access-and-session.md#ordinary-uuid-issuer-and-receiving) records current implementation and focused proof. Full token-profile qualification and production authorization custody remain separate.
-The caller verifier, lease owner and certificate-guarded seven-method receiver remain manually composed and unregistered. Their [lease contract](./api-contracts.md#canonical-public-production-new-admission-lease-source) preserves immutable original attempts and ACKs, with full tenant-source guards for new acquisition and first finalization and the separate current-caller/global-Account/token guards for exact metadata and cleanup recovery. Current-token verification alone grants no admission. Forward V1014 stores separate immutable resolution of a retained unknown-decision abort without rewriting its original terminal evidence. Forward V1015 adds a disjoint never-admitted negative resolution, retaining the original transition, abandonment and candidate/closure digests without a binding decision; the linked lease contract owns its exact selectors and authority. Focused actual Account–Game Session composition covers that exact recovery and restart boundary; upstream source custody and test PKI remain controlled. Broader token-retirement and orphan-cleanup delivery, default registration and admitted binding remain unqualified. [Player Access and Session](../../../project-management/implementation-tracking/player-access-and-session.md#canonical-new-admission-components) owns the implementation and proof details.
+The caller verifier, lease owner and certificate-guarded seven-method receiver remain manually composed and unregistered. Their [lease contract](./api-contracts.md#canonical-public-production-new-admission-lease-source) preserves immutable original attempts and ACKs, with full tenant-source guards for new acquisition and first finalization and the separate current-caller/global-Account/token guards for exact metadata and cleanup recovery. The explicit paid NEW composition reuses existing hosting storage and its current reader on each exact enlisted connection; no new schema or default registration is introduced. Current-token verification alone grants no admission. Forward V1014 stores separate immutable resolution of a retained unknown-decision abort without rewriting its original terminal evidence. Forward V1015 adds a disjoint never-admitted negative resolution, retaining the original transition, abandonment and candidate/closure digests without a binding decision; the linked lease contract owns its exact selectors and authority. Focused actual Account–Game Session composition covers that exact recovery and restart boundary; upstream source custody and test PKI remain controlled. Broader token-retirement and orphan-cleanup delivery, default registration and admitted binding remain unqualified. [Player Access and Session](../../../project-management/implementation-tracking/player-access-and-session.md#canonical-new-admission-components) owns the implementation and proof details.
The selected-recipient intake source prepares distinct Entity/Automation source reservations and finalized authorizations, retained source-writer exclusion, and exact terminal settlement. Expired preliminary recovery pages use a caller-held `(expiry epoch second, operation UUID)` keyset cursor that advances across every examined row, including invalid rows and candidates whose abort does not commit; a caller continues while a cursor is returned and starts a fresh sweep only after an empty page. Prepared final authorization and terminal migrations V1008–V1010 follow the actual V1006 activation-alignment and V1007 source-disclosure parent, including Saga V1000–V1002, while preserving prior protection/disposal guards. These components remain unregistered and unqualified; the [recipient-intake tracker](../../../project-management/implementation-tracking/player-access-and-session.md#selected-recipient-source-intake-preparation) owns current proof, qualification limits and remaining dependencies.
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 3884ff387c..00ae0adfb0 100644
--- a/design/project-management/implementation-tracking/player-access-and-session.md
+++ b/design/project-management/implementation-tracking/player-access-and-session.md
@@ -192,6 +192,12 @@ The unregistered receiver includes explicit original closure under the existing
### Canonical NEW admission components
+The Account NEW source now prepares an explicit paid-hosting composition alongside DEMO. Account selects the current source head, prepares the existing hosting owner's exact fence in an Account-first writable SERIALIZABLE transaction, observes the real bounded Stripe SDK outside SQL, then reconstructs that owner on the decisive transaction's exact connection and rereads its current receipt. Opaque owner-bound preparation/observation carries no caller-selected source authority; missing paid composition, changed heads, unresolved provider facts and expired authority fail closed without DEMO fallback. The original lease retains the same five source subtrees and is additionally capped at paid authority expiry. First finalization rereads complete paid authority through the original physical-COMMIT executor and exact-compares the original lease; metadata, cleanup and terminal receipt recovery retain their narrower current-caller checks. The [canonical session contract](../../architecture/system-architecture-session-behavior.md#canonical-public-production-new-admission) remains normative. Seven new PostgreSQL source/composition definitions cover actual owner reads, missing composition/observation, no provider read in SQL, provider disagreement/expiry, changed heads, authenticated acquisition/finalization/recovery and writer exclusion through physical COMMIT. On the local paid-source postimage over baseline `cee9af5e75f2f84140efdc6f9e902794cf61986e`, the focused gate passes all 87 selected unit cases with zero failures, errors or skips: four lease-owner, 26 original-COMMIT executor, 40 ACK-receipt executor, eleven hosting-repository and six hosting-policy cases. Full integration compilation includes the new paid fixture; enabled main/test/integration SpotBugs, Java formatting and Markdown lint pass. The initial gate failed on one unnecessary new SpotBugs suppression, removed before the successful rerun. Physical PostgreSQL/Redis execution remains unrun because Docker is unavailable, and external link checking remains unrun. Compilation and static analysis do not replace physical proof. Controlled provider transport, reverse Game Session evidence and test custody do not establish live Stripe, an admitted binding, production registration or available `PLAY`/`LOOK`.
+
+The unregistered Account paid NEW composition requires an explicit deployment entitlement clock-skew bound below 15 seconds. The focused fixture supplies a synthetic bound. Production registration remains held until deployment supplies the validated entitlement freshness configuration.
+
+The original paid-provider observation freshness contract remains held. The last decisive Account source read rejects an expired paid receipt, but does not establish that the original observation remains fresh through physical COMMIT and ACK. That crossing is still unqualified; the focused checks above are not proof of it.
+
Local negative-continuation preparation retains irreversible original-candidate abandonment, a persistent non-admitting Redis closure, separately authenticated Account negative resolution, and genuine ordinary-local or installed frozen-cohort issuer release/retirement. R1044 executes 33 selected Game Session cases (30 pass, two historical-fixture failures and one PostgreSQL startup failure) and nine Account cases (five pass, two ordinary terminal-retirement failures, one inaccessible test-handle failure and one Redis startup failure). The run's failed aggregate remains retained; later corrections are qualified by the separately attributed receiving results below. Pre-anchor or superseded issued work without an installed revision owner remains unresolved and non-admitting under Gameplay ownership. Existing holds authorize no old-key cleanup, invented ordinary registration or Redis-absence proof; this does not waive the separately held recovery scope. Implementing that held category requires an exact authority/contract proposal. Controlled qualification, upstream source and test PKI do not establish production custody, registration, activation or gameplay admission.
For the PLAYER_CREATED correction, R1069 passed 67/68 selected cases; its single failure was an initial Redis connection refusal of unknown cause. R1074 then passed 122/126, with three Account negative-composition failures because V1051 omitted inherited `NEVER_DISPATCHED` branches and one World cleanup failure that could mask the primary exception; the underlying connection-refusal cause remains unknown. Corrected V1051 retains the inherited statuses and branch without editing source-parent migrations. On corrected source `e93aac69277af1fe39afe196db1546cf5eb4737a`, R1077 separately passes all 15 selected cases (eight Game Session region-owner, three Account final-admission, three Account negative-composition and one World receipt case), plus selected static, generation and documentation checks; source hashes are stable and Spotless made no formatter changes. R1082 is local proof only, with its two-file test preparation subsequently retained at `c8f16db50e27a754e1d80a94d09c8d8f32f2ee4f` on genuine parent `d2e3a21a31419680e68ab2da6ea7e808e4efd83c`: against that V1050.4 parent, before introducing corrected V1051, both ordinary and installed parameter cases pass while preserving release/retirement records, old columns and `xmin`, Flyway history/checksums, issuer/closure Redis and exact retry after Account restart. R1079 remains a failed pre-migration proof setup because it repeated preparation after cleanup and supplies no migration credit. R1086 subsequently passes all 31 selected receiving cases on reconciled source `b7143cf062699bca230f4c2cbec03f9da651a380`: Account handler and bounded-readback units, Game Session authenticated-session and candidate units, three actual Account final-admission compositions and both Entity namespace concurrency/scope-refusal regressions. All selected generation, enabled static analysis, formatting and documentation checks pass, with no service formatter delta. R1089 separately passes 26 native executions on the receiving child (eight final-owner and 18 parameterized Account definitive-abort cases), including the new explicit REQUIRED-delete refusal. Positive-source R1092 subsequently passes 26 executions (13 reader units, four reader-service units and nine native final-owner cases) after separating clock unavailability from retained-source conflict and tightening every refusal assertion. Its new native case confirms the existing committed-receipt delete guard, unchanged retained state through clock lag and successful readback when the clock catches up; R1093 separately executes all 12 selected descendant native cases (nine final-owner and three actual Account compositions) successfully, with selected static analysis and no source/formatter changes. Its aggregate remains failed because Markdown lint rejected the added HTML link anchor; the Markdown-heading correction and documentation recovery retain separate attribution. These separate results do not establish an all-126 clean aggregate, current CI, production/default registration, PKI custody or activation.
diff --git a/services/account-service/src/main/java/net/firedevops/firemud/accountservice/repository/AccountGameplayAdmissionCurrentSources.java b/services/account-service/src/main/java/net/firedevops/firemud/accountservice/repository/AccountGameplayAdmissionCurrentSources.java
index 021b5574be..8f708db2b2 100644
--- a/services/account-service/src/main/java/net/firedevops/firemud/accountservice/repository/AccountGameplayAdmissionCurrentSources.java
+++ b/services/account-service/src/main/java/net/firedevops/firemud/accountservice/repository/AccountGameplayAdmissionCurrentSources.java
@@ -11,6 +11,8 @@
import java.util.UUID;
import net.firedevops.firemud.accountservice.dto.DemoTenantEntitlementEventV1Codec;
import net.firedevops.firemud.accountservice.repository.AccountGameplayDelegationIssuanceRepository.CommittedCandidateVerificationData;
+import net.firedevops.firemud.accountservice.repository.AccountTenantAuthorityEventRepository.SourceKind;
+import net.firedevops.firemud.accountservice.repository.AccountTenantAuthorityEventRepository.SourceSelection;
import net.firedevops.firemud.common.account.admission.AccountGameplayAdmissionLeaseEvidence;
import net.firedevops.firemud.common.account.authority.MembershipAuthorityEventV1Codec;
import net.firedevops.firemud.common.account.authority.MembershipAuthorityEventV1Codec.AuthorityTuple;
@@ -29,11 +31,11 @@
* admission.
*
*
The caller enlists the exact supplied DSLContext in its writable SERIALIZABLE transaction.
- * This component creates no transaction, performs no writes or network calls, and owns no lease. It
- * reads current Account membership, tenant entitlement, and the active SQL token fence under the
- * canonical Account-first lock order. The caller verifier remains responsible for JWT/JWKS and
- * exact Redis currentness outside SQL; this source cannot re-prove either remote registry state or
- * a published gameplay target.
+ * This component creates no transaction, performs no writes, and owns no lease. Its SQL phases read
+ * current Account membership, tenant entitlement, and the active SQL token fence under the
+ * canonical Account-first lock order; its prepared handle observes the provider only outside SQL.
+ * The caller verifier remains responsible for JWT/JWKS and exact Redis currentness outside SQL;
+ * this source cannot re-prove either remote registry state or a published gameplay target.
*
*
The returned membership snapshot is complete current Account evidence. The Current result can
* produce the five unchanged Account source subtrees for a lease and compare them against an
@@ -43,9 +45,9 @@
* global issuer/account authority and ACTIVE token checks but deliberately does not require the
* original tenant membership or entitlement baseline to remain unchanged.
*
- *
The NEW lease projection currently supports explicit DEMO entitlements only. Paid current
- * tenant authority remains readable by the generic membership source, but this DEMO-shaped lease
- * projection refuses paid hosting rather than decoding it as DEMO or consulting a provider in SQL.
+ *
Paid sources require an opaque preparation and actual provider observation from the concrete
+ * hosting owner composition. Its receipt is revalidated on this exact SQL connection. A missing
+ * paid composition or changed selected head never falls back to DEMO.
*/
public final class AccountGameplayAdmissionCurrentSources {
private static final String ACCOUNT_ISSUER = GameSessionAccountDelegationProfile.ISSUER;
@@ -63,18 +65,21 @@ public final class AccountGameplayAdmissionCurrentSources {
private final AccountTenantAuthorityEventRepository tenantAuthorityEvents;
private final AccountTenantEntitlementOutboxRepository tenantEntitlementOutbox;
private final AccountGameplayDelegationIssuanceRepository issuance;
+ private final String workloadNamespace;
private AccountGameplayAdmissionCurrentSources(
DSLContext dsl,
AccountCanonicalRuntimeMembershipSnapshotRepository membershipSnapshots,
AccountTenantAuthorityEventRepository tenantAuthorityEvents,
AccountTenantEntitlementOutboxRepository tenantEntitlementOutbox,
- AccountGameplayDelegationIssuanceRepository issuance) {
+ AccountGameplayDelegationIssuanceRepository issuance,
+ String workloadNamespace) {
this.dsl = Objects.requireNonNull(dsl);
this.membershipSnapshots = Objects.requireNonNull(membershipSnapshots);
this.tenantAuthorityEvents = Objects.requireNonNull(tenantAuthorityEvents);
this.tenantEntitlementOutbox = Objects.requireNonNull(tenantEntitlementOutbox);
this.issuance = Objects.requireNonNull(issuance);
+ this.workloadNamespace = workloadNamespace;
}
/**
@@ -127,7 +132,43 @@ static AccountGameplayAdmissionCurrentSources bind(
new AccountGameplayDelegationIssuanceRepository(exactDsl, sourceEvidence, evidenceBundles);
return new AccountGameplayAdmissionCurrentSources(
- exactDsl, membershipSnapshots, tenantAuthorityEvents, tenantEntitlementOutbox, issuance);
+ exactDsl,
+ membershipSnapshots,
+ tenantAuthorityEvents,
+ tenantEntitlementOutbox,
+ issuance,
+ configuredWorkloadNamespace);
+ }
+
+ /** Captures only Account-owned selectors/fences; the provider read follows outside SQL. */
+ Prepared prepareCurrentPublicProductionNew(
+ UUID tenantId,
+ UUID originalTokenJti,
+ CommittedCandidateVerificationData candidate,
+ AccountGameplayAdmissionPaidSource paidSource) {
+ UUID accountId = verifiedCallerAccountId(tenantId, originalTokenJti, candidate);
+ requireWritableSerializableAccountTransaction();
+
+ // The hosting lifecycle's lock order is Account -> customer -> instrument -> tenant owner ->
+ // subscription -> tenant generation. Complete its SQL preparation before membership/source
+ // reads lock tenant generations, avoiding a reverse edge when a joiner differs from the payer.
+ AccountGameplayAdmissionPaidSource.Preparation paidPreparation = null;
+ if (paidSource != null
+ && paidSource.hasCurrentPaidSourceCandidate(dsl, workloadNamespace, tenantId)) {
+ lockRequiredAccountsBeforeTenantSources(dsl, tenantId, accountId);
+ paidPreparation = paidSource.prepare(dsl, workloadNamespace, tenantId);
+ } else {
+ lockExactAccountFirst(accountId);
+ }
+ CallerSources caller = readCallerSources(tenantId, originalTokenJti, candidate, accountId);
+ SourceSelection selected = caller.selection();
+ if (selected.kind() == SourceKind.PAID_HOSTING) {
+ if (paidPreparation == null) throw unavailable();
+ } else {
+ if (paidPreparation != null) throw unavailable();
+ requireCurrentDemo(caller.snapshot(), tenantId, selected.checkpoint());
+ }
+ return new Prepared(selected, paidSource, paidPreparation);
}
/**
@@ -141,35 +182,80 @@ Current readCurrentPublicProductionNew(
UUID targetTenantId,
UUID expectedOriginalTokenJti,
CommittedCandidateVerificationData expectedCommittedCandidate) {
- Objects.requireNonNull(expectedCommittedCandidate, "Verified caller candidate is required");
- requireNonNilUuid(targetTenantId, "Canonical target tenant UUID");
- requireV4Uuid(expectedOriginalTokenJti, "Expected original token JTI");
+ return readCurrentPublicProductionNew(
+ targetTenantId, expectedOriginalTokenJti, expectedCommittedCandidate, null);
+ }
- var expectedIdentity = expectedCommittedCandidate.identity();
- UUID accountId = expectedIdentity.accountId();
- requireNonNilUuid(accountId, "Verified caller Account UUID");
- if (!expectedOriginalTokenJti.equals(expectedIdentity.tokenJti())
- || !accountId.equals(expectedCommittedCandidate.authoritySnapshot().accountId())) {
- throw unavailable();
+ Current readCurrentPublicProductionNew(
+ UUID targetTenantId,
+ UUID expectedOriginalTokenJti,
+ CommittedCandidateVerificationData expectedCommittedCandidate,
+ Observed observed) {
+ UUID accountId =
+ verifiedCallerAccountId(
+ targetTenantId, expectedOriginalTokenJti, expectedCommittedCandidate);
+ requireWritableSerializableAccountTransaction();
+
+ // Reacquire the complete hosting lifecycle lock set before taking membership/tenant source
+ // generations. The post-lock source selector below still verifies that this receipt is the
+ // exact current paid source for the requested tenant.
+ AccountHostingSubscriptionCurrentReceipt paidReceipt = null;
+ if (observed != null && observed.paidSource != null && observed.paidObservation != null) {
+ lockRequiredAccountsBeforeTenantSources(dsl, targetTenantId, accountId);
+ paidReceipt =
+ observed.paidSource.readCurrent(dsl, workloadNamespace, observed.paidObservation);
+ } else {
+ lockExactAccountFirst(accountId);
}
+ CallerSources caller =
+ readCallerSources(
+ targetTenantId, expectedOriginalTokenJti, expectedCommittedCandidate, accountId);
+ SourceSelection selected = caller.selection();
+ if (observed != null
+ && (selected.kind() != observed.selected.kind()
+ || !observed.selected.matches(selected.checkpoint()))) throw unavailable();
+ Long sourceValidUntilMs = null;
+ if (selected.kind() == SourceKind.PAID_HOSTING) {
+ if (paidReceipt == null) throw unavailable();
+ var receipt = paidReceipt;
+ TenantAuthorityEventV1Codec.Event event = receipt.tenantAuthorityEvent();
+ if (!targetTenantId.equals(receipt.current().tenantId())
+ || !selected.matches(event)
+ || !receipt.receiptRequestId().equals(event.requestId())
+ || !receipt.billingEventId().equals(event.tenantBillingEventId())
+ || !receipt.billingEventDigest().equals(event.tenantBillingEventDigest())
+ || receipt.tenantBillingSequence() != event.tenantBillingSequence()
+ || !receipt.gameplayAvailable()
+ || !receipt.allowNewGameplayBindings()) {
+ throw unavailable();
+ }
+ requireSupportedPublicTenantTuple(
+ caller.snapshot(), targetTenantId, event, receipt.tenantBillingSequence());
+ sourceValidUntilMs = observed.paidSource.requireReceiptStillCurrent(receipt).toEpochMilli();
+ } else {
+ if (paidReceipt != null) throw unavailable();
+ requireCurrentDemo(caller.snapshot(), targetTenantId, selected.checkpoint());
+ }
+ return new Current(caller.snapshot(), caller.candidate(), sourceValidUntilMs);
+ }
- requireWritableSerializableAccountTransaction();
- lockExactAccountFirst(accountId);
+ private void requireCurrentDemo(
+ Snapshot snapshot, UUID tenantId, TenantAuthorityEventV1Codec.Event authorityEvent) {
+ DemoTenantEntitlementEventV1Codec.Event event =
+ readExactCurrentTenantEntitlement(tenantId, authorityEvent);
+ requireSupportedPublicTenantTuple(
+ snapshot, tenantId, authorityEvent, event.tenantBillingSequence());
+ if (!event.gameplayAvailable() || !event.allowNewGameplayBindings()) throw unavailable();
+ }
+ private CallerSources readCallerSources(
+ UUID targetTenantId,
+ UUID expectedOriginalTokenJti,
+ CommittedCandidateVerificationData expectedCommittedCandidate,
+ UUID accountId) {
Snapshot snapshot = membershipSnapshots.readCurrent(accountId, targetTenantId);
var selected = tenantAuthorityEvents.readCurrentSourceSelection(targetTenantId);
- if (selected.kind() != AccountTenantAuthorityEventRepository.SourceKind.NON_PAID_DEMO) {
- throw unavailable();
- }
- TenantAuthorityEventV1Codec.Event authorityEvent = selected.checkpoint();
- DemoTenantEntitlementEventV1Codec.Event typedTenantEvent =
- readExactCurrentTenantEntitlement(targetTenantId, authorityEvent);
-
requireCurrentActiveMembership(snapshot, accountId, targetTenantId);
- requireSupportedPublicTenantTuple(snapshot, targetTenantId, authorityEvent, typedTenantEvent);
- if (!typedTenantEvent.gameplayAvailable() || !typedTenantEvent.allowNewGameplayBindings()) {
- throw unavailable();
- }
CommittedCandidateVerificationData currentCommittedCandidate =
issuance
@@ -181,7 +267,25 @@ Current readCurrentPublicProductionNew(
}
requireCandidateAuthorityMatchesSnapshot(currentCommittedCandidate, snapshot, accountId);
- return new Current(snapshot, typedTenantEvent, currentCommittedCandidate);
+ return new CallerSources(snapshot, selected, currentCommittedCandidate);
+ }
+
+ private UUID verifiedCallerAccountId(
+ UUID tenantId,
+ UUID expectedOriginalTokenJti,
+ CommittedCandidateVerificationData expectedCommittedCandidate) {
+ Objects.requireNonNull(expectedCommittedCandidate, "Verified caller candidate is required");
+ requireNonNilUuid(tenantId, "Canonical target tenant UUID");
+ requireV4Uuid(expectedOriginalTokenJti, "Expected original token JTI");
+
+ var expectedIdentity = expectedCommittedCandidate.identity();
+ UUID accountId = expectedIdentity.accountId();
+ requireNonNilUuid(accountId, "Verified caller Account UUID");
+ if (!expectedOriginalTokenJti.equals(expectedIdentity.tokenJti())
+ || !accountId.equals(expectedCommittedCandidate.authoritySnapshot().accountId())) {
+ throw unavailable();
+ }
+ return accountId;
}
/**
@@ -374,7 +478,7 @@ private static void requireSupportedPublicTenantTuple(
Snapshot snapshot,
UUID tenantId,
TenantAuthorityEventV1Codec.Event authorityEvent,
- DemoTenantEntitlementEventV1Codec.Event typedTenantEvent) {
+ long tenantBillingSequence) {
String tenantKey = tenantId.toString();
AuthorityTuple tuple = snapshot.authorityTuple();
Map expectedTenantGeneration =
@@ -384,7 +488,7 @@ private static void requireSupportedPublicTenantTuple(
TenantBillingCutoff expectedBillingCutoff =
new TenantBillingCutoff(
Long.toString(authorityEvent.tenantAuthorityGeneration()),
- Long.toString(typedTenantEvent.tenantBillingSequence()),
+ Long.toString(tenantBillingSequence),
authorityEvent.outboxStreamKey(),
Long.toString(authorityEvent.outboxSequence()));
Map expectedBillingCutoffs =
@@ -511,12 +615,12 @@ private static IllegalStateException unavailable() {
/** Complete, immutable source result; it contains neither a JWT nor registry bytes. */
record Current(
Snapshot snapshot,
- DemoTenantEntitlementEventV1Codec.Event typedTenantEvent,
- CommittedCandidateVerificationData currentCommittedCandidate) {
+ CommittedCandidateVerificationData currentCommittedCandidate,
+ Long sourceValidUntilMs) {
Current {
Objects.requireNonNull(snapshot);
- Objects.requireNonNull(typedTenantEvent);
Objects.requireNonNull(currentCommittedCandidate);
+ if (sourceValidUntilMs != null && sourceValidUntilMs <= 0L) throw unavailable();
}
/** Returns exactly the five immutable, current-source subtrees used by lease capture. */
@@ -531,6 +635,9 @@ void requireMatchesOriginalLease(AccountGameplayAdmissionLeaseEvidence originalL
!= AccountGameplayAdmissionLeaseEvidence.LeaseKind.NEW_BINDING) {
throw unavailable();
}
+ if (sourceValidUntilMs != null
+ && Long.parseLong((String) originalLease.carrier().get("expiresAt")) > sourceValidUntilMs)
+ throw unavailable();
Map carrier = originalLease.carrier();
Object scopeValue = carrier.get("bindingScope");
if (!(scopeValue instanceof Map, ?> bindingScope)
@@ -545,4 +652,46 @@ void requireMatchesOriginalLease(AccountGameplayAdmissionLeaseEvidence originalL
}
}
}
+
+ private record CallerSources(
+ Snapshot snapshot, SourceSelection selection, CommittedCandidateVerificationData candidate) {}
+
+ static final class Prepared {
+ private final SourceSelection selected;
+ private final AccountGameplayAdmissionPaidSource paidSource;
+ private final AccountGameplayAdmissionPaidSource.Preparation paidPreparation;
+
+ private Prepared(
+ SourceSelection selected,
+ AccountGameplayAdmissionPaidSource paidSource,
+ AccountGameplayAdmissionPaidSource.Preparation paidPreparation) {
+ this.selected = selected;
+ this.paidSource = paidSource;
+ this.paidPreparation = paidPreparation;
+ }
+
+ Observed observeOutsideSql() {
+ if (TransactionSynchronizationManager.isActualTransactionActive()
+ || TransactionSynchronizationManager.isSynchronizationActive()) throw unavailable();
+ return new Observed(
+ selected,
+ paidSource,
+ paidPreparation == null ? null : paidSource.observe(paidPreparation));
+ }
+ }
+
+ static final class Observed {
+ private final SourceSelection selected;
+ private final AccountGameplayAdmissionPaidSource paidSource;
+ private final AccountGameplayAdmissionPaidSource.Observation paidObservation;
+
+ private Observed(
+ SourceSelection selected,
+ AccountGameplayAdmissionPaidSource paidSource,
+ AccountGameplayAdmissionPaidSource.Observation paidObservation) {
+ this.selected = selected;
+ this.paidSource = paidSource;
+ this.paidObservation = paidObservation;
+ }
+ }
}
diff --git a/services/account-service/src/main/java/net/firedevops/firemud/accountservice/repository/AccountGameplayAdmissionLeaseOwner.java b/services/account-service/src/main/java/net/firedevops/firemud/accountservice/repository/AccountGameplayAdmissionLeaseOwner.java
index 7ee682d41a..26bfb9539e 100644
--- a/services/account-service/src/main/java/net/firedevops/firemud/accountservice/repository/AccountGameplayAdmissionLeaseOwner.java
+++ b/services/account-service/src/main/java/net/firedevops/firemud/accountservice/repository/AccountGameplayAdmissionLeaseOwner.java
@@ -68,12 +68,23 @@ public final class AccountGameplayAdmissionLeaseOwner {
private final String workloadNamespace;
private final AccountGameplayAdmissionOriginalCommitExecutor originalCommitExecutor;
private final AccountGameplayAdmissionOriginalAckReceiptCommitExecutor receiptExecutor;
+ private final AccountGameplayAdmissionPaidSource paidSource;
public AccountGameplayAdmissionLeaseOwner(
AccountGameplayAdmissionCallerVerifier callerVerifier,
CanonicalGameplayAdmissionDecisionReadClient decisionReadClient,
String workloadNamespace,
DataSource dataSource) {
+ this(callerVerifier, decisionReadClient, workloadNamespace, dataSource, null);
+ }
+
+ /** Explicit paid source composition; the four-argument form remains DEMO-only. */
+ public AccountGameplayAdmissionLeaseOwner(
+ AccountGameplayAdmissionCallerVerifier callerVerifier,
+ CanonicalGameplayAdmissionDecisionReadClient decisionReadClient,
+ String workloadNamespace,
+ DataSource dataSource,
+ AccountGameplayAdmissionPaidSource paidSource) {
this.callerVerifier =
Objects.requireNonNull(callerVerifier, "Account caller verifier required");
this.decisionReadClient =
@@ -83,6 +94,7 @@ public AccountGameplayAdmissionLeaseOwner(
}
this.workloadNamespace = workloadNamespace;
this.dataSource = Objects.requireNonNull(dataSource, "Account DataSource required");
+ this.paidSource = paidSource;
originalCommitExecutor = new AccountGameplayAdmissionOriginalCommitExecutor(dataSource);
receiptExecutor = new AccountGameplayAdmissionOriginalAckReceiptCommitExecutor(dataSource);
}
@@ -148,7 +160,8 @@ public AccountGameplayAdmissionLeaseResponse acquire(
expectedTarget,
request.bindingGeneration(),
current.currentSources().leaseSourceFields(),
- caller.identity().expiresAtEpochSecond());
+ caller.identity().expiresAtEpochSecond(),
+ current.currentSources().sourceValidUntilMs());
return repository.beginPending(evidence);
});
@@ -182,7 +195,7 @@ public AccountGameplayAdmissionLeaseResponse finalizeLease(
// Game Session is allowed to have advanced the decision beyond PROVISIONAL after the original
// physical COMMIT, so do this narrowly fenced read before asking for a fresh provisional view.
AccountGameplayAdmissionLeaseOperation retainedBeforeRemoteReads =
- readExactForFinalization(caller, lease);
+ readExactWithCurrentCallerOnly(caller, lease);
if (retainedBeforeRemoteReads.state()
== AccountGameplayAdmissionLeaseOperation.State.COMMITTED) {
OriginalAckReceiptEvidence receipt =
@@ -205,22 +218,22 @@ public AccountGameplayAdmissionLeaseResponse finalizeLease(
null);
}
- // Both remote authorities are read after the short Account replay lookup and before the
- // original physical-COMMIT path. The decision reader returns only the actual retained
- // lease-bound PROVISIONAL decision, never request echoes.
- Evidence decision;
- PublishedRealmEvidence published;
+ // Complete the paid observation outside SQL before reading either Game Session authority.
+ // The decision or published target can change while the provider read is in flight.
+ AccountGameplayAdmissionCurrentSources.Observed observed;
try {
- decision = decisionReadClient.read(request.bindingDecisionId(), lease);
+ observed = prepareCurrentSources(caller, tenantId(lease));
+ Evidence decision = decisionReadClient.read(request.bindingDecisionId(), lease);
requireDecisionMatchesLease(decision, request.bindingDecisionId(), lease, caller, peer);
- published =
+ PublishedRealmEvidence published =
readPublishedTarget(requestId(lease), decision.candidate(), decision.targetEvidence());
if (!published.currentTarget().equals(decision.targetEvidence())) throw unavailable();
} catch (RuntimeException unavailable) {
throw unavailable();
}
- AccountGameplayAdmissionLeaseOperation beforeCommit = readExactForFinalization(caller, lease);
+ AccountGameplayAdmissionLeaseOperation beforeCommit =
+ readExactWithCurrentCallerOnly(caller, lease);
if (beforeCommit.state() == AccountGameplayAdmissionLeaseOperation.State.COMMITTED) {
OriginalAckReceiptEvidence receipt =
@@ -249,7 +262,11 @@ public AccountGameplayAdmissionLeaseResponse finalizeLease(
try {
acknowledgement =
originalCommitExecutor.executeWithCurrentSources(
- lease, request.bindingDecisionId(), workloadNamespace, caller.currentCandidate());
+ lease,
+ request.bindingDecisionId(),
+ workloadNamespace,
+ caller.currentCandidate(),
+ observed);
} catch (RuntimeException unavailable) {
throw unavailable();
}
@@ -693,7 +710,8 @@ private AccountGameplayAdmissionLeaseEvidence buildOriginalEvidence(
Target target,
BigInteger bindingGeneration,
Map currentSourceFields,
- long tokenExpiryEpochSecond) {
+ long tokenExpiryEpochSecond,
+ Long sourceValidUntilMs) {
Long databaseNow =
dsl.fetchSingle("SELECT floor(extract(epoch FROM clock_timestamp()) * 1000)::bigint")
.get(0, Long.class);
@@ -705,6 +723,7 @@ private AccountGameplayAdmissionLeaseEvidence buildOriginalEvidence(
Math.min(
Math.addExact(now, AccountGameplayAdmissionLeaseEvidence.MAX_DURATION_MILLIS),
Math.multiplyExact(tokenExpiryEpochSecond, 1000L));
+ if (sourceValidUntilMs != null) originalExpiry = Math.min(originalExpiry, sourceValidUntilMs);
} catch (ArithmeticException overflow) {
throw unavailable();
}
@@ -749,12 +768,13 @@ private T withCurrentSources(
Objects.requireNonNull(caller);
Objects.requireNonNull(tenantId);
try {
+ var observed = prepareCurrentSources(caller, tenantId);
return inWritableSerializableTransaction(dsl -> {
AccountGameplayAdmissionCurrentSources currentSources =
AccountGameplayAdmissionCurrentSources.bind(dsl, workloadNamespace);
var current =
currentSources.readCurrentPublicProductionNew(
- tenantId, caller.identity().tokenJti(), caller.currentCandidate());
+ tenantId, caller.identity().tokenJti(), caller.currentCandidate(), observed);
return operation.apply(
new CurrentAccountOperation(
dsl, current, new AccountGameplayAdmissionLeaseRepository(dsl)));
@@ -766,6 +786,21 @@ private T withCurrentSources(
}
}
+ private AccountGameplayAdmissionCurrentSources.Observed prepareCurrentSources(
+ VerifiedCaller caller, UUID tenantId) {
+ if (paidSource == null) {
+ requireNoAmbientSql();
+ return null;
+ }
+ var prepared =
+ inWritableSerializableTransaction(dsl ->
+ AccountGameplayAdmissionCurrentSources.bind(dsl, workloadNamespace)
+ .prepareCurrentPublicProductionNew(
+ tenantId, caller.identity().tokenJti(), caller.currentCandidate(), paidSource));
+ requireNoAmbientSql();
+ return prepared.observeOutsideSql();
+ }
+
/** Exact non-admitting read after fresh current caller/global Account/token SQL proof. */
private AccountGameplayAdmissionLeaseOperation readExactWithCurrentCallerOnly(
VerifiedCaller caller, AccountGameplayAdmissionLeaseEvidence lease) {
@@ -785,38 +820,6 @@ private AccountGameplayAdmissionLeaseOperation readExactWithCurrentCallerOnly(
}
}
- /**
- * Exact finalization lookup: terminal history needs only current caller proof, while PENDING
- * still requires the complete current public-production tenant source tuple in this transaction.
- */
- private AccountGameplayAdmissionLeaseOperation readExactForFinalization(
- VerifiedCaller caller, AccountGameplayAdmissionLeaseEvidence lease) {
- try {
- return inWritableSerializableTransaction(dsl -> {
- AccountGameplayAdmissionCurrentSources currentSources =
- AccountGameplayAdmissionCurrentSources.bind(dsl, workloadNamespace);
- currentSources.requireCurrentAuthenticatedCallerOnly(caller.currentCandidate());
- AccountGameplayAdmissionLeaseRepository repository =
- new AccountGameplayAdmissionLeaseRepository(dsl);
- AccountGameplayAdmissionLeaseOperation operation =
- repository
- .readExact(lease)
- .orElseThrow(AccountGameplayAdmissionLeaseOwner::unavailable);
- if (operation.state() == AccountGameplayAdmissionLeaseOperation.State.PENDING) {
- var current =
- currentSources.readCurrentPublicProductionNew(
- tenantId(lease), caller.identity().tokenJti(), caller.currentCandidate());
- current.requireMatchesOriginalLease(lease);
- }
- return operation;
- });
- } catch (StatusRuntimeException failure) {
- throw failure;
- } catch (RuntimeException unavailable) {
- throw unavailable();
- }
- }
-
/**
* Atomically records or replays the exact orphan obligation under fresh caller-only SQL proof.
*/
diff --git a/services/account-service/src/main/java/net/firedevops/firemud/accountservice/repository/AccountGameplayAdmissionOriginalCommitExecutor.java b/services/account-service/src/main/java/net/firedevops/firemud/accountservice/repository/AccountGameplayAdmissionOriginalCommitExecutor.java
index 09c5ecae8b..18ed6ab2d3 100644
--- a/services/account-service/src/main/java/net/firedevops/firemud/accountservice/repository/AccountGameplayAdmissionOriginalCommitExecutor.java
+++ b/services/account-service/src/main/java/net/firedevops/firemud/accountservice/repository/AccountGameplayAdmissionOriginalCommitExecutor.java
@@ -54,6 +54,16 @@ OriginalCommitAcknowledgement executeWithCurrentSources(
UUID decisionId,
String configuredNamespace,
CommittedCandidateVerificationData authenticatedCandidate) {
+ return executeWithCurrentSources(
+ evidence, decisionId, configuredNamespace, authenticatedCandidate, null);
+ }
+
+ OriginalCommitAcknowledgement executeWithCurrentSources(
+ AccountGameplayAdmissionLeaseEvidence evidence,
+ UUID decisionId,
+ String configuredNamespace,
+ CommittedCandidateVerificationData authenticatedCandidate,
+ AccountGameplayAdmissionCurrentSources.Observed observed) {
Objects.requireNonNull(evidence);
if (evidence.leaseKind() != AccountGameplayAdmissionLeaseEvidence.LeaseKind.NEW_BINDING
|| evidence.carrier().containsKey("expectedOldBindingGeneration")) {
@@ -64,7 +74,8 @@ OriginalCommitAcknowledgement executeWithCurrentSources(
decisionId,
new CurrentSourceScope(
Objects.requireNonNull(configuredNamespace),
- Objects.requireNonNull(authenticatedCandidate)));
+ Objects.requireNonNull(authenticatedCandidate),
+ observed));
}
private OriginalCommitAcknowledgement execute(
@@ -101,7 +112,8 @@ private OriginalCommitAcknowledgement execute(
.readCurrentPublicProductionNew(
UUID.fromString((String) scope.get("tenantId")),
UUID.fromString((String) token.get("tokenJti")),
- currentSources.authenticatedCandidate());
+ currentSources.authenticatedCandidate(),
+ currentSources.observed());
current.requireMatchesOriginalLease(evidence);
}
var repository = new AccountGameplayAdmissionLeaseRepository(exactDsl);
@@ -166,7 +178,9 @@ public String toString() {
}
private record CurrentSourceScope(
- String configuredNamespace, CommittedCandidateVerificationData authenticatedCandidate) {}
+ String configuredNamespace,
+ CommittedCandidateVerificationData authenticatedCandidate,
+ AccountGameplayAdmissionCurrentSources.Observed observed) {}
private record OriginalBinding(
AccountGameplayAdmissionLeaseEvidence evidence, UUID decisionId, String finalizationXid) {}
diff --git a/services/account-service/src/main/java/net/firedevops/firemud/accountservice/repository/AccountGameplayAdmissionPaidSource.java b/services/account-service/src/main/java/net/firedevops/firemud/accountservice/repository/AccountGameplayAdmissionPaidSource.java
new file mode 100644
index 0000000000..7b6b9e63c4
--- /dev/null
+++ b/services/account-service/src/main/java/net/firedevops/firemud/accountservice/repository/AccountGameplayAdmissionPaidSource.java
@@ -0,0 +1,180 @@
+package net.firedevops.firemud.accountservice.repository;
+
+import java.time.Clock;
+import java.time.Duration;
+import java.time.Instant;
+import java.util.Objects;
+import java.util.UUID;
+import net.firedevops.firemud.accountservice.client.StripeHostingSubscriptionObserver;
+import net.firedevops.firemud.accountservice.repository.AccountHostingSubscriptionLifecycleRepository.ReadFence;
+import net.firedevops.firemud.accountservice.repository.AccountHostingSubscriptionLifecycleRepository.ReconciliationLimits;
+import net.firedevops.firemud.common.grpc.GrpcPeerIdentity;
+import org.jooq.DSLContext;
+import org.jooq.Record;
+import org.springframework.transaction.support.TransactionSynchronizationManager;
+import tools.jackson.core.StreamReadFeature;
+import tools.jackson.databind.DeserializationFeature;
+import tools.jackson.databind.JsonNode;
+import tools.jackson.databind.json.JsonMapper;
+
+/**
+ * Explicit, unregistered paid-source composition for Account's original NEW lease owner.
+ *
+ * Only the genuine hosting owner reads a current receipt. Every SQL phase constructs that owner
+ * on the caller's exact enlisted DSLContext. The opaque preparation and observation retain their
+ * originating composition; neither a public receipt record nor raw provider data is an input.
+ * Provider observation runs only outside SQL. This component registers no route or provider write.
+ */
+public final class AccountGameplayAdmissionPaidSource {
+ private static final Duration FRESHNESS_LIMIT = Duration.ofSeconds(15);
+ private static final JsonMapper BILLING_HINT_JSON =
+ JsonMapper.builder()
+ .enable(StreamReadFeature.STRICT_DUPLICATE_DETECTION)
+ .enable(DeserializationFeature.FAIL_ON_TRAILING_TOKENS)
+ .build();
+ private static final String BILLING_SCHEMA_VERSION = "account-hosting-subscription-event/v1";
+ private final AccountHostingPlanCatalog plans;
+ private final Clock clock;
+ private final Duration maxClockSkew;
+ private final ReconciliationLimits limits;
+ private final AccountHostingSubscriptionLifecyclePolicy policy;
+ private final StripeHostingSubscriptionObserver observer;
+ private final String namespace;
+ private final boolean livemode;
+
+ public AccountGameplayAdmissionPaidSource(
+ AccountHostingPlanCatalog plans,
+ Clock clock,
+ Duration maxClockSkew,
+ ReconciliationLimits limits,
+ AccountHostingSubscriptionLifecyclePolicy policy,
+ StripeHostingSubscriptionObserver observer,
+ String namespace,
+ boolean livemode) {
+ this.plans = Objects.requireNonNull(plans);
+ this.clock = Objects.requireNonNull(clock);
+ if (maxClockSkew == null
+ || maxClockSkew.isNegative()
+ || maxClockSkew.compareTo(FRESHNESS_LIMIT) >= 0) {
+ throw new IllegalArgumentException("Entitlement clock skew must be in [0, 15 seconds)");
+ }
+ this.maxClockSkew = maxClockSkew;
+ this.limits = Objects.requireNonNull(limits);
+ this.policy = Objects.requireNonNull(policy);
+ this.observer = Objects.requireNonNull(observer);
+ if (!GrpcPeerIdentity.isValidNamespace(namespace)) {
+ throw new IllegalArgumentException("Canonical Account workload namespace required");
+ }
+ this.namespace = namespace;
+ this.livemode = livemode;
+ }
+
+ Preparation prepare(DSLContext exactDsl, String expectedNamespace, UUID tenantId) {
+ requireNamespace(expectedNamespace);
+ return new Preparation(this, reader(exactDsl).prepareCurrentRead(tenantId));
+ }
+
+ /**
+ * Unlocked routing hint from the exact current tenant source head. The paid lifecycle owner locks
+ * its sources first, then the locked selector validates the complete current envelope.
+ */
+ boolean hasCurrentPaidSourceCandidate(
+ DSLContext exactDsl, String expectedNamespace, UUID tenantId) {
+ requireNamespace(expectedNamespace);
+ Record source =
+ exactDsl.fetchOne(
+ "SELECT e.payload "
+ + "FROM account_tenant_authority_source_records h "
+ + "JOIN account_tenant_entitlement_outbox_events e "
+ + "ON e.tenant_uuid = h.tenant_uuid "
+ + "AND e.tenant_billing_sequence = h.tenant_billing_sequence "
+ + "AND e.request_id = h.last_request_id "
+ + "AND e.event_id = h.tenant_billing_event_id "
+ + "AND e.event_digest = h.tenant_billing_event_digest "
+ + "WHERE h.tenant_uuid = ?",
+ tenantId);
+ if (source == null) return false;
+ byte[] payload = source.get("payload", byte[].class);
+ if (payload == null || payload.length == 0 || payload.length > 32768) return false;
+ try {
+ JsonNode envelope = BILLING_HINT_JSON.readTree(payload);
+ return envelope != null
+ && BILLING_SCHEMA_VERSION.equals(envelope.path("schemaVersion").asText());
+ } catch (RuntimeException unreadableHint) {
+ return false;
+ }
+ }
+
+ Observation observe(Preparation preparation) {
+ if (preparation == null
+ || preparation.owner != this
+ || TransactionSynchronizationManager.isActualTransactionActive()
+ || TransactionSynchronizationManager.isSynchronizationActive()) {
+ throw new IllegalStateException("Paid NEW observation requires no ambient Account SQL");
+ }
+ return new Observation(preparation, observer.observe(preparation.fence.binding()));
+ }
+
+ AccountHostingSubscriptionCurrentReceipt readCurrent(
+ DSLContext exactDsl, String expectedNamespace, Observation observation) {
+ requireNamespace(expectedNamespace);
+ if (observation == null || observation.preparation.owner != this) {
+ throw new IllegalStateException("Original paid NEW source observation required");
+ }
+ var receipt = reader(exactDsl).readCurrent(observation.preparation.fence, observation.result);
+ requireReceiptStillCurrent(receipt);
+ return receipt;
+ }
+
+ Instant requireReceiptStillCurrent(AccountHostingSubscriptionCurrentReceipt receipt) {
+ Instant now = clock.instant();
+ Instant evaluatedAt = receipt.evaluatedAt();
+ Instant validUntil = receipt.validUntil();
+ if (evaluatedAt == null || validUntil == null || evaluatedAt.isAfter(now.plus(maxClockSkew))) {
+ throw new IllegalStateException("Current paid NEW source has expired");
+ }
+ Instant freshUntil = evaluatedAt.plus(FRESHNESS_LIMIT.minus(maxClockSkew));
+ Instant deadline = freshUntil.isBefore(validUntil) ? freshUntil : validUntil;
+ if (!now.isBefore(deadline)) {
+ throw new IllegalStateException("Current paid NEW source has expired");
+ }
+ return deadline;
+ }
+
+ private AccountHostingSubscriptionLifecycleRepository reader(DSLContext exactDsl) {
+ return new AccountHostingSubscriptionLifecycleRepository(
+ exactDsl,
+ new AccountSubscriptionIntentRepository(exactDsl, plans),
+ clock,
+ limits,
+ policy,
+ namespace,
+ livemode);
+ }
+
+ private void requireNamespace(String expectedNamespace) {
+ if (!namespace.equals(expectedNamespace)) {
+ throw new IllegalStateException("Exact Account paid-source namespace required");
+ }
+ }
+
+ static final class Preparation {
+ private final AccountGameplayAdmissionPaidSource owner;
+ private final ReadFence fence;
+
+ private Preparation(AccountGameplayAdmissionPaidSource owner, ReadFence fence) {
+ this.owner = owner;
+ this.fence = Objects.requireNonNull(fence);
+ }
+ }
+
+ static final class Observation {
+ private final Preparation preparation;
+ private final StripeHostingSubscriptionObserver.Result result;
+
+ private Observation(Preparation preparation, StripeHostingSubscriptionObserver.Result result) {
+ this.preparation = preparation;
+ this.result = Objects.requireNonNull(result);
+ }
+ }
+}
diff --git a/services/account-service/src/main/java/net/firedevops/firemud/accountservice/repository/AccountHostingSubscriptionLifecycleRepository.java b/services/account-service/src/main/java/net/firedevops/firemud/accountservice/repository/AccountHostingSubscriptionLifecycleRepository.java
index 72fe481d6a..b4232b5753 100644
--- a/services/account-service/src/main/java/net/firedevops/firemud/accountservice/repository/AccountHostingSubscriptionLifecycleRepository.java
+++ b/services/account-service/src/main/java/net/firedevops/firemud/accountservice/repository/AccountHostingSubscriptionLifecycleRepository.java
@@ -1394,10 +1394,11 @@ public AccountHostingSubscriptionCurrentReceipt readCurrent(
throw new FenceRejectedException(
"ENTITLEMENT_UNAVAILABLE: provider facts differ from the committed receipt");
}
- Instant evaluatedAt = now();
+ Instant preciseEvaluatedAt = clock.instant();
+ Instant evaluatedAt = preciseEvaluatedAt.truncatedTo(ChronoUnit.MICROS);
var decision =
retainedPolicy(operation)
- .evaluate(observed, evaluatedAt, nullableInstant(receipt, "past_due_since"));
+ .evaluate(observed, preciseEvaluatedAt, nullableInstant(receipt, "past_due_since"));
if (!decision.resolved() || !decision.status().storageValue().equals(current.status())) {
throw new FenceRejectedException(
"ENTITLEMENT_UNAVAILABLE: lifecycle/period requires reconciliation");
diff --git a/services/account-service/src/main/java/net/firedevops/firemud/accountservice/repository/AccountOriginalNewBoundGameplayCredentialOwner.java b/services/account-service/src/main/java/net/firedevops/firemud/accountservice/repository/AccountOriginalNewBoundGameplayCredentialOwner.java
index 7e7357a63f..55cc5fb5a5 100644
--- a/services/account-service/src/main/java/net/firedevops/firemud/accountservice/repository/AccountOriginalNewBoundGameplayCredentialOwner.java
+++ b/services/account-service/src/main/java/net/firedevops/firemud/accountservice/repository/AccountOriginalNewBoundGameplayCredentialOwner.java
@@ -81,6 +81,7 @@ public final class AccountOriginalNewBoundGameplayCredentialOwner {
private final AccountGameplayDelegationTokenRegistry tokenRegistry;
private final AccountResponseEnvelopeCryptography responseCryptography;
private final AccountOriginalNewFinalAdmissionReadClient finalAdmissionReadClient;
+ private final AccountGameplayAdmissionPaidSource paidSource;
private final Clock clock;
private final SecureRandom secureRandom;
@@ -101,6 +102,7 @@ public AccountOriginalNewBoundGameplayCredentialOwner(
responseCryptography,
clock,
null,
+ null,
new SecureRandom());
}
@@ -123,6 +125,31 @@ public AccountOriginalNewBoundGameplayCredentialOwner(
responseCryptography,
clock,
Objects.requireNonNull(finalAdmissionReadClient),
+ null,
+ new SecureRandom());
+ }
+
+ /** Explicit paid-source observation composition; absent final reader keeps confirmation held. */
+ public AccountOriginalNewBoundGameplayCredentialOwner(
+ DataSource dataSource,
+ String workloadNamespace,
+ AccountGameplayAdmissionCallerVerifier callerVerifier,
+ AccountGameplayDelegationSigner signer,
+ AccountGameplayDelegationTokenRegistry tokenRegistry,
+ AccountResponseEnvelopeCryptography responseCryptography,
+ Clock clock,
+ AccountOriginalNewFinalAdmissionReadClient finalAdmissionReadClient,
+ AccountGameplayAdmissionPaidSource paidSource) {
+ this(
+ dataSource,
+ workloadNamespace,
+ callerVerifier,
+ signer,
+ tokenRegistry,
+ responseCryptography,
+ clock,
+ finalAdmissionReadClient,
+ Objects.requireNonNull(paidSource),
new SecureRandom());
}
@@ -144,6 +171,7 @@ public AccountOriginalNewBoundGameplayCredentialOwner(
responseCryptography,
clock,
null,
+ null,
secureRandom);
}
@@ -156,6 +184,7 @@ private AccountOriginalNewBoundGameplayCredentialOwner(
AccountResponseEnvelopeCryptography responseCryptography,
Clock clock,
AccountOriginalNewFinalAdmissionReadClient finalAdmissionReadClient,
+ AccountGameplayAdmissionPaidSource paidSource,
SecureRandom secureRandom) {
this.dataSource = Objects.requireNonNull(dataSource, "Account DataSource is required");
if (!GrpcPeerIdentity.isValidNamespace(workloadNamespace)) {
@@ -168,6 +197,7 @@ private AccountOriginalNewBoundGameplayCredentialOwner(
this.tokenRegistry = Objects.requireNonNull(tokenRegistry);
this.responseCryptography = Objects.requireNonNull(responseCryptography);
this.finalAdmissionReadClient = finalAdmissionReadClient;
+ this.paidSource = paidSource;
this.clock = Objects.requireNonNull(clock);
this.secureRandom = Objects.requireNonNull(secureRandom);
}
@@ -246,14 +276,20 @@ private IssuedOriginalNew issueChecked(
throw unavailable();
}
final Genesis exactGenesisForCommit = genesis;
+ AccountGameplayAdmissionCurrentSources.Observed currentObservation =
+ prepareCurrentOriginalSource(currentCaller, requestedLease);
Genesis committed =
inWritableSerializableTransaction(dsl -> {
- SourceRead current = readCurrentOriginalSource(dsl, currentCaller, requestedLease);
+ SourceRead current =
+ readCurrentOriginalSource(dsl, currentCaller, requestedLease, currentObservation);
requireSameOriginalOperation(initial.operation(), current.operation());
AccountOriginalNewBoundGameplayIssuanceRepository issuance =
new AccountOriginalNewBoundGameplayIssuanceRepository(dsl);
Genesis stored = issuance.readByLease(leaseId(requestedLease));
requireSameGenesisIdentity(exactGenesisForCommit, stored);
+ if (clock.instant().getEpochSecond() >= caller.identity().expiresAtEpochSecond()) {
+ throw unavailable();
+ }
Genesis committedResult = issuance.commit(stored, receiptDigest);
var fenceRepository = new AccountGameplayTokenIdentityFenceRepository(dsl);
var tokenIdentity =
@@ -357,9 +393,12 @@ public OriginalAdmissionConfirmation confirmOriginalFinalAdmission(
AccountGameplayAdmissionOriginalAckReceipt receipt =
receiptExecutor.read(requestedLease, beforeRead.operation().bindingDecisionId());
requireExactReceipt(receipt, beforeRead.operation(), requestedLease);
+ AccountGameplayAdmissionCurrentSources.Observed beforeGenesisObservation =
+ prepareCurrentOriginalSource(caller, requestedLease);
Genesis beforeGenesis =
inWritableSerializableTransaction(dsl -> {
- SourceRead current = readCurrentOriginalSource(dsl, caller, requestedLease);
+ SourceRead current =
+ readCurrentOriginalSource(dsl, caller, requestedLease, beforeGenesisObservation);
requireSameOriginalOperation(beforeRead.operation(), current.operation());
Genesis stored =
new AccountOriginalNewBoundGameplayIssuanceRepository(dsl)
@@ -404,9 +443,12 @@ public OriginalAdmissionConfirmation confirmOriginalFinalAdmission(
.hasSameOwnerEvidence(caller.currentCandidate(), currentCaller.currentCandidate())) {
throw unavailable();
}
+ AccountGameplayAdmissionCurrentSources.Observed recoveryObservation =
+ prepareCurrentOriginalSource(currentCaller, requestedLease);
ConfirmedSource recovered =
inWritableSerializableTransaction(dsl -> {
- SourceRead current = readCurrentOriginalSource(dsl, currentCaller, requestedLease);
+ SourceRead current =
+ readCurrentOriginalSource(dsl, currentCaller, requestedLease, recoveryObservation);
requireSameOriginalOperation(beforeRead.operation(), current.operation());
AccountGameplayAdmissionOriginalAckReceipt durableReceipt =
new AccountGameplayAdmissionOriginalAckReceiptRepository(
@@ -451,10 +493,7 @@ dsl, new AccountGameplayAdmissionLeaseRepository(dsl))
throw unavailable();
}
if (!expected.equals(finalReadback.anchors())) throw unavailable();
- long nowMillis = clock.millis();
- if (nowMillis <= 0L
- || finalReadback.admissionAtMillis() > nowMillis
- || nowMillis >= finalReadback.continuityExpiresAtMillis()) throw unavailable();
+ requireCurrentFinalReadback(finalReadback);
VerifiedCaller beforeActivationCaller = verifyCaller(presentedInitialGsACompactJwt, peer);
if (!AccountGameplayDelegationIssuanceRepository.CommittedCandidateVerificationData
@@ -463,15 +502,21 @@ dsl, new AccountGameplayAdmissionLeaseRepository(dsl))
throw unavailable();
}
- if (committedCapacityRequest != null) {
+ if (committedCapacityRequest != null || beforeRead.paidHosting()) {
+ AccountGameplayAdmissionCurrentSources.Observed beforeActivationObservation =
+ prepareCurrentOriginalSource(beforeActivationCaller, requestedLease);
inWritableSerializableTransaction(dsl -> {
- SourceRead current = readCurrentOriginalSource(dsl, beforeActivationCaller, requestedLease);
+ SourceRead current =
+ readCurrentOriginalSource(
+ dsl, beforeActivationCaller, requestedLease, beforeActivationObservation);
requireSameOriginalOperation(beforeRead.operation(), current.operation());
- return readCommittedCapacity(dsl, current.operation(), peer, committedCapacityRequest);
+ readCommittedCapacity(dsl, current.operation(), peer, committedCapacityRequest);
+ return current;
});
if (Context.current().isCancelled()) throw unavailable();
}
+ requireCurrentFinalReadback(finalReadback);
// Activation is Account-owned and happens only after the authenticated GS readback exists.
// If its reply is lost, the Redis CAS accepts only the same immutable active projection.
AccountGameplayDelegationRedisClient.OriginalNewActivationReadback activation =
@@ -491,9 +536,13 @@ dsl, new AccountGameplayAdmissionLeaseRepository(dsl))
stringObjectMap(beforeGenesis.authorityTupleCanonicalBytes()),
stringStringMap(beforeGenesis.membershipVersionCanonicalBytes()));
String confirmationDigest = confirmationDigest(finalReadback, activation);
+ AccountGameplayAdmissionCurrentSources.Observed confirmationObservation =
+ prepareCurrentOriginalSource(currentCaller, requestedLease);
ConfirmedSource confirmed =
inWritableSerializableTransaction(dsl -> {
- SourceRead current = readCurrentOriginalSource(dsl, currentCaller, requestedLease);
+ SourceRead current =
+ readCurrentOriginalSource(
+ dsl, currentCaller, requestedLease, confirmationObservation);
requireSameOriginalOperation(beforeRead.operation(), current.operation());
AccountGameplayAdmissionOriginalAckReceipt durableReceipt =
new AccountGameplayAdmissionOriginalAckReceiptRepository(
@@ -510,17 +559,19 @@ dsl, new AccountGameplayAdmissionLeaseRepository(dsl))
new AccountGameplayTokenIdentityFenceRepository(dsl).requireActiveReadback(tokenIdentity);
var capacity =
readCommittedCapacity(dsl, current.operation(), peer, committedCapacityRequest);
- return new ConfirmedSource(
+ requireCurrentFinalReadback(finalReadback);
+ Genesis written =
issuance.confirmFinalAdmission(
exact,
finalReadback.admissionAtMillis(),
finalReadback.continuityExpiresAtMillis(),
- confirmationDigest),
- capacity);
+ confirmationDigest);
+ requireCurrentFinalReadback(finalReadback);
+ return new ConfirmedSource(written, capacity);
});
tokenRegistry.requireExactOriginalNewActiveRecord(confirmed.genesis());
+ requireCurrentFinalReadback(finalReadback);
if (!confirmationDigest.equals(confirmed.genesis().confirmationReadbackSha256())
- || clock.millis() >= finalReadback.continuityExpiresAtMillis()
|| (committedCapacityRequest != null && Context.current().isCancelled())) {
throw unavailable();
}
@@ -615,6 +666,13 @@ private static void requireActivationMatches(
|| activation.replicaAofCount() < 1L) throw unavailable();
}
+ private void requireCurrentFinalReadback(AuthenticatedFinalAdmissionReadback readback) {
+ long now = clock.millis();
+ if (now <= 0L
+ || readback.admissionAtMillis() > now
+ || now >= readback.continuityExpiresAtMillis()) throw unavailable();
+ }
+
private static String confirmationDigest(
AuthenticatedFinalAdmissionReadback finalReadback,
AccountGameplayDelegationRedisClient.OriginalNewActivationReadback activation) {
@@ -688,8 +746,10 @@ private Genesis signAndPersistCandidate(
byte[] exactRecord = recordBytes.clone();
byte[] exactEnvelope = envelopeBytes.clone();
try {
+ AccountGameplayAdmissionCurrentSources.Observed currentObservation =
+ prepareCurrentOriginalSource(caller, lease);
return inWritableSerializableTransaction(dsl -> {
- SourceRead current = readCurrentOriginalSource(dsl, caller, lease);
+ SourceRead current = readCurrentOriginalSource(dsl, caller, lease, currentObservation);
if (current.operation().state() != State.COMMITTED
|| !current.operation().bindingDecisionId().equals(receipt.bindingDecisionId())) {
throw unavailable();
@@ -728,37 +788,9 @@ private OriginalNewCredential openCommittedResult(
AccountGameplayAdmissionLeaseEvidence lease,
AccountGameplayAdmissionOriginalAckReceipt receipt,
Genesis expectedGenesis) {
- SourceRead source = readCurrentOriginalSource(caller, lease);
- requireExactReceipt(receipt, source.operation(), lease);
- Genesis committed =
- inWritableSerializableTransaction(dsl -> {
- SourceRead current = readCurrentOriginalSource(dsl, caller, lease);
- requireSameOriginalOperation(source.operation(), current.operation());
- var issuance = new AccountOriginalNewBoundGameplayIssuanceRepository(dsl);
- Genesis exact = issuance.readByLease(leaseId(lease));
- requireSameGenesisIdentity(expectedGenesis, exact);
- if (exact.status()
- != AccountOriginalNewBoundGameplayIssuanceRepository.Status.COMMITTED) {
- throw unavailable();
- }
- var tokenIdentity =
- new TokenIdentity(
- exact.accountId(),
- exact.lineageId(),
- exact.requestId(),
- exact.tokenHash(),
- exact.tokenJti(),
- exact.notBeforeEpochSecond(),
- exact.tokenGeneration(),
- exact.issuanceFence(),
- SourceKind.ORIGINAL_NEW);
- new AccountGameplayTokenIdentityFenceRepository(dsl).requireActiveReadback(tokenIdentity);
- return exact;
- });
-
- requireCommittedRegistryProjection(committed);
-
- return openFrozenCredentialResult(lease, receipt, source, committed);
+ CredentialOpen opened = readCredentialForOpen(caller, lease, receipt, expectedGenesis);
+ requireCommittedRegistryProjection(opened.genesis());
+ return openFrozenCredentialResult(lease, receipt, opened.source(), opened.genesis());
}
/**
@@ -772,25 +804,33 @@ private OriginalNewCredential openFrozenCredentialForFinalAdmissionVerification(
AccountGameplayAdmissionLeaseEvidence lease,
AccountGameplayAdmissionOriginalAckReceipt receipt,
Genesis expectedGenesis) {
- SourceRead source = readCurrentOriginalSource(caller, lease);
- requireExactReceipt(receipt, source.operation(), lease);
- Genesis committed =
- inWritableSerializableTransaction(dsl -> {
- SourceRead current = readCurrentOriginalSource(dsl, caller, lease);
- requireSameOriginalOperation(source.operation(), current.operation());
- var issuance = new AccountOriginalNewBoundGameplayIssuanceRepository(dsl);
- Genesis exact = issuance.readByLease(leaseId(lease));
- requireSameGenesisIdentity(expectedGenesis, exact);
- if (exact.status()
- != AccountOriginalNewBoundGameplayIssuanceRepository.Status.COMMITTED) {
- throw unavailable();
- }
- new AccountGameplayTokenIdentityFenceRepository(dsl)
- .requireActiveReadback(originalNewIdentity(exact));
- return exact;
- });
+ CredentialOpen opened = readCredentialForOpen(caller, lease, receipt, expectedGenesis);
+ return openFrozenCredentialResult(lease, receipt, opened.source(), opened.genesis());
+ }
- return openFrozenCredentialResult(lease, receipt, source, committed);
+ private CredentialOpen readCredentialForOpen(
+ VerifiedCaller caller,
+ AccountGameplayAdmissionLeaseEvidence lease,
+ AccountGameplayAdmissionOriginalAckReceipt receipt,
+ Genesis expectedGenesis) {
+ AccountGameplayAdmissionCurrentSources.Observed currentObservation =
+ prepareCurrentOriginalSource(caller, lease);
+ return inWritableSerializableTransaction(dsl -> {
+ SourceRead current = readCurrentOriginalSource(dsl, caller, lease, currentObservation);
+ // The owner already proved the immutable ACK's independent durability. Bind that exact
+ // proof and the token identity fence to the same fresh source used to verify the credential.
+ requireExactReceipt(receipt, current.operation(), lease);
+ requireSameOriginalOperation(receipt.operation(), current.operation());
+ var issuance = new AccountOriginalNewBoundGameplayIssuanceRepository(dsl);
+ Genesis exact = issuance.readByLease(leaseId(lease));
+ requireSameGenesisIdentity(expectedGenesis, exact);
+ if (exact.status() != AccountOriginalNewBoundGameplayIssuanceRepository.Status.COMMITTED) {
+ throw unavailable();
+ }
+ new AccountGameplayTokenIdentityFenceRepository(dsl)
+ .requireActiveReadback(originalNewIdentity(exact));
+ return new CredentialOpen(current, exact);
+ });
}
private OriginalNewCredential openFrozenCredentialResult(
@@ -847,23 +887,51 @@ private OriginalNewCredential openFrozenCredentialResult(
private SourceRead readCurrentOriginalSource(
VerifiedCaller caller, AccountGameplayAdmissionLeaseEvidence lease) {
- return inWritableSerializableTransaction(dsl -> readCurrentOriginalSource(dsl, caller, lease));
+ AccountGameplayAdmissionCurrentSources.Observed observed =
+ prepareCurrentOriginalSource(caller, lease);
+ return inWritableSerializableTransaction(
+ dsl -> readCurrentOriginalSource(dsl, caller, lease, observed));
+ }
+
+ private AccountGameplayAdmissionCurrentSources.Observed prepareCurrentOriginalSource(
+ VerifiedCaller caller, AccountGameplayAdmissionLeaseEvidence lease) {
+ UUID targetTenantId = tenantId(lease);
+ if (paidSource == null) {
+ requireNoAmbientSql();
+ return null;
+ }
+ AccountGameplayAdmissionCurrentSources.Prepared prepared =
+ inWritableSerializableTransaction(dsl ->
+ AccountGameplayAdmissionCurrentSources.bind(dsl, workloadNamespace)
+ .prepareCurrentPublicProductionNew(
+ targetTenantId,
+ caller.identity().tokenJti(),
+ caller.currentCandidate(),
+ paidSource));
+ requireNoAmbientSql();
+ return prepared.observeOutsideSql();
}
private SourceRead readCurrentOriginalSource(
- DSLContext dsl, VerifiedCaller caller, AccountGameplayAdmissionLeaseEvidence lease) {
+ DSLContext dsl,
+ VerifiedCaller caller,
+ AccountGameplayAdmissionLeaseEvidence lease,
+ AccountGameplayAdmissionCurrentSources.Observed observed) {
UUID tenantId = tenantId(lease);
AccountGameplayAdmissionCurrentSources sourceReader =
AccountGameplayAdmissionCurrentSources.bind(dsl, workloadNamespace);
var current =
sourceReader.readCurrentPublicProductionNew(
- tenantId, caller.identity().tokenJti(), caller.currentCandidate());
+ tenantId, caller.identity().tokenJti(), caller.currentCandidate(), observed);
current.requireMatchesOriginalLease(lease);
AccountGameplayAdmissionLeaseOperation operation =
new AccountGameplayAdmissionLeaseRepository(dsl)
.readExact(lease)
.orElseThrow(AccountOriginalNewBoundGameplayCredentialOwner::unavailable);
- return new SourceRead(operation, current.currentCommittedCandidate().authoritySnapshot());
+ return new SourceRead(
+ operation,
+ current.currentCommittedCandidate().authoritySnapshot(),
+ current.sourceValidUntilMs() != null);
}
private Binding responseBinding(
@@ -1205,13 +1273,17 @@ private static IllegalStateException unavailable() {
}
private record SourceRead(
- AccountGameplayAdmissionLeaseOperation operation, AccountAuthoritySnapshot accountAuthority) {
+ AccountGameplayAdmissionLeaseOperation operation,
+ AccountAuthoritySnapshot accountAuthority,
+ boolean paidHosting) {
SourceRead {
Objects.requireNonNull(operation);
Objects.requireNonNull(accountAuthority);
}
}
+ private record CredentialOpen(SourceRead source, Genesis genesis) {}
+
private record OpenedProtectedResult(byte[] compactJwtBytes, byte[] handleBytes) {}
private record ConfirmedSource(Genesis genesis, TenantCapacityAdmission.Result capacityResult) {}
diff --git a/services/account-service/src/main/java/net/firedevops/firemud/accountservice/repository/AccountRepository.java b/services/account-service/src/main/java/net/firedevops/firemud/accountservice/repository/AccountRepository.java
index f86cbaed5f..60efdc0273 100644
--- a/services/account-service/src/main/java/net/firedevops/firemud/accountservice/repository/AccountRepository.java
+++ b/services/account-service/src/main/java/net/firedevops/firemud/accountservice/repository/AccountRepository.java
@@ -144,6 +144,13 @@ public List findByAccountUuids(List accountUuids) {
return List.copyOf(accounts);
}
+ /** Uses the same caller/payer Account lock order as paid NEW before JOIN source reads. */
+ @Transactional(propagation = Propagation.MANDATORY)
+ public void lockCanonicalJoinAccounts(UUID tenantId, UUID callerAccountId) {
+ AccountGameplayAdmissionCurrentSources.lockRequiredAccountsBeforeTenantSources(
+ dsl, tenantId, callerAccountId);
+ }
+
/** Locks one exact Account UUID inside a writable owner transaction. */
@Transactional(propagation = Propagation.MANDATORY)
public Optional findByAccountUuidForUpdate(UUID accountUuid) {
diff --git a/services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/impl/AccountServiceImpl.java b/services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/impl/AccountServiceImpl.java
index 03536be46a..d34fa114c0 100644
--- a/services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/impl/AccountServiceImpl.java
+++ b/services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/impl/AccountServiceImpl.java
@@ -595,12 +595,25 @@ private CanonicalJoinPreparation prepareCanonicalJoin(
String requestId,
String callerBinding) {
// Retain the exact policy-independent intent before any fallible source/provider work.
- joinTransactionTemplate.executeWithoutResult(status -> {
- lockCanonicalScopeAccount(scope);
- accountJoinOperationRepository.insertCanonicalIntent(requestId, scope, callerBinding);
- });
+ var retainedFailure =
+ Objects.requireNonNull(
+ joinTransactionTemplate.execute(status -> {
+ lockCanonicalScopeAccount(scope);
+ if (accountJoinOperationRepository.insertCanonicalIntent(
+ requestId, scope, callerBinding)) {
+ return Optional.empty();
+ }
+ return accountJoinOperationRepository
+ .findCanonicalEvidenceByRequestId(requestId)
+ .filter(operation -> "FAILED".equals(operation.status()));
+ }));
+ if (retainedFailure.isPresent()) {
+ return new CanonicalJoinPreparation(retainedFailure.orElseThrow(), null, null, null);
+ }
return Objects.requireNonNull(
joinTransactionTemplate.execute(status -> {
+ // Lock the caller and distinct payer before source selection or a hosting read.
+ accountRepository.lockCanonicalJoinAccounts(scope.tenantId(), scope.accountId());
lockCanonicalScopeAccount(scope);
CanonicalJoinOperationEvidence operation =
accountJoinOperationRepository
@@ -634,6 +647,11 @@ private CanonicalJoinResult commitCanonicalJoin(
StripeHostingSubscriptionObserver.Result observation) {
return Objects.requireNonNull(
joinTransactionTemplate.execute(status -> {
+ boolean retainedFailure = "FAILED".equals(prepared.operation().status());
+ // Only source-dependent work needs the sorted caller and payer locks.
+ if (!retainedFailure) {
+ accountRepository.lockCanonicalJoinAccounts(scope.tenantId(), scope.accountId());
+ }
lockCanonicalScopeAccount(scope);
requireCanonicalScopeFresh(consumers, scope);
CanonicalJoinOperationEvidence lockedOperation =
@@ -648,6 +666,10 @@ private CanonicalJoinResult commitCanonicalJoin(
requestId, scope, callerBinding, lockedOperation.outcome());
return new CanonicalJoinResult(retained.outcome(), null, false, true);
}
+ if (retainedFailure) {
+ throw new AccountJoinOperationRepository.CanonicalJoinOperationConflictException(
+ "Retained JOIN failure changed before replay");
+ }
SourceSelection current =
consumers.tenantSources().readCurrentSourceSelection(scope.tenantId());
if (current.kind() != prepared.source().kind()
@@ -769,6 +791,7 @@ private BootstrapCharacterAuthority prepareBootstrapCharacterAuthority(
CanonicalScopeConsumers consumers, CanonicalJoinScopeV2 scope) {
return Objects.requireNonNull(
joinTransactionTemplate.execute(status -> {
+ accountRepository.lockCanonicalJoinAccounts(scope.tenantId(), scope.accountId());
lockCanonicalScopeAccount(scope);
requireCanonicalScopeFresh(consumers, scope);
var membership = readBootstrapCharacterMembership(scope);
@@ -816,6 +839,7 @@ private void requireBootstrapCharacterAuthority(
BootstrapCharacterAuthority prepared,
StripeHostingSubscriptionObserver.Result observation) {
joinTransactionTemplate.executeWithoutResult(status -> {
+ accountRepository.lockCanonicalJoinAccounts(scope.tenantId(), scope.accountId());
lockCanonicalScopeAccount(scope);
requireCanonicalScopeFresh(consumers, scope);
var membership = readBootstrapCharacterMembership(scope);
diff --git a/services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/BootstrapCharacterUuidEntityCompositionIntegrationTest.java b/services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/BootstrapCharacterUuidEntityCompositionIntegrationTest.java
index 547f5b69bd..561dc1a1cd 100644
--- a/services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/BootstrapCharacterUuidEntityCompositionIntegrationTest.java
+++ b/services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/BootstrapCharacterUuidEntityCompositionIntegrationTest.java
@@ -2,6 +2,7 @@
import static org.assertj.core.api.Assertions.assertThat;
+import integration.net.firedevops.firemud.accountservice.repository.CanonicalHostingSubscriptionTestFixture;
import io.grpc.ManagedChannel;
import io.grpc.Server;
import io.grpc.ServerInterceptors;
@@ -32,8 +33,11 @@
import java.util.List;
import java.util.Map;
import java.util.UUID;
+import java.util.concurrent.CountDownLatch;
+import java.util.concurrent.Executors;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.atomic.AtomicInteger;
+import javax.sql.DataSource;
import net.firedevops.firemud.accountservice.client.AccountBootstrapRosterReadClient;
import net.firedevops.firemud.accountservice.client.CanonicalGameplayAdmissionDecisionReadClient;
import net.firedevops.firemud.accountservice.client.LoggingAdminClient;
@@ -127,6 +131,7 @@
import org.springframework.test.context.DynamicPropertySource;
import org.springframework.test.context.bean.override.mockito.MockitoBean;
import org.springframework.transaction.PlatformTransactionManager;
+import org.springframework.transaction.support.TransactionSynchronizationManager;
import org.springframework.transaction.support.TransactionTemplate;
import org.testcontainers.containers.GenericContainer;
import org.testcontainers.containers.PostgreSQLContainer;
@@ -261,8 +266,8 @@ void bootstrapCharactersUseCanonicalOwnersAndPersistedLevelsAcrossHttpAndTwoMtls
TestAccount ownerB = registerAccount("uuid-owner-b-" + suffix);
assertThat(ownerA.accountUuid()).isNotEqualTo(ownerB.accountUuid());
configureCanonicalAccountOwners();
- initializeMemberAuthority(ownerA);
- initializeMemberAuthority(ownerB);
+ initializeMemberAuthority(ownerA, SOURCE.target().tenantUuid());
+ initializeMemberAuthority(ownerB, SOURCE.target().tenantUuid());
String tokenA = issuePlayerBootstrap(ownerA);
String tokenB = issuePlayerBootstrap(ownerB);
String scopeA = discoverConnectScope(ownerA, tokenA);
@@ -385,36 +390,135 @@ void retainedNumericSelectorIsRefusedByOrdinaryRpcWithoutRewritingItsRow() throw
assertThat(retainedNumericOwnerRow(entity)).isEqualTo(retainedBefore);
}
+ @org.junit.jupiter.api.Nested
+ class PaidJoinDiscoveryComposition {
+ @org.junit.jupiter.api.io.TempDir Path checkoutDirectory;
+ @Autowired private DataSource paidCompositionDataSource;
+
+ @org.junit.jupiter.api.Test
+ @org.springframework.test.annotation.DirtiesContext
+ void paidJoinReplayAndCharacterDiscoveryCompleteConcurrently() throws Exception {
+ var source = AccountBootstrapRosterFixture.create(UUID.randomUUID());
+ var target = accountTarget(source);
+ assertThat(target.canonicalTenantId()).isNotEqualTo(SOURCE.target().tenantUuid());
+ String suffix = UUID.randomUUID().toString().substring(0, 8);
+ var first = registerAccount("paid-pair-a-" + suffix);
+ var second = registerAccount("paid-pair-b-" + suffix);
+ boolean firstIsPayer = first.accountUuid().compareTo(second.accountUuid()) < 0;
+ var payer = firstIsPayer ? first : second;
+ var caller = firstIsPayer ? second : first;
+ assertThat(payer.accountUuid().compareTo(caller.accountUuid())).isNegative();
+ var hosting =
+ CanonicalHostingSubscriptionTestFixture.createForExistingTenant(
+ paidCompositionDataSource,
+ accounts.findByAccountUuid(payer.accountUuid()).orElseThrow(),
+ tenantEvidence(target, 102L))
+ .withCheckoutDirectory(checkoutDirectory);
+ assertThat(hosting.completeFirstInvoice("password123").outcome().name())
+ .isEqualTo("COMMITTED");
+ new TransactionTemplate(transactionManager)
+ .executeWithoutResult(
+ status -> accountSources.initializeIssuerIfAbsent("firemud-account-service"));
+ initializeMemberAuthority(caller, target.canonicalTenantId());
+
+ var observer = Mockito.mock(StripeHostingSubscriptionObserver.class);
+ var concurrentObservations = new CountDownLatch(2);
+ var observeTogether = new java.util.concurrent.atomic.AtomicBoolean();
+ var firstObservationByWorker = ThreadLocal.withInitial(() -> true);
+ Mockito.when(observer.observe(Mockito.any()))
+ .thenAnswer(invocation -> {
+ assertThat(TransactionSynchronizationManager.isActualTransactionActive()).isFalse();
+ if (observeTogether.get() && firstObservationByWorker.get()) {
+ firstObservationByWorker.set(false);
+ concurrentObservations.countDown();
+ if (!concurrentObservations.await(10, TimeUnit.SECONDS)) {
+ throw new IllegalStateException("Paid entrypoints did not overlap outside SQL");
+ }
+ }
+ synchronized (hosting) {
+ return hosting.observer().observe(invocation.getArgument(0));
+ }
+ });
+ configureCanonicalAccountOwners(
+ controlledAccountTargets(target, source),
+ hosting.lifecycleRepository(),
+ observer,
+ hosting.clock());
+ var roster = Mockito.mock(AccountBootstrapRosterReadClient.class);
+ UUID actorId = UUID.randomUUID();
+ Mockito.when(roster.read(Mockito.any(), Mockito.eq(caller.accountUuid()), Mockito.any()))
+ .thenReturn(
+ List.of(new AccountBootstrapRosterReadClient.Actor(actorId, "Fixture actor", 7)));
+ facade.setAccountBootstrapRosterReadClient(roster);
+ String token = issuePlayerBootstrap(caller);
+ // HTTP issuance uses the wall clock; keep the retained paid and scope fixtures on one clock.
+ hosting.clock().advanceToAtLeast(Clock.systemUTC().instant());
+ hosting
+ .clock()
+ .advanceToAtLeast(
+ hosting
+ .clock()
+ .instant()
+ .truncatedTo(java.time.temporal.ChronoUnit.MICROS)
+ .plusNanos(999));
+ var bootstrapClaims = jwtUtil.parseToken(token).getPayload();
+ assertThat(hosting.clock().instant())
+ .isAfterOrEqualTo(bootstrapClaims.getIssuedAt().toInstant())
+ .isBefore(bootstrapClaims.getExpiration().toInstant());
+ assertThat(hosting.clock().instant().getNano() % 1_000).isEqualTo(999);
+ String scope = discoverConnectScope(caller, token, target);
+ var request = new JoinPublicProductionRequest(scope, UUID.randomUUID().toString());
+ var joined = facade.joinPublicProduction(token, request);
+ assertThat(joined.success()).isTrue();
+ assertThat(joined.tenantId()).isEqualTo(target.canonicalTenantId());
+
+ var ready = new CountDownLatch(2);
+ var go = new CountDownLatch(1);
+ var workers = Executors.newFixedThreadPool(2);
+ try {
+ var replay =
+ workers.submit(() -> {
+ ready.countDown();
+ if (!go.await(10, TimeUnit.SECONDS))
+ throw new IllegalStateException("Start not released");
+ return facade.joinPublicProduction(token, request);
+ });
+ var discovery =
+ workers.submit(() -> {
+ ready.countDown();
+ if (!go.await(10, TimeUnit.SECONDS))
+ throw new IllegalStateException("Start not released");
+ return facade.listBootstrapCharacters(
+ token, target.worldSlug(), target.realmSlug(), scope);
+ });
+ assertThat(ready.await(10, TimeUnit.SECONDS)).isTrue();
+ observeTogether.set(true);
+ go.countDown();
+ var retained = replay.get(30, TimeUnit.SECONDS);
+ assertThat(retained.success()).isTrue();
+ assertThat(retained.tenantId()).isEqualTo(joined.tenantId());
+ assertThat(retained.membershipVersion()).isEqualTo(joined.membershipVersion());
+ assertThat(discovery.get(30, TimeUnit.SECONDS))
+ .singleElement()
+ .satisfies(actor -> {
+ assertThat(actor.characterId()).isEqualTo(actorId.toString());
+ assertThat(actor.characterName()).isEqualTo("Fixture actor");
+ assertThat(actor.level()).isEqualTo(7);
+ });
+ assertThat(concurrentObservations.getCount()).isZero();
+ Mockito.verify(roster).read(Mockito.any(), Mockito.eq(caller.accountUuid()), Mockito.any());
+ } finally {
+ go.countDown();
+ workers.shutdownNow();
+ assertThat(workers.awaitTermination(10, TimeUnit.SECONDS)).isTrue();
+ }
+ }
+ }
+
private void configureCanonicalAccountOwners() {
var transaction = new TransactionTemplate(transactionManager);
var target = accountTarget();
- var creationRequest = UUID.randomUUID();
- var operation = UUID.randomUUID();
- String key = "b-" + operation.toString().replace("-", "");
- String digest =
- GameTenantCreationDigest.requestDigest(
- TEST_NAMESPACE, creationRequest, key, "Bootstrap composition", null);
- long rowId = 101L;
- var source =
- new FreshTenantCreationEvidence(
- 1,
- TEST_NAMESPACE,
- creationRequest,
- operation,
- digest,
- target.canonicalTenantId(),
- rowId,
- key,
- "NEW_GAME_ROW",
- GameTenantCreationDigest.evidenceDigest(
- TEST_NAMESPACE,
- creationRequest,
- operation,
- digest,
- target.canonicalTenantId(),
- rowId,
- key,
- "NEW_GAME_ROW"));
+ var source = tenantEvidence(target, 101L);
transaction.executeWithoutResult(status -> {
tenants.importVerified(source);
generations.initializeTenantIfAbsent(target.canonicalTenantId());
@@ -438,7 +542,42 @@ private void configureCanonicalAccountOwners() {
var targets = controlledAccountTargets(target);
var hosting = Mockito.mock(AccountHostingSubscriptionLifecycleRepository.class);
var observer = Mockito.mock(StripeHostingSubscriptionObserver.class);
- var clock = Clock.systemUTC();
+ configureCanonicalAccountOwners(targets, hosting, observer, Clock.systemUTC());
+ }
+
+ private static FreshTenantCreationEvidence tenantEvidence(Target target, long rowId) {
+ var creationRequest = UUID.randomUUID();
+ var operation = UUID.randomUUID();
+ String key = "b-" + operation.toString().replace("-", "");
+ String digest =
+ GameTenantCreationDigest.requestDigest(
+ TEST_NAMESPACE, creationRequest, key, "Bootstrap composition", null);
+ return new FreshTenantCreationEvidence(
+ 1,
+ TEST_NAMESPACE,
+ creationRequest,
+ operation,
+ digest,
+ target.canonicalTenantId(),
+ rowId,
+ key,
+ "NEW_GAME_ROW",
+ GameTenantCreationDigest.evidenceDigest(
+ TEST_NAMESPACE,
+ creationRequest,
+ operation,
+ digest,
+ target.canonicalTenantId(),
+ rowId,
+ key,
+ "NEW_GAME_ROW"));
+ }
+
+ private void configureCanonicalAccountOwners(
+ CanonicalGameplayAdmissionDecisionReadClient targets,
+ AccountHostingSubscriptionLifecycleRepository hosting,
+ StripeHostingSubscriptionObserver observer,
+ Clock clock) {
var entitlement =
new AccountPublicBootstrapEntitlementOwner(
tenantEvents,
@@ -474,6 +613,11 @@ private void configureCanonicalAccountOwners() {
}
private CanonicalGameplayAdmissionDecisionReadClient controlledAccountTargets(Target target) {
+ return controlledAccountTargets(target, SOURCE);
+ }
+
+ private CanonicalGameplayAdmissionDecisionReadClient controlledAccountTargets(
+ Target target, AccountBootstrapRosterFixture.Fixture source) {
var client = Mockito.mock(CanonicalGameplayAdmissionDecisionReadClient.class);
Mockito.when(client.listVisiblePublicProductionAdmissionTargets(Mockito.any()))
.thenAnswer(invocation -> {
@@ -504,7 +648,7 @@ private CanonicalGameplayAdmissionDecisionReadClient controlledAccountTargets(Ta
CanonicalGameplayAdmissionDecisionReadGrpcCodec.PublishedRealmEvidence.class);
Mockito.when(published.selector()).thenReturn(request);
Mockito.when(published.currentTarget()).thenReturn(target);
- Mockito.when(published.sourceEvidence()).thenReturn(ownerEvidence(request));
+ Mockito.when(published.sourceEvidence()).thenReturn(ownerEvidence(request, source));
var world = Mockito.mock(WorldCanonicalInstanceLifecycleEvidence.class);
Mockito.when(world.lifecycleStatus()).thenReturn("ACTIVE");
Mockito.when(world.lifecycleEpoch()).thenReturn(target.activeWorldEpoch());
@@ -514,17 +658,21 @@ private CanonicalGameplayAdmissionDecisionReadClient controlledAccountTargets(Ta
return client;
}
- private void initializeMemberAuthority(TestAccount account) {
+ private void initializeMemberAuthority(TestAccount account, UUID tenantId) {
new TransactionTemplate(transactionManager)
.executeWithoutResult(status ->
generations.initialize(
AccountAuthorityGenerationRepository.AuthorityScope.membership(
- account.accountUuid(), SOURCE.target().tenantUuid())));
+ account.accountUuid(), tenantId)));
}
private static Target accountTarget() {
- var target = SOURCE.target();
- var proof = SOURCE.evidence().gameSessionOwnerProof();
+ return accountTarget(SOURCE);
+ }
+
+ private static Target accountTarget(AccountBootstrapRosterFixture.Fixture source) {
+ var target = source.target();
+ var proof = source.evidence().gameSessionOwnerProof();
var hold = proof.holdIdentity();
var request = hold.request();
return new Target(
@@ -564,7 +712,13 @@ private static Target accountTarget() {
private static CanonicalGameplayRosterOwnerReadEvidence ownerEvidence(
CanonicalGameplayRosterOwnerReadEvidence.Request request) {
- var base = SOURCE.evidence().request();
+ return ownerEvidence(request, SOURCE);
+ }
+
+ private static CanonicalGameplayRosterOwnerReadEvidence ownerEvidence(
+ CanonicalGameplayRosterOwnerReadEvidence.Request request,
+ AccountBootstrapRosterFixture.Fixture source) {
+ var base = source.evidence().request();
var expected =
new CanonicalGameplayRosterOwnerReadEvidence.Request(
request.requestUuid(),
@@ -585,9 +739,9 @@ private static CanonicalGameplayRosterOwnerReadEvidence ownerEvidence(
throw new IllegalArgumentException("Controlled owner target mismatch");
return new CanonicalGameplayRosterOwnerReadEvidence(
request,
- SOURCE.target().admissionPointerSnapshotDigest(),
- SOURCE.evidence().gameSessionOwnerProof(),
- SOURCE.evidence().publishedPolicySetEvidence());
+ source.target().admissionPointerSnapshotDigest(),
+ source.evidence().gameSessionOwnerProof(),
+ source.evidence().publishedPolicySetEvidence());
}
private TestAccount registerAccount(String username) throws Exception {
@@ -630,14 +784,19 @@ private String issuePlayerBootstrap(TestAccount account) throws Exception {
}
private String discoverConnectScope(TestAccount account, String token) throws Exception {
+ return discoverConnectScope(account, token, accountTarget());
+ }
+
+ private String discoverConnectScope(TestAccount account, String token, Target target)
+ throws Exception {
var request =
HttpRequest.newBuilder(
URI.create(
accountBaseUrl()
+ "/auth/bootstrap/worlds/"
- + SOURCE.target().worldSlug()
+ + target.worldSlug()
+ "/realms?tenantSlug="
- + accountTarget().tenantSlug()))
+ + target.tenantSlug()))
.header(HttpHeaders.AUTHORIZATION, "Bearer " + token)
.GET()
.build();
@@ -645,9 +804,8 @@ private String discoverConnectScope(TestAccount account, String token) throws Ex
if (response.statusCode() != 200) {
// Preserve the HTTP assertion while exposing an owner/proxy exception otherwise hidden by
// the public INTERNAL_ERROR projection. This uses the same actual caller and owner setup.
- org.assertj.core.api.Assertions.assertThatCode(() ->
- facade.listBootstrapRealms(
- token, accountTarget().tenantSlug(), SOURCE.target().worldSlug()))
+ org.assertj.core.api.Assertions.assertThatCode(
+ () -> facade.listBootstrapRealms(token, target.tenantSlug(), target.worldSlug()))
.as("REALMS owner composition after HTTP response: %s", response.body())
.doesNotThrowAnyException();
}
@@ -655,13 +813,13 @@ token, accountTarget().tenantSlug(), SOURCE.target().worldSlug()))
var realms = jsonMapper.readTree(response.body()).path("data");
assertThat(realms.size()).isEqualTo(1);
assertThat(realms.get(0).path("tenantId").asText())
- .isEqualTo(SOURCE.target().tenantUuid().toString());
+ .isEqualTo(target.canonicalTenantId().toString());
String scope = realms.get(0).path("connectScopeId").asText();
var claims = jwtUtil.parseToken(scope).getPayload();
assertThat(claims.getSubject()).isEqualTo(account.accountUuid().toString());
assertThat(claims.get("scopeDigestVersion", Number.class).longValue()).isEqualTo(2L);
assertThat(claims.get("tenantId", String.class))
- .isEqualTo(SOURCE.target().tenantUuid().toString());
+ .isEqualTo(target.canonicalTenantId().toString());
return scope;
}
diff --git a/services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/repository/AccountGameplayAdmissionCurrentSourcesPostgresIntegrationTest.java b/services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/repository/AccountGameplayAdmissionCurrentSourcesPostgresIntegrationTest.java
index 7d72f9fa2d..8baa175393 100644
--- a/services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/repository/AccountGameplayAdmissionCurrentSourcesPostgresIntegrationTest.java
+++ b/services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/repository/AccountGameplayAdmissionCurrentSourcesPostgresIntegrationTest.java
@@ -12,6 +12,7 @@
import edu.umd.cs.findbugs.annotations.SuppressFBWarnings;
import integration.net.firedevops.firemud.accountservice.repository.AccountPostgresIntegrationFixture;
+import integration.net.firedevops.firemud.accountservice.repository.CanonicalHostingSubscriptionTestFixture;
import io.grpc.Context;
import io.grpc.ManagedChannel;
import io.grpc.MethodDescriptor;
@@ -60,6 +61,7 @@
import java.util.Optional;
import java.util.Set;
import java.util.UUID;
+import java.util.concurrent.Callable;
import java.util.concurrent.CountDownLatch;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
@@ -89,6 +91,8 @@
import net.firedevops.firemud.accountservice.repository.AccountGameplayDelegationResponseEnvelopeRepository.RecoveredCredential;
import net.firedevops.firemud.accountservice.repository.AccountMembershipPairAuthorityRepository.TenantProvenanceKind;
import net.firedevops.firemud.accountservice.repository.AccountMembershipPairAuthorityRepository.VerifiedTenantProvenance;
+import net.firedevops.firemud.accountservice.repository.AccountSubscriptionCreateRequest.OwnerFence;
+import net.firedevops.firemud.accountservice.repository.AccountSubscriptionCreateRequest.ProducerEvidence;
import net.firedevops.firemud.accountservice.service.AccountCanonicalFirstJoinTerminalCoordinator;
import net.firedevops.firemud.accountservice.service.AccountMembershipAuthorityEventProducer;
import net.firedevops.firemud.accountservice.service.session.AccountCoordinationPinnedConnectionProvider;
@@ -124,6 +128,8 @@
import net.firedevops.firemud.common.security.GameSessionAccountDelegationProfile.AccountSecurityCutoff;
import net.firedevops.firemud.common.security.GameSessionAccountDelegationRegistryRecord.AccountAuthoritySnapshot;
import net.firedevops.firemud.common.tenant.FreshTenantCreationEvidence;
+import net.firedevops.firemud.common.tenant.FreshTenantCreatorDigest;
+import net.firedevops.firemud.common.tenant.FreshTenantCreatorEvidence;
import net.firedevops.firemud.common.tenant.GameTenantCreationDigest;
import net.firedevops.firemud.common.world.CanonicalGameplayRosterOwnerReadEvidence;
import net.firedevops.firemud.common.world.WorldCanonicalInitialAdmissionHold;
@@ -131,6 +137,7 @@
import net.firedevops.firemud.test.TestContainerImages;
import org.flywaydb.core.Flyway;
import org.jooq.DSLContext;
+import org.jooq.ExecuteListener;
import org.jooq.Record;
import org.jooq.SQLDialect;
import org.jooq.impl.DSL;
@@ -139,6 +146,8 @@
import org.junit.jupiter.api.BeforeAll;
import org.junit.jupiter.api.Test;
import org.junit.jupiter.api.io.TempDir;
+import org.junit.jupiter.params.ParameterizedTest;
+import org.junit.jupiter.params.provider.ValueSource;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.jdbc.datasource.ConnectionHolder;
import org.springframework.jdbc.datasource.DataSourceTransactionManager;
@@ -225,8 +234,7 @@ void positiveCurrentReadReturnsExactFiveSourcesAndOriginalCommitPreservesOwners(
CommittedCandidateVerificationData.hasSameOwnerEvidence(
independentCandidate, current.currentCommittedCandidate()))
.isTrue();
- assertThat(current.typedTenantEvent().gameplayAvailable()).isTrue();
- assertThat(current.typedTenantEvent().allowNewGameplayBindings()).isTrue();
+ assertThat(current.sourceValidUntilMs()).isNull();
assertThat(current.leaseSourceFields().keySet())
.containsExactlyInAnyOrder(
"authorityTuple",
@@ -255,6 +263,499 @@ void positiveCurrentReadReturnsExactFiveSourcesAndOriginalCommitPreservesOwners(
.isEqualTo(current.leaseSourceFields());
}
+ @Test
+ void paidCurrentReadAndOriginalPhysicalCommitUseTheGenuineOwnerWithoutChangingSources()
+ throws Exception {
+ PaidFixture paid = newPaidFixture(null);
+ Fixture caller = paid.caller();
+ var before = caller.sourceAndIssuanceImage();
+ int reads = paid.hosting().transport().reads();
+ var observed = paid.prepare().observeOutsideSql();
+ var current = paid.read(observed);
+ assertThat(paid.hosting().transport().reads()).isEqualTo(reads + 1);
+ assertThat(current.snapshot().tenantId()).isEqualTo(paid.hosting().tenantId().toString());
+ assertThat(current.sourceValidUntilMs())
+ .isEqualTo(paid.hosting().clock().instant().plusSeconds(14).toEpochMilli());
+ assertThat(caller.sourceAndIssuanceImage()).isEqualTo(before);
+
+ var lease = caller.beginPendingAdmissionLease(current);
+ assertThat(Long.parseLong((String) lease.carrier().get("expiresAt")))
+ .isLessThanOrEqualTo(current.sourceValidUntilMs());
+ var ownerImage = caller.sourceAndIssuanceImage();
+ UUID decisionId = UUID.randomUUID();
+ var acknowledgement =
+ new AccountGameplayAdmissionOriginalCommitExecutor(caller.dataSource)
+ .executeWithCurrentSources(
+ lease,
+ decisionId,
+ TEST_NAMESPACE,
+ caller.committedCandidate,
+ paid.prepare().observeOutsideSql());
+ assertThat(acknowledgement.evidence().canonicalJson()).isEqualTo(lease.canonicalJson());
+ assertThat(caller.sourceAndIssuanceImage()).isEqualTo(ownerImage);
+ var receipt =
+ new AccountGameplayAdmissionOriginalAckReceiptCommitExecutor(caller.dataSource)
+ .confirm(acknowledgement);
+ assertThat(receipt.operation().state())
+ .isEqualTo(AccountGameplayAdmissionLeaseOperation.State.COMMITTED);
+ assertThat(receipt.operation().evidence().canonicalJson()).isEqualTo(lease.canonicalJson());
+ assertThatThrownBy(() ->
+ new AccountGameplayAdmissionOriginalCommitExecutor(caller.dataSource)
+ .executeWithCurrentSources(
+ lease,
+ decisionId,
+ TEST_NAMESPACE,
+ caller.committedCandidate,
+ paid.prepare().observeOutsideSql()))
+ .isInstanceOf(IllegalStateException.class);
+ }
+
+ @Test
+ void paidAdmissionLocksWalletBeforeTenantGenerationInBothSqlPhases() throws Exception {
+ PaidFixture paid = newPaidFixture(null);
+ Fixture caller = paid.caller();
+ List sourceImageBefore = caller.sourceAndIssuanceImage();
+
+ var prepared = whileWalletInstrumentIsLockedBeforeTenantGeneration(paid, () -> paid.prepare());
+ var observed = prepared.observeOutsideSql();
+ var current =
+ whileWalletInstrumentIsLockedBeforeTenantGeneration(paid, () -> paid.read(observed));
+
+ assertThat(current.snapshot().tenantId()).isEqualTo(paid.hosting().tenantId().toString());
+ assertThat(caller.sourceAndIssuanceImage()).isEqualTo(sourceImageBefore);
+ }
+
+ @Test
+ void currentDemoHeadRemainsSelectedWhileSameTenantHasPendingHostingSubscription()
+ throws Exception {
+ Fixture caller = newFixture(null);
+ var hosting = CanonicalHostingSubscriptionTestFixture.create(caller.dataSource, TEST_NAMESPACE);
+ String authorizationDigest = "sha256:" + "a".repeat(64);
+ UUID authorizationOperation = UUID.randomUUID();
+ var creator =
+ new FreshTenantCreatorEvidence(
+ 1,
+ caller.tenantEvidence,
+ hosting.accountUuid(),
+ authorizationOperation,
+ authorizationDigest,
+ FreshTenantCreatorDigest.evidenceDigest(
+ 1,
+ caller.tenantEvidence,
+ hosting.accountUuid(),
+ authorizationOperation,
+ authorizationDigest));
+ var owner =
+ caller.transaction.execute(status ->
+ new AccountInitialTenantBillingOwnerRepository(caller.dsl)
+ .establishInitial(
+ new AccountInitialTenantBillingOwnerRepository.InitialRequest(
+ UUID.randomUUID(), creator, UUID.randomUUID(), 1, true)));
+ var instrument = hosting.instrument();
+ caller.transaction.execute(status ->
+ hosting
+ .intents()
+ .retainPending(
+ new AccountSubscriptionCreateRequest(
+ UUID.randomUUID(),
+ caller.tenantUuid,
+ new OwnerFence(
+ hosting.accountUuid(), owner.ownerVersion(), owner.ownerGeneration()),
+ "hosting",
+ instrument.instrumentUuid(),
+ instrument.rowVersion(),
+ new ProducerEvidence(
+ hosting.accountUuid(), UUID.randomUUID(), authorizationDigest),
+ null)));
+
+ int providerReads = hosting.transport().reads();
+ var prepared =
+ caller.inCurrentSources(sources ->
+ sources.prepareCurrentPublicProductionNew(
+ caller.tenantUuid,
+ caller.committedCandidate.identity().tokenJti(),
+ caller.committedCandidate,
+ hosting.admissionPaidSource()));
+ var observed = prepared.observeOutsideSql();
+ var current =
+ caller.inCurrentSources(sources ->
+ sources.readCurrentPublicProductionNew(
+ caller.tenantUuid,
+ caller.committedCandidate.identity().tokenJti(),
+ caller.committedCandidate,
+ observed));
+
+ assertThat(current.sourceValidUntilMs()).isNull();
+ assertThat(hosting.transport().reads()).isEqualTo(providerReads);
+ }
+
+ @Test
+ void paidSourceWithoutItsConcreteCompositionOrObservationNeverFallsBackToDemo() throws Exception {
+ PaidFixture paid = newPaidFixture(null, true);
+ Fixture caller = paid.caller();
+ var before = caller.sourceAndIssuanceImage();
+ int reads = paid.hosting().transport().reads();
+ assertThatThrownBy(() ->
+ caller.inCurrentSources(sources ->
+ sources.prepareCurrentPublicProductionNew(
+ paid.hosting().tenantId(),
+ caller.committedCandidate.identity().tokenJti(),
+ caller.committedCandidate,
+ null)))
+ .isInstanceOf(IllegalStateException.class);
+ assertThatThrownBy(() -> paid.read(null)).isInstanceOf(IllegalStateException.class);
+ // Historical DEMO evidence for the exact paid tenant remains retained, not a fallback.
+ assertThat(
+ caller.dsl.fetchExists(
+ caller
+ .dsl
+ .selectOne()
+ .from("account_demo_tenant_entitlements")
+ .where(
+ org.jooq
+ .impl
+ .DSL
+ .field("tenant_uuid", UUID.class)
+ .eq(paid.hosting().tenantId()))))
+ .isTrue();
+ assertThat(paid.hosting().transport().reads()).isEqualTo(reads);
+ assertThat(caller.sourceAndIssuanceImage()).isEqualTo(before);
+ assertThat(caller.leaseOperationCount()).isZero();
+ }
+
+ @Test
+ void paidObservationCannotRunInsideThePreparingAccountTransaction() throws Exception {
+ PaidFixture paid = newPaidFixture(null);
+ int reads = paid.hosting().transport().reads();
+ paid.caller()
+ .inCurrentSources(sources -> {
+ var prepared =
+ sources.prepareCurrentPublicProductionNew(
+ paid.hosting().tenantId(),
+ paid.caller().committedCandidate.identity().tokenJti(),
+ paid.caller().committedCandidate,
+ paid.hosting().admissionPaidSource());
+ assertThat(prepared).isNotNull();
+ assertThatThrownBy(prepared::observeOutsideSql).isInstanceOf(IllegalStateException.class);
+ return null;
+ });
+ assertThat(paid.hosting().transport().reads()).isEqualTo(reads);
+ }
+
+ @ParameterizedTest
+ @ValueSource(longs = {13_999, 14_000})
+ void paidReceiptExpiresAtEntitlementDeadlineBeforeLifecycleDeadline(long elapsedMillis)
+ throws Exception {
+ PaidFixture paid = newPaidFixture(null);
+ Fixture caller = paid.caller();
+ var observed = paid.prepare().observeOutsideSql();
+ Instant evaluatedAt = paid.hosting().clock().instant();
+ Instant deadline = evaluatedAt.plusSeconds(14);
+ Instant readTime = evaluatedAt.plusMillis(elapsedMillis);
+ UUID originalJti = caller.committedCandidate.identity().tokenJti();
+ var reachedCallerRead = new AtomicBoolean();
+ var advanceClock =
+ advancePaidClockDuringCallerRead(paid, originalJti, readTime, reachedCallerRead);
+ java.util.function.Supplier read =
+ () ->
+ caller.inCurrentSources(
+ sources ->
+ sources.readCurrentPublicProductionNew(
+ paid.hosting().tenantId(),
+ originalJti,
+ caller.committedCandidate,
+ observed),
+ advanceClock);
+
+ if (readTime.isBefore(deadline)) {
+ assertThat(read.get().sourceValidUntilMs()).isEqualTo(deadline.toEpochMilli());
+ } else {
+ assertThatThrownBy(read::get)
+ .isInstanceOf(IllegalStateException.class)
+ .hasMessage("Current paid NEW source has expired");
+ }
+ assertThat(reachedCallerRead).isTrue();
+ assertThat(paid.hosting().clock().instant()).isEqualTo(readTime);
+ }
+
+ @Test
+ void paidReceiptExpiringDuringFinalCallerSourceReadIsUnavailableWithoutWrites() throws Exception {
+ PaidFixture paid = newPaidFixture(null);
+ Fixture caller = paid.caller();
+ var observed = paid.prepare().observeOutsideSql();
+ long validUntil = paid.read(observed).sourceValidUntilMs();
+ Instant pastDeadline = Instant.ofEpochMilli(validUntil).plusMillis(1);
+ UUID originalJti = caller.committedCandidate.identity().tokenJti();
+ int providerReads = paid.hosting().transport().reads();
+ var before = caller.sourceAndIssuanceImage();
+ var reachedCallerRead = new AtomicBoolean();
+ var expireDuringCallerRead =
+ advancePaidClockDuringCallerRead(paid, originalJti, pastDeadline, reachedCallerRead);
+
+ assertThatThrownBy(() ->
+ caller.inCurrentSources(
+ sources ->
+ sources.readCurrentPublicProductionNew(
+ paid.hosting().tenantId(),
+ originalJti,
+ caller.committedCandidate,
+ observed),
+ expireDuringCallerRead))
+ .isInstanceOf(IllegalStateException.class)
+ .hasMessage("Current paid NEW source has expired");
+ assertThat(reachedCallerRead).isTrue();
+ assertThat(paid.hosting().clock().instant()).isEqualTo(pastDeadline);
+ assertThat(paid.hosting().transport().reads()).isEqualTo(providerReads);
+ assertThat(caller.sourceAndIssuanceImage()).isEqualTo(before);
+ assertThat(caller.leaseOperationCount()).isZero();
+ }
+
+ private static ExecuteListener advancePaidClockDuringCallerRead(
+ PaidFixture paid, UUID originalJti, Instant readTime, AtomicBoolean reachedCallerRead) {
+ // This exact issuance SELECT is downstream of the paid receipt read and early clock check.
+ return ExecuteListener.onExecuteEnd(ctx -> {
+ String sql = ctx.sql();
+ var query = ctx.query();
+ if (sql != null
+ && sql.contains("SELECT request_id FROM account_gameplay_delegation_issuance_operations")
+ && sql.contains("WHERE token_jti = ? AND status = 'COMMITTED'")
+ && query != null
+ && query.getBindValues().equals(List.of(originalJti))
+ && reachedCallerRead.compareAndSet(false, true)) {
+ assertThat(paid.hosting().clock().instant()).isBefore(readTime);
+ paid.hosting().clock().advanceToAtLeast(readTime);
+ }
+ });
+ }
+
+ @Test
+ void paidObservationExpiryAndContradictoryProviderFactsCannotFinalizeTheOriginalLease()
+ throws Exception {
+ PaidFixture paid = newPaidFixture(null);
+ var current = paid.read(paid.prepare().observeOutsideSql());
+ var lease = paid.caller().beginPendingAdmissionLease(current);
+ paid.hosting().providerStatus("past_due");
+ var contradictory = paid.prepare().observeOutsideSql();
+ assertThatThrownBy(() -> paid.read(contradictory)).isInstanceOf(IllegalStateException.class);
+ paid.hosting().providerStatus("active");
+ var expired = paid.prepare().observeOutsideSql();
+ paid.hosting().clock().advance(Duration.ofSeconds(15));
+ var before = paid.caller().sourceAndIssuanceImage();
+ assertThatThrownBy(() ->
+ new AccountGameplayAdmissionOriginalCommitExecutor(paid.caller().dataSource)
+ .executeWithCurrentSources(
+ lease,
+ UUID.randomUUID(),
+ TEST_NAMESPACE,
+ paid.caller().committedCandidate,
+ expired))
+ .isInstanceOf(IllegalStateException.class);
+ assertThat(paid.caller().readLeaseOperation(lease).state())
+ .isEqualTo(AccountGameplayAdmissionLeaseOperation.State.PENDING);
+ assertThat(paid.caller().sourceAndIssuanceImage()).isEqualTo(before);
+ }
+
+ @Test
+ void paidHeadChangeDuringTheActualProviderReadRefusesThePreparedSourceAndOriginalLease()
+ throws Exception {
+ PaidFixture paid = newPaidFixture(null);
+ var current = paid.read(paid.prepare().observeOutsideSql());
+ var lease = paid.caller().beginPendingAdmissionLease(current);
+ var prepared = paid.prepare();
+ paid.hosting()
+ .transport()
+ .duringRead(() -> {
+ paid.hosting().clock().advance(Duration.ofSeconds(1));
+ paid.refresh();
+ });
+ var observed = prepared.observeOutsideSql();
+ var before = paid.caller().sourceAndIssuanceImage();
+ assertThatThrownBy(() -> paid.read(observed))
+ .isInstanceOf(AccountSubscriptionIntentRepository.FenceRejectedException.class)
+ .hasMessage("Pending claim owner/customer/instrument/subscription fence rejected");
+ assertThatThrownBy(() ->
+ new AccountGameplayAdmissionOriginalCommitExecutor(paid.caller().dataSource)
+ .executeWithCurrentSources(
+ lease,
+ UUID.randomUUID(),
+ TEST_NAMESPACE,
+ paid.caller().committedCandidate,
+ paid.prepare().observeOutsideSql()))
+ .isInstanceOf(IllegalArgumentException.class)
+ .hasMessage(
+ "membership source tenantAuthorityGeneration current equality does not match its bound evidence");
+ assertThat(paid.caller().readLeaseOperation(lease).evidence().canonicalJson())
+ .isEqualTo(lease.canonicalJson());
+ assertThat(paid.caller().readLeaseOperation(lease).state())
+ .isEqualTo(AccountGameplayAdmissionLeaseOperation.State.PENDING);
+ assertThat(paid.caller().sourceAndIssuanceImage()).isEqualTo(before);
+ }
+
+ @Test
+ void authenticatedPaidOwnerCapsTheLeaseFinalizesOnceAndRecoversWithoutPaidAuthority()
+ throws Exception {
+ try (PhysicalRedisFixture redis = PhysicalRedisFixture.start()) {
+ PaidFixture paid = newPaidFixture(redis.client());
+ Fixture caller = paid.caller();
+ var identity = caller.committedCandidate.identity();
+ var recovered =
+ caller.responseRecoveryOwner.recoverInitialLoginResponse(
+ identity.requestId(),
+ identity.accountId(),
+ new CallerIdentity(identity.callerWorkload(), identity.callerContextId()));
+ String jwt = new String(recovered.compactJwtBytes(), StandardCharsets.US_ASCII);
+ Candidate candidate =
+ candidateWithTenant(admissionCandidate(caller), paid.hosting().tenantId());
+ UUID requestId = UUID.randomUUID();
+ Target target = admissionTarget(candidate, UUID.randomUUID());
+ var decisions = controlledPublishedTargetClient(candidate, target, requestId);
+ controlProvisionalDecisionRead(decisions, candidate, target);
+ var verifier =
+ new AccountGameplayAdmissionCallerVerifier(
+ caller.signerFixture.trustedJwksSource(),
+ caller.committedIssuanceOwner,
+ Clock.systemUTC());
+ var owner =
+ new AccountGameplayAdmissionLeaseOwner(
+ verifier,
+ decisions,
+ TEST_NAMESPACE,
+ caller.dataSource,
+ paid.hosting().admissionPaidSource());
+ var peer = GrpcPeerIdentity.parseUri(CALLER_WORKLOAD).orElseThrow();
+ var acquire =
+ AccountGameplayAdmissionLeaseGrpcCodec.toAcquireRequest(
+ requestId, jwt, candidate, target, BigInteger.ONE);
+ var response = new AtomicReference();
+ var before = caller.sourceAndIssuanceImageForAuthenticatedCommit();
+ long acquisitionDatabaseMillis =
+ caller.inSerializableTransaction(caller::currentDatabaseMillisOnEnlistedConnection);
+ paid.hosting().clock().advanceToAtLeast(Instant.ofEpochMilli(acquisitionDatabaseMillis));
+ withPeer(peer, () -> response.set(owner.acquire(acquire)));
+ var lease =
+ AccountGameplayAdmissionLeaseGrpcCodec.parseAcquireResponse(
+ AccountGameplayAdmissionLeaseGrpcCodec.parseAcquireRequest(acquire),
+ response.get())
+ .originalLeaseEvidence();
+ long evaluatedAt = Long.parseLong((String) lease.carrier().get("evaluatedAt"));
+ assertThat(Long.parseLong((String) lease.carrier().get("expiresAt")))
+ .isEqualTo(
+ Math.min(
+ Math.min(evaluatedAt + 15_000L, identity.expiresAtEpochSecond() * 1000L),
+ paid.hosting().clock().instant().plusSeconds(14).toEpochMilli()));
+ byte[] leaseBytes = lease.canonicalJson().getBytes(StandardCharsets.UTF_8);
+ paid.hosting().providerStatus("unsupported");
+ var read = AccountGameplayAdmissionLeaseGrpcCodec.toReadRequest(jwt, leaseBytes);
+ withPeer(peer, () -> response.set(owner.read(read)));
+ assertThat(
+ AccountGameplayAdmissionLeaseGrpcCodec.parseReadResponse(
+ AccountGameplayAdmissionLeaseGrpcCodec.parseReadRequest(read), response.get())
+ .state())
+ .isEqualTo(State.PENDING);
+ assertThatThrownBy(() -> withPeer(peer, () -> owner.acquire(acquire)))
+ .isInstanceOf(StatusRuntimeException.class);
+ UUID decisionId = UUID.randomUUID();
+ var finalize =
+ AccountGameplayAdmissionLeaseGrpcCodec.toFinalizeRequest(jwt, leaseBytes, decisionId);
+ assertThatThrownBy(() -> withPeer(peer, () -> owner.finalizeLease(finalize)))
+ .isInstanceOf(StatusRuntimeException.class);
+ assertThat(caller.readLeaseOperation(lease).state())
+ .isEqualTo(AccountGameplayAdmissionLeaseOperation.State.PENDING);
+
+ paid.hosting().providerStatus("active");
+ var publishedTarget = controlledPublishedTarget(candidate, target, requestId);
+ var targetWithdrawn = new AtomicBoolean();
+ when(decisions.readPublishedRealmAdmissionOwner(any()))
+ .thenAnswer(invocation -> {
+ if (targetWithdrawn.get()) throw Status.UNAVAILABLE.asRuntimeException();
+ return publishedTarget;
+ });
+ paid.hosting().transport().duringRead(() -> targetWithdrawn.set(true));
+ assertThatThrownBy(() -> withPeer(peer, () -> owner.finalizeLease(finalize)))
+ .isInstanceOfSatisfying(
+ StatusRuntimeException.class,
+ failure ->
+ assertThat(failure.getStatus().getCode()).isEqualTo(Status.Code.UNAVAILABLE));
+ assertThat(targetWithdrawn.get()).isTrue();
+ var stillPending = caller.readLeaseOperation(lease);
+ assertThat(stillPending.state())
+ .isEqualTo(AccountGameplayAdmissionLeaseOperation.State.PENDING);
+ assertThat(stillPending.evidence().canonicalJson()).isEqualTo(lease.canonicalJson());
+ assertThat(caller.originalAckReceiptImage(requestId)).isEmpty();
+
+ targetWithdrawn.set(false);
+ withPeer(peer, () -> response.set(owner.finalizeLease(finalize)));
+ var committed = response.get();
+ assertThat(
+ AccountGameplayAdmissionLeaseGrpcCodec.parseFinalizeResponse(
+ AccountGameplayAdmissionLeaseGrpcCodec.parseFinalizeRequest(finalize),
+ committed)
+ .state())
+ .isEqualTo(State.COMMITTED);
+ assertThat(caller.readLeaseOperation(lease).evidence().canonicalJson())
+ .isEqualTo(lease.canonicalJson());
+ assertThat(caller.sourceAndIssuanceImageForAuthenticatedCommit()).isEqualTo(before);
+
+ paid.hosting().providerStatus("unsupported");
+ int providerReads = paid.hosting().transport().reads();
+ var restartedWithoutPaidSource =
+ new AccountGameplayAdmissionLeaseOwner(
+ verifier, decisions, TEST_NAMESPACE, caller.dataSource);
+ withPeer(peer, () -> response.set(restartedWithoutPaidSource.finalizeLease(finalize)));
+ assertThat(response.get()).isEqualTo(committed);
+ assertThat(paid.hosting().transport().reads()).isEqualTo(providerReads);
+ }
+ }
+
+ @Test
+ void paidLifecycleWriterWaitsForCurrentSourceLocksThroughOriginalPhysicalCommit()
+ throws Exception {
+ PaidFixture paid = newPaidFixture(null);
+ Fixture caller = paid.caller();
+ var current = paid.read(paid.prepare().observeOutsideSql());
+ var lease = caller.beginPendingAdmissionLease(current);
+ var observed = paid.prepare().observeOutsideSql();
+ CountDownLatch reached = new CountDownLatch(1);
+ CountDownLatch release = new CountDownLatch(1);
+ AtomicInteger originalBackendPid = new AtomicInteger();
+ ExecutorService executor = Executors.newFixedThreadPool(2);
+ var barrierSource =
+ holdOriginalCommitBeforePhysicalCommit(
+ caller.dataSource, reached, release, originalBackendPid);
+ try {
+ var commit =
+ executor.submit(() ->
+ new AccountGameplayAdmissionOriginalCommitExecutor(barrierSource)
+ .executeWithCurrentSources(
+ lease,
+ UUID.randomUUID(),
+ TEST_NAMESPACE,
+ caller.committedCandidate,
+ observed));
+ assertThat(reached.await(5, TimeUnit.SECONDS)).isTrue();
+ var writer = executor.submit(paid::refresh);
+ int blockedPid =
+ awaitBackendBlockedBy(caller.dsl, originalBackendPid.get(), 3, TimeUnit.SECONDS);
+ assertThat(blockedPid).isPositive().isNotEqualTo(originalBackendPid.get());
+ assertThat(writer.isDone()).isFalse();
+ release.countDown();
+ assertThat(commit.get(5, TimeUnit.SECONDS).evidence().canonicalJson())
+ .isEqualTo(lease.canonicalJson());
+ writer.get(5, TimeUnit.SECONDS);
+ assertThat(caller.readLeaseOperation(lease).state())
+ .isEqualTo(AccountGameplayAdmissionLeaseOperation.State.COMMITTED);
+ assertThatThrownBy(() ->
+ paid.read(paid.prepare().observeOutsideSql()).requireMatchesOriginalLease(lease))
+ .isInstanceOf(IllegalArgumentException.class)
+ .hasMessage(
+ "membership source tenantAuthorityGeneration current equality does not match its bound evidence");
+ } finally {
+ release.countDown();
+ executor.shutdown();
+ if (!executor.awaitTermination(5, TimeUnit.SECONDS)) executor.shutdownNow();
+ }
+ }
+
@Test
void authenticatedAccountOwnerAcquiresAndRetriesTheExactRecoveredAccountToken() throws Exception {
try (PhysicalRedisFixture redis = PhysicalRedisFixture.start()) {
@@ -1405,6 +1906,95 @@ private Fixture newFixture() throws Exception {
return newFixture(null);
}
+ PaidFixture newPaidFixture(AccountGameplayDelegationRedisClient redis) throws Exception {
+ return newPaidFixture(redis, false);
+ }
+
+ private PaidFixture newPaidFixture(
+ AccountGameplayDelegationRedisClient redis, boolean retainSameTenantDemo) throws Exception {
+ Fixture caller = newFixture(redis);
+ var hosting = CanonicalHostingSubscriptionTestFixture.create(caller.dataSource, TEST_NAMESPACE);
+ UUID tenantId = hosting.tenantId();
+ var source =
+ caller.transaction.execute(status -> caller.freshTenants.read(tenantId).orElseThrow());
+ if (retainSameTenantDemo) {
+ var demoRequest = entitlementRequest(tenantId, source);
+ caller.transaction.execute(status -> caller.demoEntitlements.provision(demoRequest, source));
+ }
+ hosting.withCheckoutDirectory(temporaryDirectory).completeFirstInvoice();
+ var scope = canonicalJoinScope(caller.account.getAccountUuid(), tenantId);
+ var provenance =
+ new VerifiedTenantProvenance(
+ null,
+ TenantProvenanceKind.FRESH_GAME_DESIGN,
+ source.operationId(),
+ source.evidenceDigest());
+ var scopes =
+ new AccountConnectScopeRepository(
+ caller.dsl,
+ new AccountTenantIdentityResolver(
+ mock(ApprovedLegacyTenantAssociationRepository.class), TEST_NAMESPACE),
+ caller.freshTenants);
+ String requestId = UUID.randomUUID().toString();
+ String binding = "paid-new-player-" + UUID.randomUUID();
+ caller.transaction.executeWithoutResult(status -> {
+ caller.generations.initialize(
+ AuthorityScope.membership(caller.account.getAccountUuid(), tenantId));
+ scopes.insertCanonical(caller.account.getId(), scope, provenance);
+ caller.joinOperations.insertCanonicalIntent(requestId, scope, binding);
+ });
+ var fence =
+ hosting
+ .transaction()
+ .execute(status -> hosting.lifecycleRepository().prepareCurrentRead(tenantId));
+ var actual = hosting.observer().observe(fence.binding());
+ caller.transaction.executeWithoutResult(status -> {
+ var receipt = hosting.lifecycleRepository().readCurrent(fence, actual);
+ caller.joinOperations.bindCanonicalPolicyEvidence(
+ requestId, scope, binding, receipt.allowPublicJoin(), receipt.entitlementVersion());
+ caller.joinTerminal.commitPaidCanonicalFirstJoin(
+ scope, requestId, binding, hosting.lifecycleRepository(), fence, actual);
+ });
+ return new PaidFixture(caller, hosting);
+ }
+
+ record PaidFixture(Fixture caller, CanonicalHostingSubscriptionTestFixture.Fixture hosting) {
+ AccountGameplayAdmissionCurrentSources.Prepared prepare() {
+ return caller.inCurrentSources(sources ->
+ sources.prepareCurrentPublicProductionNew(
+ hosting.tenantId(),
+ caller.committedCandidate.identity().tokenJti(),
+ caller.committedCandidate,
+ hosting.admissionPaidSource()));
+ }
+
+ AccountGameplayAdmissionCurrentSources.Current read(
+ AccountGameplayAdmissionCurrentSources.Observed observed) {
+ return caller.inCurrentSources(sources ->
+ sources.readCurrentPublicProductionNew(
+ hosting.tenantId(),
+ caller.committedCandidate.identity().tokenJti(),
+ caller.committedCandidate,
+ observed));
+ }
+
+ void refresh() {
+ long version =
+ hosting.intents().findCurrentByTenant(hosting.tenantId()).orElseThrow().rowVersion();
+ assertThat(
+ hosting
+ .service()
+ .reconcile(
+ UUID.randomUUID(),
+ hosting.creation().requestId(),
+ version,
+ hosting.providerId(),
+ null)
+ .outcome())
+ .isEqualTo(AccountHostingSubscriptionLifecycleRepository.Outcome.COMMITTED);
+ }
+ }
+
Fixture newFixture(AccountGameplayDelegationRedisClient redisClient) throws Exception {
return newFixture(redisClient, "latest");
}
@@ -1483,6 +2073,60 @@ private static int awaitBackendBlockedBy(
return -1;
}
+ private T whileWalletInstrumentIsLockedBeforeTenantGeneration(
+ PaidFixture paid, Callable admissionPhase) throws Exception {
+ Fixture caller = paid.caller();
+ ExecutorService executor = Executors.newSingleThreadExecutor();
+ try (Connection blocker = caller.dataSource.getConnection()) {
+ blocker.setAutoCommit(false);
+ int blockerPid;
+ try (Statement statement = blocker.createStatement();
+ ResultSet pid = statement.executeQuery("SELECT pg_backend_pid()")) {
+ assertThat(pid.next()).isTrue();
+ blockerPid = pid.getInt(1);
+ }
+ try (PreparedStatement instrumentLock =
+ blocker.prepareStatement(
+ "SELECT instrument_uuid FROM payment_instrument WHERE account_uuid = ? "
+ + "AND instrument_uuid = ? FOR UPDATE")) {
+ instrumentLock.setObject(1, paid.hosting().instrument().accountUuid());
+ instrumentLock.setObject(2, paid.hosting().instrument().instrumentUuid());
+ try (ResultSet instrument = instrumentLock.executeQuery()) {
+ assertThat(instrument.next()).isTrue();
+ }
+ }
+
+ Future phase = executor.submit(admissionPhase);
+ int blockedPid = awaitBackendBlockedBy(caller.dsl, blockerPid, 3, TimeUnit.SECONDS);
+ assertThat(blockedPid).isPositive().isNotEqualTo(blockerPid);
+ assertTenantGenerationCanBeLocked(caller.dataSource, paid.hosting().tenantId());
+ blocker.rollback();
+ return phase.get(5, TimeUnit.SECONDS);
+ } finally {
+ executor.shutdown();
+ if (!executor.awaitTermination(5, TimeUnit.SECONDS)) executor.shutdownNow();
+ }
+ }
+
+ private static void assertTenantGenerationCanBeLocked(DataSource dataSource, UUID tenantId)
+ throws SQLException {
+ try (Connection probe = dataSource.getConnection()) {
+ probe.setAutoCommit(false);
+ try (PreparedStatement lock =
+ probe.prepareStatement(
+ "SELECT generation FROM account_authority_generations WHERE scope_kind = 'TENANT' "
+ + "AND issuer_id IS NULL AND account_uuid IS NULL AND tenant_uuid = ? "
+ + "FOR UPDATE NOWAIT")) {
+ lock.setObject(1, tenantId);
+ try (ResultSet row = lock.executeQuery()) {
+ assertThat(row.next()).isTrue();
+ }
+ } finally {
+ probe.rollback();
+ }
+ }
+ }
+
private static DataSource holdOriginalCommitBeforePhysicalCommit(
DataSource delegate,
CountDownLatch commitReached,
@@ -1766,6 +2410,25 @@ private static Candidate candidateWithAccount(Candidate candidate, UUID accountI
candidate.issuerIndexPartitionCapacity());
}
+ private static Candidate candidateWithTenant(Candidate candidate, UUID tenantId) {
+ return new Candidate(
+ candidate.accountId(),
+ tenantId,
+ candidate.playableStateNamespaceId(),
+ candidate.characterId(),
+ candidate.playableStateScope(),
+ candidate.gameInstanceId(),
+ candidate.runtimeGameInstanceId(),
+ candidate.sessionId(),
+ candidate.regionId(),
+ candidate.regionEpoch(),
+ candidate.issuerId(),
+ candidate.issuerAuthGeneration(),
+ candidate.issuerIndexLayoutVersion(),
+ candidate.issuerIndexPartitionCount(),
+ candidate.issuerIndexPartitionCapacity());
+ }
+
private static Target admissionTarget(Candidate candidate, UUID requestId) {
UUID realmId = UUID.randomUUID();
UUID versionId = UUID.randomUUID();
@@ -2465,6 +3128,19 @@ private CommittedCandidateVerificationData createCommittedIssuanceCandidate(
private AccountGameplayAdmissionCurrentSources.Current readCurrent(
CommittedCandidateVerificationData expectedCandidate) {
+ return inCurrentSources(sources ->
+ sources.readCurrentPublicProductionNew(
+ tenantUuid, expectedCandidate.identity().tokenJti(), expectedCandidate));
+ }
+
+ private T inCurrentSources(
+ java.util.function.Function read) {
+ return inCurrentSources(read, null);
+ }
+
+ private T inCurrentSources(
+ java.util.function.Function read,
+ ExecuteListener listener) {
return serializable.execute(status -> {
if (!TransactionSynchronizationManager.isActualTransactionActive()
|| TransactionSynchronizationManager.isCurrentTransactionReadOnly()
@@ -2477,14 +3153,16 @@ private AccountGameplayAdmissionCurrentSources.Current readCurrent(
throw new IllegalStateException("Expected the manager-enlisted Account connection");
}
Connection connection = holder.getConnection();
- DSLContext exactDsl = DSL.using(connection, SQLDialect.POSTGRES);
+ DSLContext boundDsl = DSL.using(connection, SQLDialect.POSTGRES);
+ DSLContext exactDsl =
+ listener == null
+ ? boundDsl
+ : DSL.using(boundDsl.configuration().deriveAppending(listener));
try {
Integer backendBefore =
exactDsl.fetchSingle("SELECT pg_backend_pid()").get(0, Integer.class);
- var current =
- AccountGameplayAdmissionCurrentSources.bind(exactDsl, TEST_NAMESPACE)
- .readCurrentPublicProductionNew(
- tenantUuid, expectedCandidate.identity().tokenJti(), expectedCandidate);
+ T current =
+ read.apply(AccountGameplayAdmissionCurrentSources.bind(exactDsl, TEST_NAMESPACE));
Integer backendAfter =
exactDsl.fetchSingle("SELECT pg_backend_pid()").get(0, Integer.class);
assertThat(backendAfter).isEqualTo(backendBefore);
@@ -2523,10 +3201,16 @@ private AccountGameplayAdmissionLeaseEvidence beginPendingAdmissionLease(
carrier.put("leaseId", allocation.leaseId().toString());
carrier.put("leaseFence", Long.toString(allocation.leaseFence()));
carrier.put("leaseKind", "NEW_BINDING");
- carrier.put("bindingScope", bindingScope());
+ Map scope = new LinkedHashMap<>(bindingScope());
+ scope.put("tenantId", current.snapshot().tenantId());
+ carrier.put("bindingScope", scope);
carrier.putAll(current.leaseSourceFields());
carrier.put("evaluatedAt", Long.toString(evaluatedAt));
- carrier.put("expiresAt", Long.toString(evaluatedAt + 14_000L));
+ long expiry = evaluatedAt + 14_000L;
+ if (current.sourceValidUntilMs() != null) {
+ expiry = Math.min(expiry, current.sourceValidUntilMs());
+ }
+ carrier.put("expiresAt", Long.toString(expiry));
var evidence = AccountGameplayAdmissionLeaseEvidence.fromCarrier(carrier);
leases.beginPending(evidence);
return evidence;
diff --git a/services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/repository/AccountOriginalNewBoundGameplayCredentialOwnerIntegrationTest.java b/services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/repository/AccountOriginalNewBoundGameplayCredentialOwnerIntegrationTest.java
index 8887995142..3d12eec740 100644
--- a/services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/repository/AccountOriginalNewBoundGameplayCredentialOwnerIntegrationTest.java
+++ b/services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/repository/AccountOriginalNewBoundGameplayCredentialOwnerIntegrationTest.java
@@ -12,6 +12,8 @@
import java.nio.file.Path;
import java.security.MessageDigest;
import java.time.Clock;
+import java.time.Instant;
+import java.time.ZoneId;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Base64;
@@ -86,6 +88,7 @@ class AccountOriginalNewBoundGameplayCredentialOwnerIntegrationTest {
@TempDir Path temporaryDirectory;
private AccountGameplayAdmissionCurrentSourcesPostgresIntegrationTest fixtureHarness;
private AccountGameplayAdmissionCurrentSourcesPostgresIntegrationTest.Fixture sourceFixture;
+ private AccountGameplayAdmissionCurrentSourcesPostgresIntegrationTest.PaidFixture paidFixture;
private AccountGameplayAdmissionCurrentSourcesPostgresIntegrationTest.PhysicalRedisFixture
redisFixture;
@@ -103,6 +106,7 @@ static void stopPostgres() {
void createActualSourceFixture() throws Exception {
fixtureHarness = new AccountGameplayAdmissionCurrentSourcesPostgresIntegrationTest();
fixtureHarness.temporaryDirectory = temporaryDirectory;
+ paidFixture = null;
redisFixture =
AccountGameplayAdmissionCurrentSourcesPostgresIntegrationTest.PhysicalRedisFixture.start();
sourceFixture = fixtureHarness.newFixture(redisFixture.client());
@@ -124,7 +128,83 @@ void loginCallerRevokedDuringFinalReadCannotActivateThePendingCredential() throw
exerciseFinalConfirmation(true);
}
+ @Test
+ void paidHostingSourceIsObservedOutsideSqlForIssueAndConfirmation() throws Exception {
+ paidFixture = fixtureHarness.newPaidFixture(redisFixture.client());
+ sourceFixture = paidFixture.caller();
+ exerciseFinalConfirmation(false);
+ }
+
+ @Test
+ void paidSourceHeadChangeDuringObservationRefusesOriginalCredentialIssuance() throws Exception {
+ paidFixture = fixtureHarness.newPaidFixture(redisFixture.client());
+ sourceFixture = paidFixture.caller();
+ exerciseFinalConfirmation(false, true);
+ }
+
+ @Test
+ void paidConfirmationWithElapsedContinuityLeavesRegistryPending() throws Exception {
+ paidFixture = fixtureHarness.newPaidFixture(redisFixture.client());
+ sourceFixture = paidFixture.caller();
+ exerciseFinalConfirmation(false, false, true);
+ }
+
+ @Test
+ void paidIssuanceWithCallerExpiringDuringCommitObservationLeavesGenesisPending()
+ throws Exception {
+ paidFixture = fixtureHarness.newPaidFixture(redisFixture.client());
+ sourceFixture = paidFixture.caller();
+ exerciseFinalConfirmation(false, false, false, true);
+ }
+
private void exerciseFinalConfirmation(boolean revokeCallerDuringFinalRead) throws Exception {
+ exerciseFinalConfirmation(revokeCallerDuringFinalRead, false);
+ }
+
+ private void exerciseFinalConfirmation(
+ boolean revokeCallerDuringFinalRead, boolean changePaidSourceDuringObservation)
+ throws Exception {
+ exerciseFinalConfirmation(
+ revokeCallerDuringFinalRead, changePaidSourceDuringObservation, false);
+ }
+
+ private void exerciseFinalConfirmation(
+ boolean revokeCallerDuringFinalRead,
+ boolean changePaidSourceDuringObservation,
+ boolean expireContinuityDuringConfirmationObservation)
+ throws Exception {
+ exerciseFinalConfirmation(
+ revokeCallerDuringFinalRead,
+ changePaidSourceDuringObservation,
+ expireContinuityDuringConfirmationObservation,
+ false);
+ }
+
+ private void exerciseFinalConfirmation(
+ boolean revokeCallerDuringFinalRead,
+ boolean changePaidSourceDuringObservation,
+ boolean expireContinuityDuringConfirmationObservation,
+ boolean expireCallerDuringIssuanceObservation)
+ throws Exception {
+ AtomicReference selectedOwnerClock = new AtomicReference<>(Clock.systemUTC());
+ Clock ownerClock =
+ new Clock() {
+ @Override
+ public ZoneId getZone() {
+ return selectedOwnerClock.get().getZone();
+ }
+
+ @Override
+ public Clock withZone(ZoneId zone) {
+ return selectedOwnerClock.get().withZone(zone);
+ }
+
+ @Override
+ public Instant instant() {
+ return selectedOwnerClock.get().instant();
+ }
+ };
+ AtomicInteger continuityAdvances = new AtomicInteger();
DSLContext dsl =
DSL.using(
new TransactionAwareDataSourceProxy(sourceFixture.dataSource), SQLDialect.POSTGRES);
@@ -190,6 +270,26 @@ private void exerciseFinalConfirmation(boolean revokeCallerDuringFinalRead) thro
when(readback.canonicalSessionDurationMillis()).thenReturn(SESSION_DURATION_MILLIS);
when(readback.canonicalReadbackSha256()).thenReturn("f".repeat(64));
finalReadResults.add(readback);
+ if (expireContinuityDuringConfirmationObservation) {
+ selectedOwnerClock.set(
+ Clock.fixed(
+ Instant.ofEpochMilli(controlledAdmissionAtMillis + 1), ZoneId.of("UTC")));
+ paidFixture
+ .hosting()
+ .transport()
+ .duringRead(() -> {
+ assertThat(
+ org.springframework.transaction.support.TransactionSynchronizationManager
+ .isActualTransactionActive())
+ .isFalse();
+ selectedOwnerClock.set(
+ Clock.fixed(
+ Instant.ofEpochMilli(
+ controlledAdmissionAtMillis + SESSION_DURATION_MILLIS),
+ ZoneId.of("UTC")));
+ continuityAdvances.incrementAndGet();
+ });
+ }
if (revokeCallerDuringFinalRead) {
// The normal revocation owner lawfully changes the genuine LOGIN identity fence
// after Account began its reverse read, without changing the original NEW lineage.
@@ -218,19 +318,32 @@ private void exerciseFinalConfirmation(boolean revokeCallerDuringFinalRead) thro
}
return readback;
};
+ var callerVerifier =
+ new AccountGameplayAdmissionCallerVerifier(
+ sourceFixture.signerFixture.trustedJwksSource(),
+ sourceFixture.committedIssuanceOwner,
+ Clock.systemUTC());
var owner =
- new AccountOriginalNewBoundGameplayCredentialOwner(
- sourceFixture.dataSource,
- NAMESPACE,
- new AccountGameplayAdmissionCallerVerifier(
- sourceFixture.signerFixture.trustedJwksSource(),
- sourceFixture.committedIssuanceOwner,
- Clock.systemUTC()),
- sourceFixture.signerFixture.signer(),
- tokenRegistry,
- responseCryptography,
- Clock.systemUTC(),
- controlledFinalReadback);
+ paidFixture == null
+ ? new AccountOriginalNewBoundGameplayCredentialOwner(
+ sourceFixture.dataSource,
+ NAMESPACE,
+ callerVerifier,
+ sourceFixture.signerFixture.signer(),
+ tokenRegistry,
+ responseCryptography,
+ ownerClock,
+ controlledFinalReadback)
+ : new AccountOriginalNewBoundGameplayCredentialOwner(
+ sourceFixture.dataSource,
+ NAMESPACE,
+ callerVerifier,
+ sourceFixture.signerFixture.signer(),
+ tokenRegistry,
+ responseCryptography,
+ ownerClock,
+ controlledFinalReadback,
+ paidFixture.hosting().admissionPaidSource());
GrpcPeerIdentity peer = GrpcPeerIdentity.parseUri(GAME_SESSION_WORKLOAD).orElseThrow();
AccountGameplayAdmissionLeaseEvidence originalLease =
commitActualOriginalNewLease(dsl, serializable);
@@ -244,16 +357,68 @@ private void exerciseFinalConfirmation(boolean revokeCallerDuringFinalRead) thro
if (originalDecisionId == null) throw new IllegalStateException("Original decision is absent");
String originalEvidenceSha256 = originalLease.sha256();
+ if (changePaidSourceDuringObservation) {
+ paidFixture.hosting().transport().duringRead(paidFixture::refresh);
+ assertThatThrownBy(() ->
+ Context.current()
+ .withValue(GrpcPeerIdentity.CONTEXT_KEY, peer)
+ .call(() -> owner.issue(loginJwt, originalLease)))
+ .isInstanceOf(AccountSubscriptionIntentRepository.FenceRejectedException.class);
+ assertThat(dsl.fetchCount(DSL.table("account_original_new_bound_gameplay_issuances")))
+ .isZero();
+ assertThat(finalReadCalls.get()).isZero();
+ assertOriginalLeaseAndAckRemainExact(dsl, originalLease, originalEvidenceSha256);
+ return;
+ }
+
+ if (expireCallerDuringIssuanceObservation) {
+ var issuances = DSL.table("account_original_new_bound_gameplay_issuances");
+ var committedIssuances = DSL.field("status", String.class).eq("COMMITTED");
+ var identityFences = DSL.table("account_gameplay_token_identity_fences");
+ int committedCount = dsl.fetchCount(issuances, committedIssuances);
+ int fenceCount = dsl.fetchCount(identityFences);
+ var transport = paidFixture.hosting().transport();
+ int before = transport.reads();
+ Instant callerExpiry = Instant.ofEpochSecond(initialIdentity.expiresAtEpochSecond());
+ // Let the initial source read and signed-candidate binding finish before advancing time.
+ transport.duringRead(() ->
+ transport.duringRead(() ->
+ transport.duringRead(
+ () -> selectedOwnerClock.set(Clock.fixed(callerExpiry, ZoneId.of("UTC"))))));
+
+ assertThatThrownBy(() ->
+ Context.current()
+ .withValue(GrpcPeerIdentity.CONTEXT_KEY, peer)
+ .call(() -> owner.issue(loginJwt, originalLease)))
+ .isInstanceOf(IllegalStateException.class)
+ .hasMessage("Original-new bound gameplay credential is unavailable");
+ assertPaidObservationReadsSince(before, 3);
+ assertThat(ownerClock.instant()).isEqualTo(callerExpiry);
+ assertThat(dsl.fetchCount(issuances, committedIssuances)).isEqualTo(committedCount);
+ assertThat(dsl.fetchCount(identityFences)).isEqualTo(fenceCount);
+ Genesis pending = readGenesis(dsl, serializable, originalLease);
+ assertThat(pending.status())
+ .isEqualTo(AccountOriginalNewBoundGameplayIssuanceRepository.Status.PENDING);
+ assertThat(pending.tokenHash()).isNotNull();
+ assertThat(pending.committedRegistryReceiptSha256()).isNull();
+ assertThat(finalReadCalls.get()).isZero();
+ assertOriginalLeaseAndAckRemainExact(dsl, originalLease, originalEvidenceSha256);
+ return;
+ }
+
OriginalNewCredential first =
Context.current()
.withValue(GrpcPeerIdentity.CONTEXT_KEY, peer)
.call(() -> owner.issue(loginJwt, originalLease));
+ int paidReadsBeforeCommittedRetry = paidObservationReads();
OriginalNewCredential lostReplyRetry =
Context.current()
.withValue(GrpcPeerIdentity.CONTEXT_KEY, peer)
.call(() -> owner.issue(loginJwt, originalLease));
try (first;
lostReplyRetry) {
+ // Current source, issuance fence, and a single source for opening the committed result.
+ assertPaidObservationReadsSince(paidReadsBeforeCommittedRetry, 3);
Genesis committed = readGenesis(dsl, serializable, originalLease);
byte[] firstHandle = first.opaqueRebindHandle();
byte[] retryHandle = lostReplyRetry.opaqueRebindHandle();
@@ -323,6 +488,24 @@ private void exerciseFinalConfirmation(boolean revokeCallerDuringFinalRead) thro
Math.addExact(
Math.multiplyExact(committed.expiresAtEpochSecond(), 1_000L),
REDIS_CLEANUP_MARGIN_MILLIS);
+ if (expireContinuityDuringConfirmationObservation) {
+ String before = issuancePhysicalImage(dsl);
+ assertFinalConfirmationUnavailable(owner, peer, loginJwt, originalLease);
+ assertThat(finalReadCalls.get()).isOne();
+ assertThat(continuityAdvances.get()).isOne();
+ assertUnconfirmed(dsl, serializable, originalLease);
+ byte[] expectedPending = committed.pendingRegistryRecordBytes();
+ try {
+ redisFixture
+ .client()
+ .requirePendingRecord(committed.tokenHash(), expectedPending, exactRedisExpiryMillis);
+ } finally {
+ Arrays.fill(expectedPending, (byte) 0);
+ }
+ assertThat(issuancePhysicalImage(dsl)).isEqualTo(before);
+ assertOriginalLeaseAndAckRemainExact(dsl, originalLease, originalEvidenceSha256);
+ return;
+ }
if (revokeCallerDuringFinalRead) {
String issuanceBefore =
dsl.fetchSingle(
@@ -433,7 +616,10 @@ private void exerciseFinalConfirmation(boolean revokeCallerDuringFinalRead) thro
// ACTIVE Redis state cannot substitute for a new authenticated Game Session final read.
finalReadMode.set(FinalReadMode.CHANGED);
+ int paidReadsBeforeChangedFinal = paidObservationReads();
assertFinalConfirmationUnavailable(owner, peer, loginJwt, originalLease);
+ // Refusal happens after the same single frozen-credential open, before another paid read.
+ assertPaidObservationReadsSince(paidReadsBeforeChangedFinal, 3);
Genesis afterChangedRead = assertUnconfirmed(dsl, serializable, originalLease);
assertSameActiveRegistryReadback(
activeAfterLostConfirmation,
@@ -449,7 +635,10 @@ private void exerciseFinalConfirmation(boolean revokeCallerDuringFinalRead) thro
// Recovery makes a fresh read of the same controlled final result and confirms the same
// frozen lineage, token, anchors, continuity deadline, and physical registry expiry.
finalReadMode.set(FinalReadMode.EXACT);
+ int paidReadsBeforeExactFinal = paidObservationReads();
var confirmed = confirm(owner, peer, loginJwt, originalLease);
+ // Early source, genesis, frozen-credential open, preactivation, and final confirmation.
+ assertPaidObservationReadsSince(paidReadsBeforeExactFinal, 5);
assertThat(confirmed.lineageId()).isEqualTo(first.lineageId());
assertThat(confirmed.originalLeaseId())
.isEqualTo(UUID.fromString((String) originalLease.carrier().get("leaseId")));
@@ -524,83 +713,78 @@ private void exerciseFinalConfirmation(boolean revokeCallerDuringFinalRead) thro
assertThat(finalReadCalls.get()).isEqualTo(4);
}
assertOriginalLeaseAndAckRemainExact(dsl, originalLease, originalEvidenceSha256);
+ if (paidFixture != null) {
+ var transport = paidFixture.hosting().transport();
+ int before = transport.reads();
+ var observationsAtRefresh = new AtomicInteger();
+ String issuanceBefore = issuancePhysicalImage(dsl);
+ // Only change the paid source at the committed credential open, after the earlier
+ // current-source and issuance-fence reads succeeded.
+ transport.duringRead(() ->
+ transport.duringRead(() ->
+ transport.duringRead(() -> {
+ observationsAtRefresh.set(transport.reads() - before);
+ paidFixture.refresh();
+ })));
+ assertThatThrownBy(() ->
+ Context.current()
+ .withValue(GrpcPeerIdentity.CONTEXT_KEY, peer)
+ .call(() -> owner.issue(loginJwt, originalLease)))
+ .isInstanceOf(AccountSubscriptionIntentRepository.FenceRejectedException.class);
+ assertThat(observationsAtRefresh.get()).isEqualTo(3);
+ assertThat(issuancePhysicalImage(dsl)).isEqualTo(issuanceBefore);
+ assertOriginalLeaseAndAckRemainExact(dsl, originalLease, originalEvidenceSha256);
+ }
}
}
+ private int paidObservationReads() {
+ return paidFixture == null ? 0 : paidFixture.hosting().transport().reads();
+ }
+
+ private void assertPaidObservationReadsSince(int prior, int expectedPaid) {
+ assertThat(paidObservationReads() - prior).isEqualTo(paidFixture == null ? 0 : expectedPaid);
+ }
+
private AccountGameplayAdmissionLeaseEvidence commitActualOriginalNewLease(
DSLContext dsl, TransactionTemplate serializable) {
UUID accountId = sourceFixture.committedCandidate.identity().accountId();
- UUID tenantId =
- dsl.fetchSingle(
- "SELECT membership.tenant_uuid FROM account_tenant_membership membership "
- + "JOIN accounts account ON account.id = membership.account_id "
- + "WHERE account.account_uuid = ? AND membership.tenant_uuid IS NOT NULL",
- accountId)
- .get(0, UUID.class);
- if (tenantId == null)
- throw new IllegalStateException("Current-source fixture tenant is absent");
-
- AccountGameplayAdmissionLeaseEvidence evidence =
- serializable.execute(status -> {
- var current =
- AccountGameplayAdmissionCurrentSources.bind(dsl, NAMESPACE)
- .readCurrentPublicProductionNew(
- tenantId,
- sourceFixture.committedCandidate.identity().tokenJti(),
- sourceFixture.committedCandidate);
- UUID requestId = UUID.randomUUID();
- UUID leaseId = UUID.randomUUID();
- var leaseRepository = new AccountGameplayAdmissionLeaseRepository(dsl);
- var allocation = leaseRepository.allocate(accountId, requestId, leaseId);
- long evaluatedAt =
- dsl.fetchSingle("SELECT floor(extract(epoch FROM clock_timestamp()) * 1000)::bigint")
- .get(0, Long.class);
- long maxLeaseExpiry =
- Math.addExact(evaluatedAt, AccountGameplayAdmissionLeaseEvidence.MAX_DURATION_MILLIS);
- long initialTokenExpiry =
- Math.multiplyExact(
- sourceFixture.committedCandidate.identity().expiresAtEpochSecond(), 1_000L);
- Map carrier = new LinkedHashMap<>();
- carrier.put("schema", AccountGameplayAdmissionLeaseEvidence.SCHEMA);
- carrier.put("schemaVersion", "1");
- carrier.put("mode", "PUBLIC_PRODUCTION");
- carrier.put("targetNamespace", NAMESPACE);
- carrier.put("callerWorkload", GAME_SESSION_WORKLOAD);
- carrier.put("requestId", allocation.requestId().toString());
- carrier.put("leaseId", allocation.leaseId().toString());
- carrier.put("leaseFence", Long.toString(allocation.leaseFence()));
- carrier.put("leaseKind", "NEW_BINDING");
- carrier.put(
- "bindingScope",
- Map.ofEntries(
- Map.entry("accountId", accountId.toString()),
- Map.entry("tenantId", tenantId.toString()),
- Map.entry("realmId", UUID.randomUUID().toString()),
- Map.entry("worldSlug", "world"),
- Map.entry("realmSlug", "realm"),
- Map.entry("playableStateNamespaceId", UUID.randomUUID().toString()),
- Map.entry("playableStateScope", "SHARED"),
- Map.entry("gameInstanceId", UUID.randomUUID().toString()),
- Map.entry("characterId", UUID.randomUUID().toString()),
- Map.entry("sessionId", UUID.randomUUID().toString()),
- Map.entry("bindingGeneration", "1"),
- Map.entry("catalogRevision", "1"),
- Map.entry("pointerVersion", "1"),
- Map.entry("regionId", UUID.randomUUID().toString()),
- Map.entry("regionEpoch", "1")));
- carrier.putAll(current.leaseSourceFields());
- carrier.put("evaluatedAt", Long.toString(evaluatedAt));
- carrier.put("expiresAt", Long.toString(Math.min(maxLeaseExpiry, initialTokenExpiry)));
- var originalLease = AccountGameplayAdmissionLeaseEvidence.fromCarrier(carrier);
- leaseRepository.beginPending(originalLease);
- return originalLease;
- });
+ AccountGameplayAdmissionLeaseEvidence evidence;
+ if (paidFixture == null) {
+ UUID tenantId =
+ dsl.fetchSingle(
+ "SELECT membership.tenant_uuid FROM account_tenant_membership membership "
+ + "JOIN accounts account ON account.id = membership.account_id "
+ + "WHERE account.account_uuid = ? AND membership.tenant_uuid IS NOT NULL",
+ accountId)
+ .get(0, UUID.class);
+ if (tenantId == null)
+ throw new IllegalStateException("Current-source fixture tenant is absent");
+
+ evidence =
+ serializable.execute(status -> {
+ var current =
+ AccountGameplayAdmissionCurrentSources.bind(dsl, NAMESPACE)
+ .readCurrentPublicProductionNew(
+ tenantId,
+ sourceFixture.committedCandidate.identity().tokenJti(),
+ sourceFixture.committedCandidate);
+ return beginPendingLease(dsl, accountId, tenantId, current);
+ });
+ } else {
+ var observed = paidFixture.prepare().observeOutsideSql();
+ var current = paidFixture.read(observed);
+ UUID tenantId = paidFixture.hosting().tenantId();
+ evidence =
+ serializable.execute(status -> beginPendingLease(dsl, accountId, tenantId, current));
+ }
UUID decisionId = UUID.randomUUID();
+ var paidObservation = paidFixture == null ? null : paidFixture.prepare().observeOutsideSql();
var acknowledgement =
new AccountGameplayAdmissionOriginalCommitExecutor(sourceFixture.dataSource)
.executeWithCurrentSources(
- evidence, decisionId, NAMESPACE, sourceFixture.committedCandidate);
+ evidence, decisionId, NAMESPACE, sourceFixture.committedCandidate, paidObservation);
var receipt =
new AccountGameplayAdmissionOriginalAckReceiptCommitExecutor(sourceFixture.dataSource)
.confirm(acknowledgement);
@@ -609,6 +793,70 @@ private AccountGameplayAdmissionLeaseEvidence commitActualOriginalNewLease(
return evidence;
}
+ private AccountGameplayAdmissionLeaseEvidence beginPendingLease(
+ DSLContext dsl,
+ UUID accountId,
+ UUID tenantId,
+ AccountGameplayAdmissionCurrentSources.Current current) {
+ UUID requestId = UUID.randomUUID();
+ UUID leaseId = UUID.randomUUID();
+ var leaseRepository = new AccountGameplayAdmissionLeaseRepository(dsl);
+ var allocation = leaseRepository.allocate(accountId, requestId, leaseId);
+ long evaluatedAt =
+ dsl.fetchSingle("SELECT floor(extract(epoch FROM clock_timestamp()) * 1000)::bigint")
+ .get(0, Long.class);
+ long maxLeaseExpiry =
+ Math.addExact(evaluatedAt, AccountGameplayAdmissionLeaseEvidence.MAX_DURATION_MILLIS);
+ long initialTokenExpiry =
+ Math.multiplyExact(
+ sourceFixture.committedCandidate.identity().expiresAtEpochSecond(), 1_000L);
+ Map carrier = new LinkedHashMap<>();
+ carrier.put("schema", AccountGameplayAdmissionLeaseEvidence.SCHEMA);
+ carrier.put("schemaVersion", "1");
+ carrier.put("mode", "PUBLIC_PRODUCTION");
+ carrier.put("targetNamespace", NAMESPACE);
+ carrier.put("callerWorkload", GAME_SESSION_WORKLOAD);
+ carrier.put("requestId", allocation.requestId().toString());
+ carrier.put("leaseId", allocation.leaseId().toString());
+ carrier.put("leaseFence", Long.toString(allocation.leaseFence()));
+ carrier.put("leaseKind", "NEW_BINDING");
+ carrier.put(
+ "bindingScope",
+ Map.ofEntries(
+ Map.entry("accountId", accountId.toString()),
+ Map.entry("tenantId", tenantId.toString()),
+ Map.entry("realmId", UUID.randomUUID().toString()),
+ Map.entry("worldSlug", "world"),
+ Map.entry("realmSlug", "realm"),
+ Map.entry("playableStateNamespaceId", UUID.randomUUID().toString()),
+ Map.entry("playableStateScope", "SHARED"),
+ Map.entry("gameInstanceId", UUID.randomUUID().toString()),
+ Map.entry("characterId", UUID.randomUUID().toString()),
+ Map.entry("sessionId", UUID.randomUUID().toString()),
+ Map.entry("bindingGeneration", "1"),
+ Map.entry("catalogRevision", "1"),
+ Map.entry("pointerVersion", "1"),
+ Map.entry("regionId", UUID.randomUUID().toString()),
+ Map.entry("regionEpoch", "1")));
+ carrier.putAll(current.leaseSourceFields());
+ carrier.put("evaluatedAt", Long.toString(evaluatedAt));
+ long expiry = Math.min(maxLeaseExpiry, initialTokenExpiry);
+ if (current.sourceValidUntilMs() != null) {
+ expiry = Math.min(expiry, current.sourceValidUntilMs());
+ }
+ carrier.put("expiresAt", Long.toString(expiry));
+ var originalLease = AccountGameplayAdmissionLeaseEvidence.fromCarrier(carrier);
+ leaseRepository.beginPending(originalLease);
+ return originalLease;
+ }
+
+ private static String issuancePhysicalImage(DSLContext dsl) {
+ return dsl.fetchSingle(
+ "SELECT xmin::text || ':' || to_jsonb(issuance)::text"
+ + " FROM account_original_new_bound_gameplay_issuances issuance")
+ .get(0, String.class);
+ }
+
private static Genesis readGenesis(
DSLContext dsl,
TransactionTemplate transaction,
diff --git a/services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/repository/CanonicalHostingSubscriptionTestFixture.java b/services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/repository/CanonicalHostingSubscriptionTestFixture.java
index f283905ab6..69fb91a1b5 100644
--- a/services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/repository/CanonicalHostingSubscriptionTestFixture.java
+++ b/services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/repository/CanonicalHostingSubscriptionTestFixture.java
@@ -51,6 +51,7 @@
import net.firedevops.firemud.accountservice.repository.AccountBillingCustomerRecord;
import net.firedevops.firemud.accountservice.repository.AccountBillingCustomerRepository;
import net.firedevops.firemud.accountservice.repository.AccountEmailLoginChallengeRepository;
+import net.firedevops.firemud.accountservice.repository.AccountGameplayAdmissionPaidSource;
import net.firedevops.firemud.accountservice.repository.AccountHostingFirstInvoicePayment;
import net.firedevops.firemud.accountservice.repository.AccountHostingFirstInvoicePaymentRepository;
import net.firedevops.firemud.accountservice.repository.AccountHostingPlanCatalog;
@@ -117,22 +118,36 @@ public final class CanonicalHostingSubscriptionTestFixture {
private CanonicalHostingSubscriptionTestFixture() {}
public static Fixture create(DataSource source) {
- return createInternal(source, null, "prod");
+ return createInternal(source, null, "prod", null);
}
/** Uses the caller's explicit workload namespace without changing controlled source custody. */
public static Fixture create(DataSource source, String namespace) {
- return createInternal(source, null, namespace);
+ return createInternal(source, null, namespace, null);
}
/** Reuses the exact persisted Account of a genuine actor/authentication composition. */
public static Fixture create(DataSource source, Account account) {
return createInternal(
- source, Objects.requireNonNull(account, "persisted Account required"), "prod");
+ source, Objects.requireNonNull(account, "persisted Account required"), "prod", null);
+ }
+
+ /** Seeds paid receipt state for the exact tenant carried by a separate test composition. */
+ public static Fixture createForExistingTenant(
+ DataSource source, Account account, FreshTenantCreationEvidence tenantSource) {
+ Objects.requireNonNull(tenantSource, "exact fixture tenant evidence required");
+ return createInternal(
+ source,
+ Objects.requireNonNull(account, "persisted Account required"),
+ tenantSource.targetNamespace(),
+ tenantSource);
}
private static Fixture createInternal(
- DataSource source, Account existingAccount, String namespace) {
+ DataSource source,
+ Account existingAccount,
+ String namespace,
+ FreshTenantCreationEvidence existingTenantSource) {
Objects.requireNonNull(source, "migrated Account datasource is required");
JdbcTemplate jdbc = new JdbcTemplate(source);
DSLContext dsl = DSL.using(new TransactionAwareDataSourceProxy(source), SQLDialect.POSTGRES);
@@ -158,33 +173,9 @@ private static Fixture createInternal(
long accountId = accountRow.get("id", Long.class);
UUID accountUuid = accountRow.get("account_uuid", UUID.class);
- UUID tenantId = UUID.randomUUID();
- UUID tenantCreateRequest = UUID.randomUUID();
- UUID tenantCreateOperation = UUID.randomUUID();
- String tenantKey = "hosting-fixture-game-" + row;
- String tenantRequestDigest =
- GameTenantCreationDigest.requestDigest(
- namespace, tenantCreateRequest, tenantKey, "Controlled hosting", "Storage only");
var tenantSource =
- new FreshTenantCreationEvidence(
- 1,
- namespace,
- tenantCreateRequest,
- tenantCreateOperation,
- tenantRequestDigest,
- tenantId,
- row,
- tenantKey,
- "NEW_GAME_ROW",
- GameTenantCreationDigest.evidenceDigest(
- namespace,
- tenantCreateRequest,
- tenantCreateOperation,
- tenantRequestDigest,
- tenantId,
- row,
- tenantKey,
- "NEW_GAME_ROW"));
+ existingTenantSource == null ? freshTenantSource(namespace, row) : existingTenantSource;
+ UUID tenantId = tenantSource.canonicalTenantId();
in(
transaction,
() -> {
@@ -314,12 +305,43 @@ private static Fixture createInternal(
service,
lifecycleRepository,
observer,
+ new AccountGameplayAdmissionPaidSource(
+ catalog, clock, Duration.ofSeconds(1), limits, policy, observer, namespace, false),
source);
fixture.providerStatus("active");
return fixture;
}
/** Separate factory for protected HTTPS owner tests that supply their own genuine actor. */
+ private static FreshTenantCreationEvidence freshTenantSource(String namespace, long row) {
+ UUID tenantId = UUID.randomUUID();
+ UUID tenantCreateRequest = UUID.randomUUID();
+ UUID tenantCreateOperation = UUID.randomUUID();
+ String tenantKey = "hosting-fixture-game-" + row;
+ String tenantRequestDigest =
+ GameTenantCreationDigest.requestDigest(
+ namespace, tenantCreateRequest, tenantKey, "Controlled hosting", "Storage only");
+ return new FreshTenantCreationEvidence(
+ 1,
+ namespace,
+ tenantCreateRequest,
+ tenantCreateOperation,
+ tenantRequestDigest,
+ tenantId,
+ row,
+ tenantKey,
+ "NEW_GAME_ROW",
+ GameTenantCreationDigest.evidenceDigest(
+ namespace,
+ tenantCreateRequest,
+ tenantCreateOperation,
+ tenantRequestDigest,
+ tenantId,
+ row,
+ tenantKey,
+ "NEW_GAME_ROW"));
+ }
+
public static Fixture createAwaitingPayment(
DataSource source, Account account, Path checkoutDirectory) {
var fixture = create(source, account);
@@ -999,6 +1021,7 @@ public static final class Fixture {
private final AccountHostingSubscriptionLifecycleService service;
private final AccountHostingSubscriptionLifecycleRepository lifecycleRepository;
private final StripeHostingSubscriptionObserver observer;
+ private final AccountGameplayAdmissionPaidSource admissionPaidSource;
private final DataSource source;
private FirstInvoiceCheckout checkout;
private Path checkoutDirectory;
@@ -1020,6 +1043,7 @@ private Fixture(
AccountHostingSubscriptionLifecycleService service,
AccountHostingSubscriptionLifecycleRepository lifecycleRepository,
StripeHostingSubscriptionObserver observer,
+ AccountGameplayAdmissionPaidSource admissionPaidSource,
DataSource source) {
this.jdbc = jdbc;
this.dsl = dsl;
@@ -1037,6 +1061,7 @@ private Fixture(
this.service = service;
this.lifecycleRepository = lifecycleRepository;
this.observer = observer;
+ this.admissionPaidSource = admissionPaidSource;
this.source = source;
}
@@ -1117,6 +1142,10 @@ public StripeHostingSubscriptionObserver observer() {
return observer;
}
+ public AccountGameplayAdmissionPaidSource admissionPaidSource() {
+ return admissionPaidSource;
+ }
+
/** Uses a JUnit-owned directory for both successful and partially constructed checkouts. */
public Fixture withCheckoutDirectory(Path directory) {
Objects.requireNonNull(directory, "test-owned checkout directory required");
diff --git a/services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/service/AccountPaidCanonicalFirstJoinPostgresIntegrationTest.java b/services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/service/AccountPaidCanonicalFirstJoinPostgresIntegrationTest.java
index 247d924fe4..512b0b0528 100644
--- a/services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/service/AccountPaidCanonicalFirstJoinPostgresIntegrationTest.java
+++ b/services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/service/AccountPaidCanonicalFirstJoinPostgresIntegrationTest.java
@@ -10,13 +10,21 @@
import integration.net.firedevops.firemud.accountservice.repository.CanonicalHostingSubscriptionTestFixture;
import java.nio.charset.StandardCharsets;
import java.nio.file.Path;
+import java.sql.SQLException;
import java.time.Duration;
+import java.util.ArrayList;
+import java.util.Comparator;
import java.util.List;
import java.util.Map;
import java.util.Objects;
import java.util.Set;
import java.util.UUID;
+import java.util.concurrent.CompletableFuture;
import java.util.concurrent.ConcurrentHashMap;
+import java.util.concurrent.Executors;
+import java.util.concurrent.TimeUnit;
+import java.util.concurrent.locks.LockSupport;
+import javax.sql.DataSource;
import net.firedevops.firemud.accountservice.client.StripeHostingSubscriptionObserver;
import net.firedevops.firemud.accountservice.dto.CanonicalJoinScopeV2;
import net.firedevops.firemud.accountservice.entity.Account;
@@ -43,16 +51,22 @@
import net.firedevops.firemud.accountservice.service.AccountMembershipAuthorityEventProducer;
import net.firedevops.firemud.common.account.authority.MembershipAuthorityEventV1Codec;
import org.flywaydb.core.Flyway;
+import org.jooq.ExecuteListener;
+import org.jooq.SQLDialect;
import org.jooq.impl.DSL;
+import org.jooq.impl.DefaultExecuteListenerProvider;
import org.junit.jupiter.api.AfterAll;
import org.junit.jupiter.api.AfterEach;
import org.junit.jupiter.api.BeforeAll;
import org.junit.jupiter.api.Test;
import org.junit.jupiter.api.io.TempDir;
import org.springframework.jdbc.core.JdbcTemplate;
+import org.springframework.jdbc.datasource.DataSourceTransactionManager;
+import org.springframework.jdbc.datasource.TransactionAwareDataSourceProxy;
import org.springframework.transaction.TransactionDefinition;
import org.springframework.transaction.support.TransactionSynchronization;
import org.springframework.transaction.support.TransactionSynchronizationManager;
+import org.springframework.transaction.support.TransactionTemplate;
/**
* Physical Account transaction and real SDK decoding against a controlled local Stripe transport.
@@ -89,6 +103,141 @@ void dropOwnedSchemas() {
schemas.clear();
}
+ @Test
+ void canonicalJoinLocksAccountPairInSharedOrderAndDeduplicatesSelfPayer() {
+ Context c = context(false);
+ UUID payer = c.hosting.accountUuid();
+ UUID caller = c.scope.accountId();
+ assertThat(caller).isNotEqualTo(payer);
+ var captured = new ArrayList();
+ var configuration =
+ c.hosting
+ .dsl()
+ .configuration()
+ .derive(
+ new DefaultExecuteListenerProvider(
+ ExecuteListener.onExecuteStart(context -> {
+ String sql = context.sql();
+ var query = context.query();
+ if (sql != null
+ && query != null
+ && sql.startsWith(
+ "SELECT account_uuid FROM accounts WHERE account_uuid = ")
+ && sql.endsWith(" FOR UPDATE")) {
+ captured.add((UUID) query.getBindValues().getFirst());
+ }
+ })));
+ var repository = new AccountRepository(configuration.dsl());
+
+ c.hosting
+ .transaction()
+ .executeWithoutResult(
+ status -> repository.lockCanonicalJoinAccounts(c.hosting.tenantId(), caller));
+ assertThat(captured)
+ .containsExactlyElementsOf(List.of(caller, payer).stream().sorted().toList());
+
+ captured.clear();
+ c.hosting
+ .transaction()
+ .executeWithoutResult(
+ status -> repository.lockCanonicalJoinAccounts(c.hosting.tenantId(), payer));
+ assertThat(captured).containsExactly(payer);
+ }
+
+ @Test
+ void orderedPaidHostingReadsDoNotHoldLaterCallerWhileWaitingForEarlierPayer() throws Exception {
+ DataSource source = migratedSource();
+ var dsl = DSL.using(new TransactionAwareDataSourceProxy(source), SQLDialect.POSTGRES);
+ var transaction = new TransactionTemplate(new DataSourceTransactionManager(source));
+ transaction.setIsolationLevel(TransactionDefinition.ISOLATION_SERIALIZABLE);
+ var accounts = new AccountRepository(dsl);
+ var candidates =
+ new ArrayList<>(
+ List.of(
+ CanonicalHostingSubscriptionTestFixture.createBillingAccount(dsl, transaction),
+ CanonicalHostingSubscriptionTestFixture.createBillingAccount(dsl, transaction)));
+ candidates.sort(Comparator.comparing(Account::getAccountUuid));
+ Account earlierPayer = candidates.getFirst();
+ UUID payer = earlierPayer.getAccountUuid();
+ UUID caller = candidates.getLast().getAccountUuid();
+ assertThat(payer.compareTo(caller)).isNegative();
+
+ var hosting =
+ CanonicalHostingSubscriptionTestFixture.create(source, earlierPayer)
+ .withCheckoutDirectory(invoiceCheckoutDirectory);
+ assertThat(hosting.completeFirstInvoice().outcome())
+ .isEqualTo(
+ net.firedevops.firemud.accountservice.repository
+ .AccountHostingSubscriptionLifecycleRepository.Outcome.COMMITTED);
+ hosting.transaction().setIsolationLevel(TransactionDefinition.ISOLATION_SERIALIZABLE);
+ UUID tenant = hosting.tenantId();
+ var lifecycle = hosting.lifecycleRepository();
+ ReadFence fence = transaction.execute(status -> lifecycle.prepareCurrentRead(tenant));
+ var observation = hosting.observer().observe(Objects.requireNonNull(fence).binding());
+
+ // The genuine paid hosting preparation and revalidation each acquire the same Account pair.
+ // A separate holder prevents the earlier payer lock from completing. There is no intentional
+ // cycle: another session must still be able to acquire the later caller immediately.
+ try (var workers = Executors.newSingleThreadExecutor()) {
+ for (boolean revalidating : List.of(false, true)) {
+ var waitingPid = new CompletableFuture();
+ var done =
+ transaction.execute(status -> {
+ int holderPid =
+ Objects.requireNonNull(dsl.fetchOne("SELECT pg_backend_pid()"))
+ .get(0, Integer.class);
+ accounts.findByAccountUuidForUpdate(payer).orElseThrow();
+ var worker =
+ workers.submit(() ->
+ transaction.executeWithoutResult(ignored -> {
+ dsl.execute("SET LOCAL lock_timeout = '8s'");
+ waitingPid.complete(
+ Objects.requireNonNull(dsl.fetchOne("SELECT pg_backend_pid()"))
+ .get(0, Integer.class));
+ accounts.lockCanonicalJoinAccounts(tenant, caller);
+ accounts.findByAccountUuidForUpdate(caller).orElseThrow();
+ if (revalidating) {
+ assertThat(lifecycle.readCurrent(fence, observation).gameplayAvailable())
+ .isTrue();
+ } else {
+ assertThat(lifecycle.prepareCurrentRead(tenant).binding())
+ .isEqualTo(fence.binding());
+ }
+ }));
+ int waiter = waitingPid.orTimeout(4, TimeUnit.SECONDS).join();
+ assertThat(waiter).isNotEqualTo(holderPid);
+ long deadline = System.nanoTime() + TimeUnit.SECONDS.toNanos(4);
+ while (!Boolean.TRUE.equals(
+ Objects.requireNonNull(
+ dsl.fetchOne("SELECT ? = ANY(pg_blocking_pids(?))", holderPid, waiter))
+ .get(0, Boolean.class))) {
+ if (System.nanoTime() >= deadline) {
+ throw new AssertionError(
+ "Ordered read did not block on the earlier payer Account");
+ }
+ LockSupport.parkNanos(TimeUnit.MILLISECONDS.toNanos(10));
+ }
+ try (var connection = source.getConnection();
+ var query =
+ connection.prepareStatement(
+ "SELECT account_uuid FROM accounts WHERE account_uuid = ? FOR UPDATE"
+ + " NOWAIT")) {
+ query.setObject(1, caller);
+ try (var selected = query.executeQuery()) {
+ assertThat(selected.next()).isTrue();
+ assertThat(selected.getObject(1, UUID.class)).isEqualTo(caller);
+ }
+ } catch (SQLException failure) {
+ throw new AssertionError(
+ "Earlier payer wait must leave caller Account unlocked", failure);
+ }
+ return worker;
+ });
+ Objects.requireNonNull(done).get(5, TimeUnit.SECONDS);
+ }
+ }
+ }
+
@Test
void paidJoinCommitsOnePlayerEventAuditAndReceiptThenExactlyReplaysWithoutProviderIo() {
Context c = context(false);
@@ -186,6 +335,13 @@ public void beforeCommit(boolean readOnly) {
}
private Context context(boolean wrongPolicy) {
+ return new Context(
+ CanonicalHostingSubscriptionTestFixture.create(migratedSource()),
+ wrongPolicy,
+ invoiceCheckoutDirectory);
+ }
+
+ private DataSource migratedSource() {
String schema = PREFIX + UUID.randomUUID().toString().replace("-", "");
schemas.add(schema);
var source = POSTGRES.dataSource(schema);
@@ -197,10 +353,7 @@ private Context context(boolean wrongPolicy) {
.locations("classpath:db/migration")
.load()
.migrate();
- return new Context(
- CanonicalHostingSubscriptionTestFixture.create(source),
- wrongPolicy,
- invoiceCheckoutDirectory);
+ return source;
}
private static final class Context {
@@ -382,8 +535,8 @@ private List